import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from "react" import EditorJS, { type BlockAPI, type OutputData, type ToolConstructable } from "@editorjs/editorjs" import Header from "@editorjs/header" import ImageTool from "@editorjs/image" import List from "@editorjs/list" import Quote from "@editorjs/quote" import { AlertTriangle, ArrowLeft, CheckCircle2, Clock3, Copy, ExternalLink, FilePenLine, FileText, ImagePlus, Link2, Loader2, Radio, RefreshCw, Save, Settings2, Trash2, X, } from "lucide-react" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Textarea } from "@/components/ui/textarea" import { Input } from "@/components/ui/input" type AppSettings = { signatureHtml: string llmInstructions: string } type VideoArticle = { id: number title: string status: string } type Video = { id: number title: string sourceUrl: string manual?: boolean status: string progressPercent: number progressStage: string durationSeconds?: number createdAt?: string publishedAt?: string errorMessage?: string articleIds: number[] articles?: VideoArticle[] } type Article = { id: number title: string slug: string status: string url: string featureImageUrl?: string createdAt?: string publishedAt?: string } type ArticlesPage = { items: Article[] total: number limit: number offset: number hasMore: boolean } type ArticleDetail = Article & { contentHtml: string editableHtml: string videoId?: number } type VideoLog = { id: number title: string status: string progressPercent: number progressStage: string progressLog: string errorMessage?: string } type VideoChapter = { id: string title: string startSeconds: number endSeconds?: number durationSeconds?: number startTimecode: string endTimecode?: string selected: boolean } type VideoChaptersResponse = { videoId: number title: string durationSeconds?: number chapters: VideoChapter[] canSplit: boolean } type EditorBlock = OutputData["blocks"][number] type RandomFrameTuneConfig = { onReplace?: (block: BlockAPI) => void | Promise } const ARTICLES_PAGE_SIZE = 10 const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:" function chapterSelectionStorageKey(videoId: number) { return `${CHAPTER_SELECTION_STORAGE_PREFIX}${videoId}` } function loadStoredChapterSelection(videoId: number): string[] | null { try { const value = window.localStorage.getItem(chapterSelectionStorageKey(videoId)) if (value === null) return null const parsed = JSON.parse(value) return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string") : null } catch { return null } } function storeChapterSelection(videoId: number, ids: Iterable) { try { window.localStorage.setItem(chapterSelectionStorageKey(videoId), JSON.stringify(Array.from(ids))) } catch { // Local Storage can be unavailable in restricted browser modes. } } function clearStoredChapterSelection(videoId: number) { try { window.localStorage.removeItem(chapterSelectionStorageKey(videoId)) } catch { // Nothing to clean up if Local Storage is unavailable. } } function imageFileFromClipboard(event: ClipboardEvent) { return ( Array.from(event.clipboardData?.files || []).find((item) => item.type.startsWith("image/")) || Array.from(event.clipboardData?.items || []) .find((item) => item.kind === "file" && item.type.startsWith("image/")) ?.getAsFile() || null ) } function imageFileFromDataTransfer(dataTransfer: DataTransfer | null) { return Array.from(dataTransfer?.files || []).find((item) => item.type.startsWith("image/")) || null } class RandomFrameTune { private readonly block: BlockAPI private readonly config: RandomFrameTuneConfig static get isTune() { return true } constructor({ block, config }: { block: BlockAPI; config?: RandomFrameTuneConfig }) { this.block = block this.config = config ?? {} } render() { return { icon: '', label: "Другой кадр", onActivate: () => { void this.config.onReplace?.(this.block) }, } } } const editorI18n = { messages: { ui: { blockTunes: { toggler: { "Click to tune": "Настроить блок", "or drag to move": "или перетащите", }, }, inlineToolbar: { converter: { "Convert to": "Преобразовать в", }, }, toolbar: { toolbox: { Add: "Добавить", }, }, popover: { Filter: "Фильтр", "Nothing found": "Ничего не найдено", "Convert to": "Преобразовать в", }, }, toolNames: { Text: "Текст", Link: "Ссылка", Bold: "Жирный", Italic: "Курсив", Heading: "Заголовок", List: "Список", Quote: "Цитата", Image: "Изображение", }, tools: { link: { "Add a link": "Вставьте ссылку", }, stub: { "The block can not be displayed correctly.": "Блок не может быть отображен корректно.", }, header: { "Heading 2": "Заголовок 2", "Heading 3": "Заголовок 3", "Enter a header": "Введите заголовок", }, list: { Ordered: "Нумерованный", Unordered: "Маркированный", }, quote: { "Enter a quote": "Введите цитату", "Enter a caption": "Автор или пояснение", "Align Left": "По левому краю", "Align Center": "По центру", }, image: { Caption: "Подпись", "Select an Image": "Выбрать изображение", "With border": "С рамкой", "Stretch image": "Растянуть изображение", "With background": "С фоном", "With caption": "С подписью", "Couldn’t upload image. Please try another.": "Не удалось загрузить изображение. Попробуйте другое.", }, }, blockTunes: { delete: { Delete: "Удалить", "Click to delete": "Нажмите, чтобы удалить", }, moveUp: { "Move up": "Переместить вверх", }, moveDown: { "Move down": "Переместить вниз", }, randomFrame: { "Другой кадр": "Другой кадр", }, }, }, } async function api(path: string, init?: RequestInit): Promise { const isFormData = init?.body instanceof FormData const response = await fetch(path, { ...init, headers: { ...(isFormData ? {} : { "content-type": "application/json" }), ...(init?.headers ?? {}) }, }) if (!response.ok) { throw new Error(await response.text()) } return response.json() as Promise } function escapeHtml(value: string) { return value .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) } function normalizeEditorText(value: string) { const parser = new DOMParser() const document = parser.parseFromString(`
${value || ""}
`, "text/html") return (document.body.textContent || "") .replace(/^#{1,6}\s*/, "") .replace(/\s+/g, " ") .trim() .toLowerCase() .replace(/ё/g, "е") } function stripLeadingDuplicateTitleBlock(blocks: EditorBlock[], title?: string) { const normalizedTitle = normalizeEditorText(title || "") if (!normalizedTitle || blocks.length === 0) return blocks const first = blocks[0] if (!["paragraph", "header"].includes(first.type)) return blocks const text = normalizeEditorText(String((first.data as Record).text || "")) return text === normalizedTitle ? blocks.slice(1) : blocks } function htmlToEditorData(html: string, title?: string): OutputData { const parser = new DOMParser() const document = parser.parseFromString(`
${html || ""}
`, "text/html") const root = document.querySelector("main") const blocks: EditorBlock[] = [] function pushParagraph(element: Element) { const text = element.innerHTML.trim() if (text) { blocks.push({ type: "paragraph", data: { text } }) } } root?.childNodes.forEach((node) => { if (node.nodeType === Node.TEXT_NODE) { const text = node.textContent?.trim() if (text) { blocks.push({ type: "paragraph", data: { text: escapeHtml(text) } }) } return } if (!(node instanceof Element)) return const tag = node.tagName.toLowerCase() if (tag === "p") { pushParagraph(node) return } if (tag === "h2" || tag === "h3") { blocks.push({ type: "header", data: { text: node.innerHTML.trim(), level: tag === "h2" ? 2 : 3 } }) return } if (tag === "blockquote") { blocks.push({ type: "quote", data: { text: node.innerHTML.trim(), caption: "", alignment: "left" } }) return } if (tag === "ul" || tag === "ol") { const items = Array.from(node.querySelectorAll(":scope > li")).map((item) => item.innerHTML.trim()).filter(Boolean) blocks.push({ type: "list", data: { style: tag === "ol" ? "ordered" : "unordered", items } }) return } if (tag === "figure") { const image = node.querySelector("img") if (!image) return blocks.push({ type: "image", data: { file: { url: image.getAttribute("src") || "" }, caption: node.querySelector("figcaption")?.innerHTML.trim() || image.getAttribute("alt") || "", withBorder: false, withBackground: false, stretched: false, }, }) return } pushParagraph(node) }) const cleanBlocks = stripLeadingDuplicateTitleBlock(blocks, title) return { time: Date.now(), blocks: cleanBlocks.length ? cleanBlocks : [{ type: "paragraph", data: { text: "" } }], version: "2.30.8", } } function editorDataToHtml(data: OutputData, title?: string): string { return stripLeadingDuplicateTitleBlock(data.blocks || [], title) .map((block) => { const item = block.data as Record if (block.type === "header") { const level = item.level === 3 ? 3 : 2 return `${item.text || ""}` } if (block.type === "list") { const tag = item.style === "ordered" ? "ol" : "ul" const items = Array.isArray(item.items) ? item.items : [] return `<${tag}>${items.map((value) => `
  • ${value}
  • `).join("")}` } if (block.type === "quote") { return `
    ${item.text || ""}
    ` } if (block.type === "image") { const url = item.file?.url || item.url || "" if (!url) return "" const caption = item.caption || title return `
    ${escapeHtml(caption)}
    ${caption}
    ` } return `

    ${item.text || ""}

    ` }) .filter(Boolean) .join("\n") } function appendSignatureToEditorData(data: OutputData, signatureHtml: string): OutputData { if (!signatureHtml.trim()) return data const signatureBlocks = htmlToEditorData(signatureHtml).blocks if (!signatureBlocks.length || signatureBlocks.every((block) => block.type === "paragraph" && !String((block.data as Record).text || "").trim())) { return data } const blocks = data.blocks || [] const tail = blocks.slice(-signatureBlocks.length) const sameBlock = (left: EditorBlock, right: EditorBlock) => left.type === right.type && JSON.stringify(left.data) === JSON.stringify(right.data) if (tail.length === signatureBlocks.length && tail.every((block, index) => sameBlock(block, signatureBlocks[index]))) { return data } return { ...data, blocks: [...blocks, ...signatureBlocks] } } function htmlToPlainText(html: string) { const parser = new DOMParser() const document = parser.parseFromString(`
    ${html || ""}
    `, "text/html") return (document.querySelector("main")?.textContent || "").replace(/\s+\n/g, "\n").replace(/[ \t]{2,}/g, " ").trim() } function editorDataToPlainText(data: OutputData, title?: string): string { const parts: string[] = [] const normalizedTitle = normalizeEditorText(title || "") const blocks = stripLeadingDuplicateTitleBlock(data.blocks || [], title) if (title?.trim()) { parts.push(title.trim()) } blocks.forEach((block) => { if (block.type === "image") return const item = block.data as Record let text = "" if (block.type === "header" || block.type === "paragraph") { text = htmlToPlainText(String(item.text || "")) } else if (block.type === "quote") { text = htmlToPlainText(String(item.text || "")) } else if (block.type === "list" && Array.isArray(item.items)) { text = item.items.map((value: unknown) => `- ${htmlToPlainText(String(value || ""))}`).join("\n") } else { text = htmlToPlainText(String(item.text || "")) } if (!text || normalizeEditorText(text) === normalizedTitle) return parts.push(text) }) return parts.join("\n\n").trim() } function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (settings: AppSettings) => void }) { const [settings, setSettings] = useState({ signatureHtml: "", llmInstructions: "" }) const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [dirty, setDirty] = useState(false) const [message, setMessage] = useState("") const signatureHolderRef = useRef(null) const signatureEditorRef = useRef(null) useEffect(() => { api("/api/settings") .then((result) => { setSettings(result) onSaved(result) setLoading(false) }) .catch((error) => { setMessage(`Не удалось загрузить настройки: ${error instanceof Error ? error.message : String(error)}`) setLoading(false) }) }, [onSaved]) useEffect(() => { if (loading || !signatureHolderRef.current) return signatureEditorRef.current?.destroy() signatureHolderRef.current.innerHTML = "" const editor = new EditorJS({ holder: signatureHolderRef.current, data: htmlToEditorData(settings.signatureHtml), placeholder: "Введите подпись...", inlineToolbar: ["bold", "italic", "link"], i18n: editorI18n, tools: { header: { class: Header as unknown as ToolConstructable, inlineToolbar: ["bold", "italic", "link"], config: { levels: [2, 3], defaultLevel: 2, placeholder: "Введите заголовок" }, }, list: { class: List as unknown as ToolConstructable, inlineToolbar: true }, quote: { class: Quote as unknown as ToolConstructable, inlineToolbar: true, config: { quotePlaceholder: "Цитата", captionPlaceholder: "" }, }, }, onChange: () => setDirty(true), }) signatureEditorRef.current = editor return () => { if (signatureEditorRef.current === editor) signatureEditorRef.current = null void editor.destroy() } }, [loading]) async function saveSettings() { setSaving(true) try { const data = await signatureEditorRef.current?.save() const serializedSignature = data ? editorDataToHtml(data) : settings.signatureHtml const next: AppSettings = { signatureHtml: htmlToPlainText(serializedSignature).trim() ? serializedSignature : "", llmInstructions: settings.llmInstructions.trim(), } const saved = await api("/api/settings", { method: "PUT", body: JSON.stringify(next) }) setSettings(saved) setDirty(false) setMessage("Настройки сохранены") onSaved(saved) } catch (error) { setMessage(`Не удалось сохранить настройки: ${error instanceof Error ? error.message : String(error)}`) } finally { setSaving(false) } } return (

    Настройки

    Общая подпись и дополнительные правила редактора.

    {message ?
    {message}
    : null} {loading ? ( Загрузка настроек... ) : (
    Подпись статьи Появится последним редактируемым блоком в новых черновиках.
    Инструкции для ИИ Будут добавлены к основным редакторским правилам.