feat: Phase 6+9 real-time уведомления, CSS Modules, UI-правки

This commit is contained in:
Suslov-MD
2026-08-16 15:28:21 +00:00
parent 476250d5e3
commit 65c44f570c
31 changed files with 1506 additions and 605 deletions
+1 -4
View File
@@ -14,7 +14,7 @@
"react-router-dom": "^7.2.0",
"rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.0",
"socket.io-client": "^4.8.1"
"socket.io-client": "^4.8.3"
},
"devDependencies": {
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
@@ -1986,14 +1986,12 @@
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.31",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
"integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
@@ -3293,7 +3291,6 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT"
},
"node_modules/damerau-levenshtein": {
+1 -1
View File
@@ -16,7 +16,7 @@
"react-router-dom": "^7.2.0",
"rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.0",
"socket.io-client": "^4.8.1"
"socket.io-client": "^4.8.3"
},
"devDependencies": {
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
+15
View File
@@ -28,3 +28,18 @@ export interface NewsItem {
export interface UploadResponse {
file: { url: string; filename: string; size: number };
}
/** Тип уведомления. */
export type NotificationType = 'news.created' | 'news.updated' | 'news.deleted' | 'news.scheduled' | 'news.published';
/** Уведомление (сериализованное от backend). */
export interface NotificationItem {
id: string;
actor: string | null;
type: NotificationType;
news: string | null;
title: string;
message: string;
isRead: boolean;
createdAt: string;
}
+1 -1
View File
@@ -12,7 +12,7 @@ interface MarkdownToolbarProps {
*/
export function MarkdownToolbar({ onAction, onImageUpload, onFileUpload }: MarkdownToolbarProps) {
return (
<div className="markdown-toolbar" role="toolbar" aria-label="Форматирование">
<div role="toolbar" aria-label="Форматирование">
<button type="button" title="Полужирный" onClick={() => { onAction('bold'); }}>
<strong>B</strong>
</button>
@@ -0,0 +1,145 @@
.wrapper {
position: relative;
display: inline-block;
}
.trigger {
background: none;
border: none;
cursor: pointer;
padding: 0.35rem 0.5rem;
border-radius: 6px;
transition: background 0.15s;
&:hover {
background: #f3f4f6;
}
}
.bell {
position: relative;
display: inline-flex;
align-items: center;
font-size: 1.25rem;
}
.badge {
position: absolute;
top: -6px;
right: -10px;
background: #ef4444;
color: #fff;
font-size: 0.65rem;
font-weight: 700;
border-radius: 10px;
padding: 1px 5px;
min-width: 16px;
text-align: center;
line-height: 1.4;
}
.panel {
position: absolute;
top: calc(100% + 0.625rem);
right: 0;
width: 340px;
max-height: 420px;
overflow-y: auto;
background: #fff;
border: 1px solid #e5e7eb;
border-radius: 10px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
z-index: 100;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.875rem 1.25rem;
border-bottom: 1px solid #f3f4f6;
h3 {
margin: 0;
font-size: 0.9rem;
font-weight: 600;
}
}
.markAll {
background: none;
border: none;
color: #3b82f6;
cursor: pointer;
font-size: 0.8rem;
padding: 0;
&:hover {
text-decoration: underline;
}
}
.list {
list-style: none;
margin: 0;
padding: 0.5rem 0;
}
.item {
border-bottom: 1px solid #f9fafb;
&:last-child {
border-bottom: none;
}
&.unread {
background: #f0f7ff;
}
&.read {
opacity: 0.65;
}
}
.itemBtn {
display: block;
width: 100%;
padding: 0.75rem 1.25rem;
border: none;
background: none;
cursor: pointer;
text-align: left;
transition: background 0.1s;
&:hover {
background: #f9fafb;
}
}
.itemTitle {
display: block;
font-size: 0.85rem;
font-weight: 600;
color: #111827;
}
.itemMessage {
display: block;
font-size: 0.82rem;
color: #4b5563;
margin-top: 0.2rem;
}
.itemTime {
display: block;
font-size: 0.72rem;
color: #9ca3af;
margin-top: 0.35rem;
}
.empty {
padding: 2rem 1.25rem;
text-align: center;
color: #9ca3af;
font-size: 0.85rem;
}
+112
View File
@@ -0,0 +1,112 @@
import { useState } from 'react';
import { useNotifications } from '../hooks/useNotifications.js';
import styles from './NotificationBell.module.scss';
import type { NotificationItem } from '../api/types.js';
/**
* Форматирует дату в коротком формате.
*
* @param iso — ISO-дата
* @returns строка вида "16.08 12:30"
*/
function formatDateTime(iso: string): string {
const d = new Date(iso);
const day = String(d.getDate()).padStart(2, '0');
const month = String(d.getMonth() + 1).padStart(2, '0');
const hours = String(d.getHours()).padStart(2, '0');
const minutes = String(d.getMinutes()).padStart(2, '0');
return `${day}.${month} ${hours}:${minutes}`;
}
/**
* Одиночное уведомление в списке.
*/
function NotificationItemRow({
notification, onRead,
}: {
readonly notification: NotificationItem;
readonly onRead: (id: string) => void;
}) {
const cls = notification.isRead ? styles.read : styles.unread;
return (
<li className={`${styles.item} ${cls}`}>
<button
type="button"
className={styles.itemBtn}
onClick={() => { if (!notification.isRead) { onRead(notification.id); } }}
>
<span className={styles.itemTitle}>{notification.title}</span>
<span className={styles.itemMessage}>{notification.message}</span>
<span className={styles.itemTime}>{formatDateTime(notification.createdAt)}</span>
</button>
</li>
);
}
/**
* Компонент колокольчика уведомлений.
*
* Отображает иконку с badge, по клику раскрывает список уведомлений.
* Подключается к Socket.IO для real-time обновлений.
*/
export function NotificationBell({ token }: { readonly token: string | null }) {
const [open, setOpen] = useState(false);
const {
notifications, unreadCount, markAsRead, markAllAsRead,
} = useNotifications(token);
const handleMarkAsRead = (id: string): void => {
markAsRead(id).catch(() => { /* ignore */ });
};
const handleMarkAll = (): void => {
markAllAsRead().catch(() => { /* ignore */ });
};
if (token === null) {
return null;
}
return (
<div className={styles.wrapper}>
<button
type="button"
className={styles.trigger}
onClick={() => { setOpen((v) => !v); }}
aria-label="Уведомления"
>
<span className={styles.bell}>
🔔
{unreadCount > 0 && <span className={styles.badge}>{unreadCount > 99 ? '99+' : String(unreadCount)}</span>}
</span>
</button>
{open ? <div className={styles.panel}>
<div className={styles.header}>
<h3>Уведомления</h3>
{unreadCount > 0
? (
<button type="button" className={styles.markAll} onClick={handleMarkAll}>
Прочитать все
</button>
)
: null}
</div>
{notifications.length === 0
? <p className={styles.empty}>Нет уведомлений</p>
: (
<ul className={styles.list}>
{notifications.map((n) => (
<NotificationItemRow key={n.id} notification={n} onRead={handleMarkAsRead} />
))}
</ul>
)}
</div> : null}
</div>
);
}
+31 -6
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
import { apiFetch, apiUpload } from '../api/client.js';
@@ -10,6 +10,7 @@ import type { UploadResponse } from '../api/types.js';
function useLoadNews(newsId: string | undefined, isNew: boolean) {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [newsStatus, setNewsStatus] = useState<'draft' | 'scheduled' | 'published'>('draft');
const [loading, setLoading] = useState(!isNew);
useEffect(() => {
@@ -20,9 +21,13 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
void (async () => {
try {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- newsId гарантированно string (проверено isNew)
const data = await apiFetch<{ news: { title: string; content: string } }>(`/news/${newsId}`);
const data = await apiFetch<{ news: { title: string; content: string; status: string } }>(`/news/${newsId}`);
setTitle(data.news.title);
setContent(data.news.content);
const s = data.news.status;
if (s === 'draft' || s === 'scheduled' || s === 'published') {
setNewsStatus(s);
}
} catch {
// Ошибка загрузки — остаёмся с пустым состоянием
} finally {
@@ -31,7 +36,7 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
})();
}, [newsId, isNew]);
return { title, setTitle, content, setContent, loading };
return { title, setTitle, content, setContent, newsStatus, loading };
}
/**
@@ -43,7 +48,7 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
/* eslint-disable max-lines-per-function -- хук-оркестратор */
export function useNewsEditor(newsId: string | undefined) {
const isNew = newsId === undefined;
const { title, setTitle, content, setContent, loading } = useLoadNews(newsId, isNew);
const { title, setTitle, content, setContent, newsStatus, loading } = useLoadNews(newsId, isNew);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const [scheduleDate, setScheduleDate] = useState('');
@@ -203,14 +208,34 @@ export function useNewsEditor(newsId: string | undefined) {
if (action === 'link') { insertMarkdown('[', '](https://)'); }
}, [insertMarkdown]);
/** Обработчик file input для изображений. */
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input
e.target.value = '';
}, [handleFileUpload]);
/** Обработчик file input для файлов. */
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input
e.target.value = '';
}, [handleFileUpload]);
return {
isNew, title, setTitle,
content, setContent,
content, setContent, newsStatus,
loading, saving, error,
scheduleDate, setScheduleDate,
textareaRef,
insertMarkdown, handleToolbarAction,
handleFileUpload,
handleFileUpload, onImageChange, onFileChange,
onSave, onPublish, onDelete, onSchedule,
};
}
+89
View File
@@ -0,0 +1,89 @@
import { useCallback, useEffect, useState } from 'react';
import { apiFetch } from '../api/client.js';
import { useSocket } from './useSocket.js';
import type { NotificationItem } from '../api/types.js';
/**
* Хук для управления уведомлениями.
*
* Подписывается на Socket.IO события, загружает список уведомлений,
* предоставляет счётчик непрочитанных и методы отметки.
*
* @param token — JWT токен (null если не авторизован)
* @returns состояние и методы для NotificationBell
*/
export function useNotifications(token: string | null) {
const socket = useSocket(token);
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
/** Загружает список уведомлений и счётчик непрочитанных. */
const fetchNotifications = useCallback(async (): Promise<void> => {
try {
const [listRes, countRes] = await Promise.all([
apiFetch<{ notifications: NotificationItem[] }>('/notifications'),
apiFetch<{ count: number }>('/notifications/unread-count'),
]);
setNotifications(listRes.notifications);
setUnreadCount(countRes.count);
} catch {
// Ошибка загрузки — игнорируем (user может быть offline)
}
}, []);
/** Отмечает одно уведомление как прочитанное. */
const markAsRead = useCallback(async (id: string): Promise<void> => {
try {
await apiFetch(`/notifications/${id}/read`, { method: 'PATCH' });
setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, isRead: true } : n));
setUnreadCount((prev) => Math.max(0, prev - 1));
} catch {
// Игнорируем ошибку
}
}, []);
/** Отмечает все уведомления как прочитанные. */
const markAllAsRead = useCallback(async (): Promise<void> => {
try {
await apiFetch('/notifications/read-all', { method: 'POST' });
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
setUnreadCount(0);
} catch {
// Игнорируем ошибку
}
}, []);
// Загружаем уведомления при монтировании (если авторизован)
useEffect(() => {
if (token !== null) {
fetchNotifications().catch(() => { /* ignore */ });
}
}, [token, fetchNotifications]);
// Подписываемся на real-time уведомления
useEffect(() => {
const onNotification = (data: NotificationItem): void => {
setNotifications((prev) => [data, ...prev]);
setUnreadCount((prev) => prev + 1);
};
if (socket !== null) {
socket.on('notification', onNotification);
return () => {
socket.off('notification', onNotification);
};
}
return undefined;
}, [socket]);
return {
notifications,
unreadCount,
fetchNotifications,
markAsRead,
markAllAsRead,
};
}
+35
View File
@@ -0,0 +1,35 @@
import { useEffect, useState } from 'react';
import { io, type Socket } from 'socket.io-client';
/**
* Подключается к Socket.IO серверу с JWT-аутентификацией.
*
* @param token — JWT токен пользователя
* @param url — URL Socket.IO сервера (по умолчанию — текущий origin)
* @returns socket или null (если не подключено)
*/
export function useSocket(token: string | null, url?: string): Socket | null {
const [socket, setSocket] = useState<Socket | null>(null);
useEffect(() => {
if (token === null || token === '') {
setSocket(null);
return undefined;
}
const socketUrl = url ?? window.location.origin;
const newSocket = io(socketUrl, {
auth: { token },
transports: ['websocket', 'polling'],
});
setSocket(newSocket);
return () => {
newSocket.disconnect();
setSocket(null);
};
}, [token, url]);
return socket;
}
+39
View File
@@ -0,0 +1,39 @@
.page {
max-width: 640px;
margin: 3rem auto;
padding: 3rem 2.5rem;
text-align: center;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
p {
margin-bottom: 1.5rem;
color: #4b5563;
}
}
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.875rem 2rem;
background: #fff;
border-bottom: 1px solid #e5e7eb;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
a {
margin-right: 1.25rem;
font-weight: 500;
}
}
.navRight {
display: flex;
align-items: center;
gap: 1rem;
button {
margin-left: 0.5rem;
}
}
+16 -10
View File
@@ -1,19 +1,23 @@
import { Link } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.js';
import { NotificationBell } from '../components/NotificationBell.js';
import styles from './HomePage.module.scss';
/**
* Главная страница (защищена ProtectedRoute).
* Показывает email пользователя, навигацию и кнопку logout.
*/
export function HomePage() {
const { userEmail, logout } = useAuth();
const { userEmail, token, logout } = useAuth();
return (
<div className="home-page">
<nav className="top-nav">
<>
<nav className={styles.nav}>
<span>News Editor — {userEmail}</span>
<div>
<div className={styles.navRight}>
<NotificationBell token={token} />
<Link to="/news">Мои новости</Link>
<button type="button" onClick={logout}>
Выйти
@@ -21,11 +25,13 @@ export function HomePage() {
</div>
</nav>
<h1>News Editor</h1>
<p>Добро пожаловать, {userEmail}!</p>
<Link to="/news" className="btn btn-primary">
Перейти к новостям
</Link>
</div>
<div className={styles.page}>
<h1>News Editor</h1>
<p>Добро пожаловать, {userEmail}!</p>
<Link to="/news" className="btn btn-primary">
Перейти к новостям
</Link>
</div>
</>
);
}
+11 -9
View File
@@ -1,8 +1,10 @@
import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.js';
import styles from './auth.module.scss';
/**
* Страница логина.
*/
@@ -29,10 +31,10 @@ export function LoginPage() {
/* eslint-enable @typescript-eslint/no-floating-promises */
return (
<div className="auth-page">
<h1>Вход</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<div className={styles.page}>
<h1 className={styles.title}>Вход</h1>
<form className={styles.form} onSubmit={handleSubmit}>
<div className={styles.group}>
<label htmlFor="email">Email</label>
<input
id="email"
@@ -43,7 +45,7 @@ export function LoginPage() {
autoComplete="email"
/>
</div>
<div className="form-group">
<div className={styles.group}>
<label htmlFor="password">Пароль</label>
<input
id="password"
@@ -55,13 +57,13 @@ export function LoginPage() {
/>
</div>
{error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={loading}>
<button type="submit" className={`btn btn-primary ${styles.submit}`} disabled={loading}>
{loading ? 'Вход...' : 'Войти'}
</button>
</form>
<p>
<p className={styles.switch}>
Нет аккаунта?{' '}
<a href="/register">Зарегистрироваться</a>
<Link to="/register">Зарегистрироваться</Link>
</p>
</div>
);
+114
View File
@@ -0,0 +1,114 @@
.page {
max-width: 820px;
margin: 2rem auto;
padding: 2rem 2.5rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
padding-bottom: 1.25rem;
border-bottom: 1px solid #f3f4f6;
flex-wrap: wrap;
gap: 0.75rem 1rem;
h1 {
margin-bottom: 0;
font-size: 1.4rem;
margin-right: auto;
}
}
.actions {
display: flex;
gap: 0.625rem;
flex-wrap: wrap;
}
.titleInput {
font-size: 1.3rem;
font-weight: 600;
margin-bottom: 1.5rem;
border: none;
border-bottom: 2px solid #e5e7eb;
border-radius: 0;
padding: 0.625rem 0;
&:focus {
border-bottom-color: #2563eb;
box-shadow: none;
}
}
.scheduleRow {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1.25rem;
padding: 0.75rem 1rem;
background: #fffbeb;
border: 1px solid #fde68a;
border-radius: 8px;
flex-wrap: wrap;
label {
font-size: 0.9rem;
display: flex;
align-items: center;
gap: 0.5rem;
input {
width: auto;
}
}
}
.toolbar {
display: flex;
gap: 0.25rem;
padding: 0.5rem 0.75rem;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-bottom: none;
border-radius: 6px 6px 0 0;
flex-wrap: wrap;
button {
padding: 0.4rem 0.65rem;
font-size: 0.88rem;
background: transparent;
color: #374151;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background 0.1s;
&:hover {
background: #e5e7eb;
}
}
}
.textarea {
min-height: 320px;
resize: vertical;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 0.9rem;
line-height: 1.7;
border-radius: 0 0 6px 6px;
margin-bottom: 1.5rem;
}
.preview {
padding: 1.5rem 2rem;
border: 1px solid #e5e7eb;
border-radius: 8px;
background: #fafafa;
min-height: 320px;
margin-bottom: 1.5rem;
}
+45 -45
View File
@@ -1,4 +1,4 @@
import { useCallback, useRef, useState, type ChangeEvent, type RefObject } from 'react';
import { useRef, useState, type ChangeEvent, type RefObject } from 'react';
import ReactMarkdown from 'react-markdown';
import { Link, useParams } from 'react-router-dom';
import rehypeSanitize from 'rehype-sanitize';
@@ -7,33 +7,38 @@ import remarkGfm from 'remark-gfm';
import { MarkdownToolbar } from '../components/MarkdownToolbar.js';
import { useNewsEditor } from '../hooks/useNewsEditor.js';
import styles from './NewsEditorPage.module.scss';
/**
* Панель действий редактора (кнопки).
*/
function EditorActions({
isNew, saving, onSave, onPublish, onDelete,
isNew, isPublished, saving, onSave, onPublish, onDelete,
}: {
readonly isNew: boolean;
readonly isPublished: boolean;
readonly saving: boolean;
readonly onSave: () => void;
readonly onPublish: () => void;
readonly onDelete: () => void;
}) {
return (
<div className="editor-actions">
<div className={styles.actions}>
<button type="button" className="btn btn-primary" onClick={onSave} disabled={saving}>
Сохранить
</button>
{!isNew && !isPublished
? (
<button type="button" className="btn btn-publish" onClick={onPublish} disabled={saving}>
Опубликовать
</button>
)
: null}
{!isNew
? (
<>
<button type="button" className="btn btn-publish" onClick={onPublish} disabled={saving}>
Опубликовать
</button>
<button type="button" className="btn btn-delete" onClick={onDelete} disabled={saving}>
Удалить
</button>
</>
<button type="button" className="btn btn-delete" onClick={onDelete} disabled={saving}>
Удалить
</button>
)
: null}
</div>
@@ -52,7 +57,7 @@ function ScheduleRow({
readonly onSchedule: () => void;
}) {
return (
<div className="schedule-row">
<div className={styles.scheduleRow}>
<label>
Отложенная публикация:{' '}
<input
@@ -93,11 +98,13 @@ function EditorForm({
}) {
return (
<>
<MarkdownToolbar onAction={onAction} onImageUpload={onImageUpload} onFileUpload={onFileUpload} />
<div className={styles.toolbar}>
<MarkdownToolbar onAction={onAction} onImageUpload={onImageUpload} onFileUpload={onFileUpload} />
</div>
<textarea
ref={textareaRef}
className="editor-textarea"
className={styles.textarea}
value={content}
onChange={(e) => { setContent(e.target.value); }}
placeholder="Напишите текст в Markdown..."
@@ -127,10 +134,10 @@ function EditorForm({
*/
function EditorPreview({ content }: { readonly content: string }) {
if (content === '') {
return <div className="editor-preview markdown-body"><p className="empty">Нет контента для предпросмотра</p></div>;
return <div className={styles.preview}><p className="empty">Нет контента для предпросмотра</p></div>;
}
return (
<div className="editor-preview markdown-body">
<div className={`${styles.preview} markdown-body`}>
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeSanitize]}>
{content}
</ReactMarkdown>
@@ -143,64 +150,57 @@ function EditorPreview({ content }: { readonly content: string }) {
*/
export function NewsEditorPage() {
const { id } = useParams<{ id: string }>();
const [showPreview, setShowPreview] = useState(false);
const [showPreview, setShowPreview] = useState(id !== undefined);
const fileInputRef = useRef<HTMLInputElement>(null);
const imageInputRef = useRef<HTMLInputElement>(null);
const editor = useNewsEditor(id);
const {
isNew, title, setTitle, content, setContent,
isNew, title, setTitle, content, setContent, newsStatus,
loading, saving, error,
scheduleDate, setScheduleDate, textareaRef,
handleToolbarAction, handleFileUpload,
handleToolbarAction, onImageChange, onFileChange,
onSave, onPublish, onDelete, onSchedule,
} = editor;
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input для повторной загрузки
e.target.value = '';
}, [handleFileUpload]);
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input для повторной загрузки
e.target.value = '';
}, [handleFileUpload]);
if (loading) {
return <p className="loading">Загрузка...</p>;
}
return (
<div className="news-editor">
<div className="editor-header">
<div className={styles.page}>
<div className={styles.header}>
<Link to="/news" className="btn btn-back">← Назад</Link>
<h1>{isNew ? 'Новая новость' : 'Редактирование'}</h1>
<EditorActions isNew={isNew} saving={saving} onSave={onSave} onPublish={onPublish} onDelete={onDelete} />
<button type="button" className="btn" onClick={() => { setShowPreview((v) => !v); }}>
{showPreview ? 'Редактор' : 'Предпросмотр'}
</button>
<EditorActions
isNew={isNew}
isPublished={newsStatus === 'published'}
saving={saving}
onSave={onSave}
onPublish={onPublish}
onDelete={onDelete}
/>
{newsStatus !== 'published'
? (
<button type="button" className="btn" onClick={() => { setShowPreview((v) => !v); }}>
{showPreview ? 'Редактор' : 'Предпросмотр'}
</button>
)
: null}
</div>
{error !== '' && <p className="error">{error}</p>}
<input
type="text"
className="title-input"
className={styles.titleInput}
placeholder="Заголовок..."
value={title}
onChange={(e) => { setTitle(e.target.value); }}
/>
{!isNew
{!isNew && newsStatus !== 'published'
? (
<ScheduleRow
scheduleDate={scheduleDate}
+104
View File
@@ -0,0 +1,104 @@
.page {
max-width: 720px;
margin: 2rem auto;
padding: 2rem 2.5rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
padding-bottom: 1rem;
border-bottom: 1px solid #f3f4f6;
h1 {
font-size: 1.4rem;
margin-bottom: 0;
}
}
.list {
list-style: none;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.card {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 1rem;
padding: 1rem 1.25rem;
background: #fafbfc;
border: 1px solid #f3f4f6;
border-radius: 8px;
transition: box-shadow 0.15s, border-color 0.15s;
&:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
border-color: #e5e7eb;
}
}
.cardBody {
flex: 1;
min-width: 0;
}
.cardTitle {
font-weight: 600;
display: block;
margin-bottom: 0.25rem;
}
.cardPreview {
font-size: 0.85rem;
color: #6b7280;
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.cardMeta {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 0.35rem;
flex-shrink: 0;
}
.cardDate {
font-size: 0.78rem;
color: #9ca3af;
}
.badge {
font-size: 0.72rem;
padding: 0.2rem 0.55rem;
border-radius: 4px;
font-weight: 600;
white-space: nowrap;
&.draft {
background: #f3f4f6;
color: #6b7280;
}
&.scheduled {
background: #fef3c7;
color: #92400e;
}
&.published {
background: #d1fae5;
color: #065f46;
}
}
+23 -11
View File
@@ -3,8 +3,11 @@ import { Link } from 'react-router-dom';
import { apiFetch } from '../api/client.js';
import styles from './NewsListPage.module.scss';
import type { NewsItem } from '../api/types.js';
/**
* Страница со списком новостей текущего пользователя.
*/
@@ -32,8 +35,8 @@ export function NewsListPage() {
}
return (
<div className="news-list">
<div className="news-list-header">
<div className={styles.page}>
<div className={styles.header}>
<h1>Мои новости</h1>
<Link to="/news/new" className="btn btn-primary">
+ Создать
@@ -45,16 +48,25 @@ export function NewsListPage() {
{news.length === 0
? <p className="empty">Нет новостей. Создайте первую!</p>
: (
<ul className="news-cards">
<ul className={styles.list}>
{news.map((item) => (
<li key={item.id} className="news-card">
<Link to={`/news/${item.id}`} className="news-card-title">
{item.title !== '' ? item.title : '(без названия)'}
</Link>
<span className={`badge badge-${item.status}`}>{item.status}</span>
<span className="news-card-date">
{new Date(item.updatedAt).toLocaleString('ru-RU')}
</span>
<li key={item.id} className={styles.card}>
<div className={styles.cardBody}>
<Link to={`/news/${item.id}`} className={styles.cardTitle}>
{item.title !== '' ? item.title : '(без названия)'}
</Link>
{item.content !== '' && (
<p className={styles.cardPreview}>
{item.content.replace(/[#*`[\]!\n]/g, '').slice(0, 120)}
</p>
)}
</div>
<div className={styles.cardMeta}>
<span className={`${styles.badge} ${styles[item.status]}`}>{item.status}</span>
<span className={styles.cardDate}>
{new Date(item.updatedAt).toLocaleString('ru-RU')}
</span>
</div>
</li>
))}
</ul>
+12 -10
View File
@@ -1,8 +1,10 @@
import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.js';
import styles from './auth.module.scss';
/**
* Страница регистрации.
*/
@@ -34,10 +36,10 @@ export function RegisterPage() {
/* eslint-enable @typescript-eslint/no-floating-promises */
return (
<div className="auth-page">
<h1>Регистрация</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<div className={styles.page}>
<h1 className={styles.title}>Регистрация</h1>
<form className={styles.form} onSubmit={handleSubmit}>
<div className={styles.group}>
<label htmlFor="email">Email</label>
<input
id="email"
@@ -48,7 +50,7 @@ export function RegisterPage() {
autoComplete="email"
/>
</div>
<div className="form-group">
<div className={styles.group}>
<label htmlFor="password">Пароль</label>
<input
id="password"
@@ -60,7 +62,7 @@ export function RegisterPage() {
autoComplete="new-password"
/>
</div>
<div className="form-group">
<div className={styles.group}>
<label htmlFor="confirmPassword">Повторите пароль</label>
<input
id="confirmPassword"
@@ -72,13 +74,13 @@ export function RegisterPage() {
/>
</div>
{error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={loading}>
<button type="submit" className={`btn btn-primary ${styles.submit}`} disabled={loading}>
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
</button>
</form>
<p>
<p className={styles.switch}>
Уже есть аккаунт?{' '}
<a href="/login">Войти</a>
<Link to="/login">Войти</Link>
</p>
</div>
);
+46
View File
@@ -0,0 +1,46 @@
.page {
max-width: 400px;
margin: 3rem auto;
padding: 2rem 2.5rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}
.title {
font-size: 1.4rem;
margin-bottom: 1.5rem;
text-align: center;
}
.form {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.group {
display: flex;
flex-direction: column;
gap: 0.35rem;
label {
font-weight: 500;
font-size: 0.9rem;
}
}
.submit {
margin-top: 0.5rem;
}
.switch {
margin-top: 1.5rem;
text-align: center;
font-size: 0.9rem;
color: #6b7280;
a {
margin-left: 0.25rem;
}
}
+34 -249
View File
@@ -1,4 +1,4 @@
// Глобальные стили News Editor
// Глобальные стили News Editor (base + shared utilities)
* {
box-sizing: border-box;
@@ -10,7 +10,7 @@ body {
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6;
color: #1a1a2e;
background: #f5f5f5;
background: #f0f2f5;
}
a {
@@ -27,25 +27,6 @@ h1 {
font-size: 1.8rem;
}
button {
padding: 0.5rem 1.2rem;
border: none;
border-radius: 6px;
background: #2563eb;
color: #fff;
font-size: 0.95rem;
cursor: pointer;
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
&:hover:not(:disabled) {
background: #1d4ed8;
}
}
input,
textarea {
width: 100%;
@@ -62,7 +43,7 @@ textarea {
}
}
// Кнопки
// === Shared: Кнопки ===
.btn {
display: inline-block;
padding: 0.5rem 1.2rem;
@@ -73,17 +54,23 @@ textarea {
text-decoration: none;
background: #e5e7eb;
color: #1a1a2e;
transition: background 0.15s;
&:hover {
background: #d1d5db;
text-decoration: none;
}
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
&-primary {
background: #2563eb;
color: #fff;
&:hover {
&:hover:not(:disabled) {
background: #1d4ed8;
}
}
@@ -92,7 +79,7 @@ textarea {
background: #16a34a;
color: #fff;
&:hover {
&:hover:not(:disabled) {
background: #15803d;
}
}
@@ -101,7 +88,7 @@ textarea {
background: #f59e0b;
color: #fff;
&:hover {
&:hover:not(:disabled) {
background: #d97706;
}
}
@@ -110,7 +97,7 @@ textarea {
background: #dc2626;
color: #fff;
&:hover {
&:hover:not(:disabled) {
background: #b91c1c;
}
}
@@ -119,37 +106,21 @@ textarea {
background: transparent;
color: #2563eb;
&:hover {
&:hover:not(:disabled) {
background: #eff6ff;
}
}
}
// Страница авторизации
.auth-page {
max-width: 400px;
margin: 4rem auto;
padding: 2rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.form-group {
margin-bottom: 1rem;
label {
display: block;
margin-bottom: 0.25rem;
font-weight: 500;
font-size: 0.9rem;
}
}
// === Shared: Error / Loading / Empty ===
.error {
color: #dc2626;
font-size: 0.9rem;
margin-bottom: 0.75rem;
margin-bottom: 1rem;
padding: 0.5rem 0.75rem;
background: #fef2f2;
border-radius: 6px;
border: 1px solid #fecaca;
}
.loading,
@@ -158,219 +129,32 @@ textarea {
font-style: italic;
}
// Навигация
.top-nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem 1.5rem;
background: #fff;
border-bottom: 1px solid #e5e7eb;
a {
margin-right: 1rem;
}
button {
margin-left: 0.5rem;
}
}
// Главная страница
.home-page {
max-width: 600px;
margin: 2rem auto;
padding: 2rem;
text-align: center;
p {
margin-bottom: 1.5rem;
}
}
// Список новостей
.news-list {
max-width: 700px;
margin: 2rem auto;
padding: 1.5rem;
&-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
}
}
.news-cards {
list-style: none;
.news-card {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 1rem;
background: #fff;
border-radius: 8px;
margin-bottom: 0.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
&-title {
flex: 1;
font-weight: 600;
}
&-date {
font-size: 0.8rem;
color: #6b7280;
}
}
}
.badge {
font-size: 0.75rem;
padding: 0.15rem 0.5rem;
border-radius: 4px;
font-weight: 500;
&-draft {
background: #f3f4f6;
color: #6b7280;
}
&-scheduled {
background: #fef3c7;
color: #92400e;
}
&-published {
background: #d1fae5;
color: #065f46;
}
}
// Редактор
.news-editor {
max-width: 800px;
margin: 1.5rem auto;
padding: 1.5rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
&-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
flex-wrap: wrap;
gap: 0.5rem;
h1 {
margin-bottom: 0;
font-size: 1.4rem;
}
}
&-actions {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
}
.title-input {
font-size: 1.3rem;
font-weight: 600;
margin-bottom: 1rem;
border: none;
border-bottom: 2px solid #e5e7eb;
border-radius: 0;
padding: 0.5rem 0;
&:focus {
border-bottom-color: #2563eb;
box-shadow: none;
}
}
.schedule-row {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
flex-wrap: wrap;
label {
font-size: 0.9rem;
display: flex;
align-items: center;
gap: 0.5rem;
input {
width: auto;
}
}
}
// Markdown toolbar
.markdown-toolbar {
display: flex;
gap: 0.25rem;
padding: 0.5rem;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-bottom: none;
border-radius: 6px 6px 0 0;
button {
padding: 0.35rem 0.6rem;
font-size: 0.9rem;
background: transparent;
color: #374151;
border-radius: 4px;
&:hover {
background: #e5e7eb;
}
}
}
.editor-textarea {
min-height: 300px;
resize: vertical;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 0.9rem;
border-radius: 0 0 6px 6px;
margin-bottom: 1rem;
}
// Markdown preview
// === Markdown body (используется в preview) ===
.markdown-body {
padding: 1.5rem;
border: 1px solid #e5e7eb;
border-radius: 6px;
background: #fafafa;
min-height: 300px;
h1, h2, h3 {
margin: 1rem 0 0.5rem;
margin: 1.25rem 0 0.5rem;
&:first-child {
margin-top: 0;
}
}
p {
margin-bottom: 0.75rem;
margin-bottom: 0.875rem;
}
blockquote {
border-left: 4px solid #2563eb;
padding-left: 1rem;
padding: 0.5rem 1rem;
margin: 1rem 0;
color: #4b5563;
background: #f8faff;
border-radius: 0 4px 4px 0;
}
code {
background: #f3f4f6;
padding: 0.15rem 0.35rem;
padding: 0.15rem 0.4rem;
border-radius: 3px;
font-size: 0.85em;
}
@@ -378,7 +162,7 @@ textarea {
pre {
background: #1f2937;
color: #e5e7eb;
padding: 1rem;
padding: 1.25rem 1.5rem;
border-radius: 6px;
overflow-x: auto;
margin: 1rem 0;
@@ -402,12 +186,13 @@ textarea {
th, td {
border: 1px solid #e5e7eb;
padding: 0.5rem;
padding: 0.6rem 0.75rem;
text-align: left;
}
th {
background: #f9fafb;
font-weight: 600;
}
}
}