feat(client): Phase 8 — markdown editor, news list, toolbar, preview, upload, publish
This commit is contained in:
@@ -4,6 +4,8 @@ import { AuthProvider } from './auth/AuthContext.js';
|
|||||||
import { ProtectedRoute } from './components/ProtectedRoute.js';
|
import { ProtectedRoute } from './components/ProtectedRoute.js';
|
||||||
import { HomePage } from './pages/HomePage.js';
|
import { HomePage } from './pages/HomePage.js';
|
||||||
import { LoginPage } from './pages/LoginPage.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';
|
import { RegisterPage } from './pages/RegisterPage.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -18,6 +20,9 @@ export function App() {
|
|||||||
<Route path="/register" element={<RegisterPage />} />
|
<Route path="/register" element={<RegisterPage />} />
|
||||||
<Route element={<ProtectedRoute />}>
|
<Route element={<ProtectedRoute />}>
|
||||||
<Route path="/" element={<HomePage />} />
|
<Route path="/" element={<HomePage />} />
|
||||||
|
<Route path="/news" element={<NewsListPage />} />
|
||||||
|
<Route path="/news/new" element={<NewsEditorPage />} />
|
||||||
|
<Route path="/news/:id" element={<NewsEditorPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
+22
-1
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Типы для API-ответов авторизации.
|
* Типы для API-ответов авторизации и новостей.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** Ответ на регистрацию/логин. */
|
/** Ответ на регистрацию/логин. */
|
||||||
@@ -7,3 +7,24 @@ export interface AuthResponse {
|
|||||||
token: string;
|
token: string;
|
||||||
user: { id: string; email: 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 };
|
||||||
|
}
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<div className="markdown-toolbar" role="toolbar" aria-label="Форматирование">
|
||||||
|
<button type="button" title="Полужирный" onClick={() => { onAction('bold'); }}>
|
||||||
|
<strong>B</strong>
|
||||||
|
</button>
|
||||||
|
<button type="button" title="Курсив" onClick={() => { onAction('italic'); }}>
|
||||||
|
<em>I</em>
|
||||||
|
</button>
|
||||||
|
<button type="button" title="Заголовок" onClick={() => { onAction('heading'); }}>
|
||||||
|
H
|
||||||
|
</button>
|
||||||
|
<button type="button" title="Цитата" onClick={() => { onAction('quote'); }}>
|
||||||
|
""
|
||||||
|
</button>
|
||||||
|
<button type="button" title="Блок кода" onClick={() => { onAction('code'); }}>
|
||||||
|
{'</>'}
|
||||||
|
</button>
|
||||||
|
<button type="button" title="Ссылка" onClick={() => { onAction('link'); }}>
|
||||||
|
🔗
|
||||||
|
</button>
|
||||||
|
<button type="button" title="Вставить изображение" onClick={() => { onImageUpload(); }}>
|
||||||
|
🖼️
|
||||||
|
</button>
|
||||||
|
<button type="button" title="Вставить файл" onClick={() => { onFileUpload(); }}>
|
||||||
|
📎
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<HTMLTextAreaElement>(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<void> => {
|
||||||
|
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<void> => {
|
||||||
|
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<void> => {
|
||||||
|
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<void> => {
|
||||||
|
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<void> => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
try {
|
||||||
|
const res = await apiUpload<UploadResponse>('/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 */
|
||||||
@@ -1,19 +1,31 @@
|
|||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
|
||||||
import { useAuth } from '../auth/AuthContext.js';
|
import { useAuth } from '../auth/AuthContext.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Главная страница (защитена ProtectedRoute).
|
* Главная страница (защищена ProtectedRoute).
|
||||||
* Показывает email пользователя и кнопку logout.
|
* Показывает email пользователя, навигацию и кнопку logout.
|
||||||
*/
|
*/
|
||||||
export function HomePage() {
|
export function HomePage() {
|
||||||
const { userEmail, logout } = useAuth();
|
const { userEmail, logout } = useAuth();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="home-page">
|
<div className="home-page">
|
||||||
|
<nav className="top-nav">
|
||||||
|
<span>News Editor — {userEmail}</span>
|
||||||
|
<div>
|
||||||
|
<Link to="/news">Мои новости</Link>
|
||||||
|
<button type="button" onClick={logout}>
|
||||||
|
Выйти
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
<h1>News Editor</h1>
|
<h1>News Editor</h1>
|
||||||
<p>Добро пожаловать, {userEmail}!</p>
|
<p>Добро пожаловать, {userEmail}!</p>
|
||||||
<button type="button" onClick={logout}>
|
<Link to="/news" className="btn btn-primary">
|
||||||
Выйти
|
Перейти к новостям
|
||||||
</button>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<div className="editor-actions">
|
||||||
|
<button type="button" className="btn btn-primary" onClick={onSave} disabled={saving}>
|
||||||
|
Сохранить
|
||||||
|
</button>
|
||||||
|
{!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>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Строка отложенной публикации.
|
||||||
|
*/
|
||||||
|
function ScheduleRow({
|
||||||
|
scheduleDate, setScheduleDate, saving, onSchedule,
|
||||||
|
}: {
|
||||||
|
readonly scheduleDate: string;
|
||||||
|
readonly setScheduleDate: (v: string) => void;
|
||||||
|
readonly saving: boolean;
|
||||||
|
readonly onSchedule: () => void;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="schedule-row">
|
||||||
|
<label>
|
||||||
|
Отложенная публикация:{' '}
|
||||||
|
<input
|
||||||
|
type="datetime-local"
|
||||||
|
value={scheduleDate}
|
||||||
|
onChange={(e) => { setScheduleDate(e.target.value); }}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-schedule"
|
||||||
|
onClick={onSchedule}
|
||||||
|
disabled={saving || scheduleDate === ''}
|
||||||
|
>
|
||||||
|
Запланировать
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Форма редактора (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<HTMLTextAreaElement>;
|
||||||
|
readonly onAction: (action: string) => void;
|
||||||
|
readonly onImageUpload: () => void;
|
||||||
|
readonly onFileUpload: () => void;
|
||||||
|
readonly onImageChange: (e: ChangeEvent<HTMLInputElement>) => void;
|
||||||
|
readonly onFileChange: (e: ChangeEvent<HTMLInputElement>) => void;
|
||||||
|
readonly imageInputRef: RefObject<HTMLInputElement>;
|
||||||
|
readonly fileInputRef: RefObject<HTMLInputElement>;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<MarkdownToolbar onAction={onAction} onImageUpload={onImageUpload} onFileUpload={onFileUpload} />
|
||||||
|
|
||||||
|
<textarea
|
||||||
|
ref={textareaRef}
|
||||||
|
className="editor-textarea"
|
||||||
|
value={content}
|
||||||
|
onChange={(e) => { setContent(e.target.value); }}
|
||||||
|
placeholder="Напишите текст в Markdown..."
|
||||||
|
rows={20}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<input
|
||||||
|
ref={imageInputRef}
|
||||||
|
type="file"
|
||||||
|
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||||
|
style={{ display: 'none' }}
|
||||||
|
onChange={onImageChange}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||||
|
style={{ display: 'none' }}
|
||||||
|
onChange={onFileChange}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Предпросмотр markdown.
|
||||||
|
*/
|
||||||
|
function EditorPreview({ content }: { readonly content: string }) {
|
||||||
|
if (content === '') {
|
||||||
|
return <div className="editor-preview markdown-body"><p className="empty">Нет контента для предпросмотра</p></div>;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="editor-preview markdown-body">
|
||||||
|
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeSanitize]}>
|
||||||
|
{content}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Страница редактирования/создания новости с Markdown-редактором.
|
||||||
|
*/
|
||||||
|
export function NewsEditorPage() {
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const [showPreview, setShowPreview] = useState(false);
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const imageInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const editor = useNewsEditor(id);
|
||||||
|
|
||||||
|
const {
|
||||||
|
isNew, title, setTitle, content, setContent,
|
||||||
|
loading, saving, error,
|
||||||
|
scheduleDate, setScheduleDate, textareaRef,
|
||||||
|
handleToolbarAction, handleFileUpload,
|
||||||
|
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">
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error !== '' && <p className="error">{error}</p>}
|
||||||
|
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="title-input"
|
||||||
|
placeholder="Заголовок..."
|
||||||
|
value={title}
|
||||||
|
onChange={(e) => { setTitle(e.target.value); }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{!isNew
|
||||||
|
? (
|
||||||
|
<ScheduleRow
|
||||||
|
scheduleDate={scheduleDate}
|
||||||
|
setScheduleDate={setScheduleDate}
|
||||||
|
saving={saving}
|
||||||
|
onSchedule={onSchedule}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
: null}
|
||||||
|
|
||||||
|
{showPreview
|
||||||
|
? <EditorPreview content={content} />
|
||||||
|
: (
|
||||||
|
<EditorForm
|
||||||
|
content={content}
|
||||||
|
setContent={setContent}
|
||||||
|
textareaRef={textareaRef}
|
||||||
|
onAction={handleToolbarAction}
|
||||||
|
onImageUpload={() => { imageInputRef.current?.click(); }}
|
||||||
|
onFileUpload={() => { fileInputRef.current?.click(); }}
|
||||||
|
onImageChange={onImageChange}
|
||||||
|
onFileChange={onFileChange}
|
||||||
|
imageInputRef={imageInputRef}
|
||||||
|
fileInputRef={fileInputRef}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
|
||||||
|
import { apiFetch } from '../api/client.js';
|
||||||
|
|
||||||
|
import type { NewsItem } from '../api/types.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Страница со списком новостей текущего пользователя.
|
||||||
|
*/
|
||||||
|
export function NewsListPage() {
|
||||||
|
const [news, setNews] = useState<NewsItem[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- async IIFE в useEffect
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const data = await apiFetch<{ news: NewsItem[] }>('/news');
|
||||||
|
setNews(data.news);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Ошибка загрузки');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <p className="loading">Загрузка...</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="news-list">
|
||||||
|
<div className="news-list-header">
|
||||||
|
<h1>Мои новости</h1>
|
||||||
|
<Link to="/news/new" className="btn btn-primary">
|
||||||
|
+ Создать
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error !== '' && <p className="error">{error}</p>}
|
||||||
|
|
||||||
|
{news.length === 0
|
||||||
|
? <p className="empty">Нет новостей. Создайте первую!</p>
|
||||||
|
: (
|
||||||
|
<ul className="news-cards">
|
||||||
|
{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>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -46,12 +46,14 @@ button {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
input {
|
input,
|
||||||
|
textarea {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
padding: 0.5rem 0.75rem;
|
padding: 0.5rem 0.75rem;
|
||||||
border: 1px solid #d1d5db;
|
border: 1px solid #d1d5db;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
font-size: 0.95rem;
|
font-size: 0.95rem;
|
||||||
|
font-family: inherit;
|
||||||
|
|
||||||
&:focus {
|
&:focus {
|
||||||
outline: none;
|
outline: none;
|
||||||
@@ -60,6 +62,69 @@ input {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Кнопки
|
||||||
|
.btn {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0.5rem 1.2rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
cursor: pointer;
|
||||||
|
text-decoration: none;
|
||||||
|
background: #e5e7eb;
|
||||||
|
color: #1a1a2e;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #d1d5db;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
&-primary {
|
||||||
|
background: #2563eb;
|
||||||
|
color: #fff;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #1d4ed8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&-publish {
|
||||||
|
background: #16a34a;
|
||||||
|
color: #fff;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #15803d;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&-schedule {
|
||||||
|
background: #f59e0b;
|
||||||
|
color: #fff;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #d97706;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&-delete {
|
||||||
|
background: #dc2626;
|
||||||
|
color: #fff;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #b91c1c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&-back {
|
||||||
|
background: transparent;
|
||||||
|
color: #2563eb;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: #eff6ff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Страница авторизации
|
// Страница авторизации
|
||||||
.auth-page {
|
.auth-page {
|
||||||
max-width: 400px;
|
max-width: 400px;
|
||||||
@@ -87,10 +152,34 @@ input {
|
|||||||
margin-bottom: 0.75rem;
|
margin-bottom: 0.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.loading,
|
||||||
|
.empty {
|
||||||
|
color: #6b7280;
|
||||||
|
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 {
|
.home-page {
|
||||||
max-width: 600px;
|
max-width: 600px;
|
||||||
margin: 4rem auto;
|
margin: 2rem auto;
|
||||||
padding: 2rem;
|
padding: 2rem;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
|
|
||||||
@@ -98,3 +187,227 @@ input {
|
|||||||
margin-bottom: 1.5rem;
|
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 {
|
||||||
|
padding: 1.5rem;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #fafafa;
|
||||||
|
min-height: 300px;
|
||||||
|
|
||||||
|
h1, h2, h3 {
|
||||||
|
margin: 1rem 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
blockquote {
|
||||||
|
border-left: 4px solid #2563eb;
|
||||||
|
padding-left: 1rem;
|
||||||
|
margin: 1rem 0;
|
||||||
|
color: #4b5563;
|
||||||
|
}
|
||||||
|
|
||||||
|
code {
|
||||||
|
background: #f3f4f6;
|
||||||
|
padding: 0.15rem 0.35rem;
|
||||||
|
border-radius: 3px;
|
||||||
|
font-size: 0.85em;
|
||||||
|
}
|
||||||
|
|
||||||
|
pre {
|
||||||
|
background: #1f2937;
|
||||||
|
color: #e5e7eb;
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 6px;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin: 1rem 0;
|
||||||
|
|
||||||
|
code {
|
||||||
|
background: transparent;
|
||||||
|
padding: 0;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
img {
|
||||||
|
max-width: 100%;
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
margin: 1rem 0;
|
||||||
|
|
||||||
|
th, td {
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
padding: 0.5rem;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
background: #f9fafb;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user