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
+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;
}