diff --git a/client/src/App.tsx b/client/src/App.tsx
index 6866ce8..f4db188 100644
--- a/client/src/App.tsx
+++ b/client/src/App.tsx
@@ -4,6 +4,8 @@ import { AuthProvider } from './auth/AuthContext.js';
import { ProtectedRoute } from './components/ProtectedRoute.js';
import { HomePage } from './pages/HomePage.js';
import { LoginPage } from './pages/LoginPage.js';
+import { NewsEditorPage } from './pages/NewsEditorPage.js';
+import { NewsListPage } from './pages/NewsListPage.js';
import { RegisterPage } from './pages/RegisterPage.js';
/**
@@ -18,6 +20,9 @@ export function App() {
} />
}>
} />
+ } />
+ } />
+ } />
} />
diff --git a/client/src/api/types.ts b/client/src/api/types.ts
index a8a342f..9e7469d 100644
--- a/client/src/api/types.ts
+++ b/client/src/api/types.ts
@@ -1,5 +1,5 @@
/**
- * Типы для API-ответов авторизации.
+ * Типы для API-ответов авторизации и новостей.
*/
/** Ответ на регистрацию/логин. */
@@ -7,3 +7,24 @@ export interface AuthResponse {
token: string;
user: { id: string; email: string };
}
+
+/** Статус новости. */
+export type NewsStatus = 'draft' | 'scheduled' | 'published';
+
+/** Новость (сериализованная от backend). */
+export interface NewsItem {
+ id: string;
+ title: string;
+ content: string;
+ status: NewsStatus;
+ author: string;
+ publishedAt: string | null;
+ scheduledAt: string | null;
+ createdAt: string;
+ updatedAt: string;
+}
+
+/** Ответ на upload. */
+export interface UploadResponse {
+ file: { url: string; filename: string; size: number };
+}
diff --git a/client/src/components/MarkdownToolbar.tsx b/client/src/components/MarkdownToolbar.tsx
new file mode 100644
index 0000000..227ad73
--- /dev/null
+++ b/client/src/components/MarkdownToolbar.tsx
@@ -0,0 +1,42 @@
+interface MarkdownToolbarProps {
+ /** Вызывается при нажатии кнопки с именем действия. */
+ readonly onAction: (action: string) => void;
+ /** Вызывается при нажатии "Вставить изображение". */
+ readonly onImageUpload: () => void;
+ /** Вызывается при нажатии "Вставить файл". */
+ readonly onFileUpload: () => void;
+}
+
+/**
+ * Панель инструментов Markdown-редактора.
+ */
+export function MarkdownToolbar({ onAction, onImageUpload, onFileUpload }: MarkdownToolbarProps) {
+ return (
+
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/client/src/hooks/useNewsEditor.ts b/client/src/hooks/useNewsEditor.ts
new file mode 100644
index 0000000..442feb2
--- /dev/null
+++ b/client/src/hooks/useNewsEditor.ts
@@ -0,0 +1,217 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { apiFetch, apiUpload } from '../api/client.js';
+
+import type { UploadResponse } from '../api/types.js';
+
+/**
+ * Загружает существующую новость из API.
+ */
+function useLoadNews(newsId: string | undefined, isNew: boolean) {
+ const [title, setTitle] = useState('');
+ const [content, setContent] = useState('');
+ const [loading, setLoading] = useState(!isNew);
+
+ useEffect(() => {
+ if (isNew) {
+ return;
+ }
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises -- async IIFE в useEffect
+ 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}`);
+ setTitle(data.news.title);
+ setContent(data.news.content);
+ } catch {
+ // Ошибка загрузки — остаёмся с пустым состоянием
+ } finally {
+ setLoading(false);
+ }
+ })();
+ }, [newsId, isNew]);
+
+ return { title, setTitle, content, setContent, loading };
+}
+
+/**
+ * Хук для управления состоянием и действиями редактора новости.
+ *
+ * @param newsId — id новости или undefined для создания
+ * @returns состояние и обработчики для NewsEditorPage
+ */
+/* 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 [saving, setSaving] = useState(false);
+ const [error, setError] = useState('');
+ const [scheduleDate, setScheduleDate] = useState('');
+ const textareaRef = useRef(null);
+
+ /** Вставляет markdown-фрагмент в textarea на позиции курсора. */
+ const insertMarkdown = useCallback((before: string, after = ''): void => {
+ const ta = textareaRef.current;
+ if (ta === null) {
+ return;
+ }
+ const start = ta.selectionStart;
+ const end = ta.selectionEnd;
+ const selected = content.substring(start, end);
+ const newContent = content.substring(0, start) + before + selected + after + content.substring(end);
+ setContent(newContent);
+ requestAnimationFrame(() => {
+ ta.focus();
+ const newCursor = start + before.length + selected.length + after.length;
+ ta.setSelectionRange(newCursor, newCursor);
+ });
+ }, [content, setContent]);
+
+ /** Сохраняет черновик. */
+ const handleSave = useCallback(async (): Promise => {
+ setSaving(true);
+ setError('');
+ try {
+ if (isNew) {
+ await apiFetch('/news', {
+ method: 'POST',
+ body: JSON.stringify({ title, content }),
+ });
+
+ window.location.href = '/news';
+ } else {
+ await apiFetch(`/news/${newsId}`, {
+ method: 'PATCH',
+ body: JSON.stringify({ title, content }),
+ });
+ setError('Сохранено ✓');
+ setTimeout(() => { setError(''); }, 2000);
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Ошибка сохранения');
+ } finally {
+ setSaving(false);
+ }
+ }, [isNew, newsId, title, content]);
+
+ /** Публикует немедленно. */
+ const handlePublish = useCallback(async (): Promise => {
+ if (newsId === undefined) {
+ setError('Сначала сохраните черновик');
+ return;
+ }
+ setSaving(true);
+ setError('');
+ try {
+ await apiFetch(`/news/${newsId}/publish`, { method: 'POST' });
+
+ window.location.href = '/news';
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Ошибка публикации');
+ } finally {
+ setSaving(false);
+ }
+ }, [newsId]);
+
+ /** Планирует публикацию. */
+ const handleSchedule = useCallback(async (): Promise => {
+ if (newsId === undefined) {
+ setError('Сначала сохраните черновик');
+ return;
+ }
+ if (scheduleDate === '') {
+ setError('Выберите дату публикации');
+ return;
+ }
+ setSaving(true);
+ setError('');
+ try {
+ await apiFetch(`/news/${newsId}/schedule`, {
+ method: 'POST',
+ body: JSON.stringify({ scheduledAt: scheduleDate }),
+ });
+
+ window.location.href = '/news';
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Ошибка планирования');
+ } finally {
+ setSaving(false);
+ }
+ }, [newsId, scheduleDate]);
+
+ /** Удаляет новость. */
+ const handleDelete = useCallback(async (): Promise => {
+ if (newsId === undefined) {
+ return;
+ }
+ // eslint-disable-next-line no-alert -- подтверждение удаления
+ if (!window.confirm('Удалить новость?')) {
+ return;
+ }
+ setSaving(true);
+ setError('');
+ try {
+ await apiFetch(`/news/${newsId}`, { method: 'DELETE' });
+ // eslint-disable-next-line require-atomic-updates -- navigation after await
+ window.location.href = '/news';
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Ошибка удаления');
+ } finally {
+ setSaving(false);
+ }
+ }, [newsId]);
+
+ /** Загружает файл и вставляет markdown-ссылку. */
+ const handleFileUpload = useCallback(async (file: File, isImage: boolean): Promise => {
+ const formData = new FormData();
+ formData.append('file', file);
+ try {
+ const res = await apiUpload('/uploads', formData);
+ const md = isImage
+ ? `\n\n`
+ : `\n[${file.name}](${res.file.url})\n`;
+ insertMarkdown(md);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Ошибка загрузки');
+ }
+ }, [insertMarkdown]);
+
+ // Обёртки для onClick: .catch() чтобы не триггерить no-floating-promises
+ const onSave = useCallback((): void => {
+ handleSave().catch((e: unknown) => { console.error('Save failed', e); });
+ }, [handleSave]);
+
+ const onPublish = useCallback((): void => {
+ handlePublish().catch((e: unknown) => { console.error('Publish failed', e); });
+ }, [handlePublish]);
+
+ const onDelete = useCallback((): void => {
+ handleDelete().catch((e: unknown) => { console.error('Delete failed', e); });
+ }, [handleDelete]);
+
+ const onSchedule = useCallback((): void => {
+ handleSchedule().catch((e: unknown) => { console.error('Schedule failed', e); });
+ }, [handleSchedule]);
+
+ /** Обработчик toolbar-кнопок. */
+ const handleToolbarAction = useCallback((action: string): void => {
+ if (action === 'bold') { insertMarkdown('**', '**'); }
+ if (action === 'italic') { insertMarkdown('*', '*'); }
+ if (action === 'heading') { insertMarkdown('# ', ''); }
+ if (action === 'quote') { insertMarkdown('> ', ''); }
+ if (action === 'code') { insertMarkdown('\n```\n', '\n```\n'); }
+ if (action === 'link') { insertMarkdown('[', '](https://)'); }
+ }, [insertMarkdown]);
+
+ return {
+ isNew, title, setTitle,
+ content, setContent,
+ loading, saving, error,
+ scheduleDate, setScheduleDate,
+ textareaRef,
+ insertMarkdown, handleToolbarAction,
+ handleFileUpload,
+ onSave, onPublish, onDelete, onSchedule,
+ };
+}
+/* eslint-enable max-lines-per-function */
diff --git a/client/src/pages/HomePage.tsx b/client/src/pages/HomePage.tsx
index 64eb7fb..d40f722 100644
--- a/client/src/pages/HomePage.tsx
+++ b/client/src/pages/HomePage.tsx
@@ -1,19 +1,31 @@
+import { Link } from 'react-router-dom';
+
import { useAuth } from '../auth/AuthContext.js';
/**
- * Главная страница (защитена ProtectedRoute).
- * Показывает email пользователя и кнопку logout.
+ * Главная страница (защищена ProtectedRoute).
+ * Показывает email пользователя, навигацию и кнопку logout.
*/
export function HomePage() {
const { userEmail, logout } = useAuth();
return (
+
+
News Editor
Добро пожаловать, {userEmail}!
-
+
+ Перейти к новостям
+
);
}
diff --git a/client/src/pages/NewsEditorPage.tsx b/client/src/pages/NewsEditorPage.tsx
new file mode 100644
index 0000000..0567eb5
--- /dev/null
+++ b/client/src/pages/NewsEditorPage.tsx
@@ -0,0 +1,232 @@
+import { useCallback, 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';
+import remarkGfm from 'remark-gfm';
+
+import { MarkdownToolbar } from '../components/MarkdownToolbar.js';
+import { useNewsEditor } from '../hooks/useNewsEditor.js';
+
+/**
+ * Панель действий редактора (кнопки).
+ */
+function EditorActions({
+ isNew, saving, onSave, onPublish, onDelete,
+}: {
+ readonly isNew: boolean;
+ readonly saving: boolean;
+ readonly onSave: () => void;
+ readonly onPublish: () => void;
+ readonly onDelete: () => void;
+}) {
+ return (
+
+
+ {!isNew
+ ? (
+ <>
+
+
+ >
+ )
+ : null}
+
+ );
+}
+
+/**
+ * Строка отложенной публикации.
+ */
+function ScheduleRow({
+ scheduleDate, setScheduleDate, saving, onSchedule,
+}: {
+ readonly scheduleDate: string;
+ readonly setScheduleDate: (v: string) => void;
+ readonly saving: boolean;
+ readonly onSchedule: () => void;
+}) {
+ return (
+
+
+
+
+ );
+}
+
+/**
+ * Форма редактора (toolbar + textarea + file inputs).
+ */
+function EditorForm({
+ content, setContent, textareaRef, onAction, onImageUpload, onFileUpload, onImageChange, onFileChange,
+ imageInputRef, fileInputRef,
+}: {
+ readonly content: string;
+ readonly setContent: (v: string) => void;
+ readonly textareaRef: RefObject;
+ readonly onAction: (action: string) => void;
+ readonly onImageUpload: () => void;
+ readonly onFileUpload: () => void;
+ readonly onImageChange: (e: ChangeEvent) => void;
+ readonly onFileChange: (e: ChangeEvent) => void;
+ readonly imageInputRef: RefObject;
+ readonly fileInputRef: RefObject;
+}) {
+ return (
+ <>
+
+
+