feat(client): Phase 8 — markdown editor, news list, toolbar, preview, upload, publish
This commit is contained in:
@@ -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 */
|
||||
Reference in New Issue
Block a user