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, Fingerprint, 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 imageApiUrl: string imageModel: string imageApiTokenConfigured: boolean } type ImageGenerationTarget = "cover" | "middle" | "final" type ImageGenerationJob = { id: string target: ImageGenerationTarget status: string progress: number stage: string localUrl?: string errorCode?: string errorMessage?: string targetBlockId?: string snapshotId?: string } type ImageGenerationBatch = { batchId: string status: string jobs: ImageGenerationJob[] } 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 } type ImageGenerationTuneConfig = { onRegenerate?: (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) }, } } } class ImageGenerationTune { private readonly block: BlockAPI private readonly config: ImageGenerationTuneConfig static get isTune() { return true } constructor({ block, config }: { block: BlockAPI; config?: ImageGenerationTuneConfig }) { this.block = block this.config = config ?? {} } render() { return { icon: '', label: "Перегенерировать по тексту", onActivate: () => { void this.config.onRegenerate?.(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 } type VkIdSdk = { Config: { init: (config: Record) => void } ConfigResponseMode?: { Callback?: unknown } ConfigSource?: { LOWCODE?: unknown } OneTap: new () => { render: (options: Record) => { on: (event: unknown, callback: (payload: any) => void) => unknown } } Auth: { exchangeCode: (code: string, deviceId: string) => Promise<{ access_token: string }> } WidgetEvents: { ERROR: unknown } OneTapInternalEvents: { LOGIN_SUCCESS: unknown } } declare global { interface Window { VKIDSDK?: VkIdSdk } } function base64UrlToBytes(value: string) { const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=") const binary = window.atob(padded) return Uint8Array.from(binary, (character) => character.charCodeAt(0)) } function bytesToBase64Url(value: ArrayBuffer | Uint8Array) { const bytes = value instanceof Uint8Array ? value : new Uint8Array(value) let binary = "" bytes.forEach((byte) => { binary += String.fromCharCode(byte) }) return window.btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "") } function registrationOptionsForBrowser(options: any) { return { ...options, challenge: base64UrlToBytes(options.challenge), user: { ...options.user, id: base64UrlToBytes(options.user.id) }, excludeCredentials: (options.excludeCredentials || []).map((item: any) => ({ ...item, id: base64UrlToBytes(item.id) })), } } function authenticationOptionsForBrowser(options: any) { return { ...options, challenge: base64UrlToBytes(options.challenge), allowCredentials: (options.allowCredentials || []).map((item: any) => ({ ...item, id: base64UrlToBytes(item.id) })), } } function serializePublicKeyCredential(credential: PublicKeyCredential) { const response = credential.response as AuthenticatorAssertionResponse | AuthenticatorAttestationResponse const payload: Record = { id: credential.id, rawId: bytesToBase64Url(credential.rawId), type: credential.type, } if ("attestationObject" in response) { payload.response = { clientDataJSON: bytesToBase64Url(response.clientDataJSON), attestationObject: bytesToBase64Url(response.attestationObject), } } else { payload.response = { clientDataJSON: bytesToBase64Url(response.clientDataJSON), authenticatorData: bytesToBase64Url(response.authenticatorData), signature: bytesToBase64Url(response.signature), userHandle: response.userHandle ? bytesToBase64Url(response.userHandle) : null, } } return payload } function loadVkIdSdk() { if (window.VKIDSDK) return Promise.resolve(window.VKIDSDK) return new Promise((resolve, reject) => { const existing = document.querySelector('script[data-vk-id-sdk="true"]') if (existing) { existing.addEventListener("load", () => window.VKIDSDK ? resolve(window.VKIDSDK) : reject(new Error("VK ID SDK не загрузился")), { once: true }) existing.addEventListener("error", () => reject(new Error("Не удалось загрузить VK ID SDK")), { once: true }) return } const script = document.createElement("script") script.dataset.vkIdSdk = "true" script.src = "https://unpkg.com/@vkid/sdk@2.6.1/dist-sdk/umd/index.js" script.onload = () => window.VKIDSDK ? resolve(window.VKIDSDK) : reject(new Error("VK ID SDK не загрузился")) script.onerror = () => reject(new Error("Не удалось загрузить VK ID SDK")) document.head.appendChild(script) }) } function ToastNotice({ message, onClose }: { message: string; onClose?: () => void }) { if (!message) return null return (
{message} {onClose ? : null}
) } function AuthScreen({ hasPasskeys, onAuthenticated }: { hasPasskeys: boolean; onAuthenticated: () => void }) { const [message, setMessage] = useState("") const [busy, setBusy] = useState(false) const [vkAuthenticated, setVkAuthenticated] = useState(false) const vkContainerRef = useRef(null) const loginInFlightRef = useRef(false) const finishVkLogin = useCallback(async (accessToken: string) => { if (loginInFlightRef.current) return loginInFlightRef.current = true setBusy(true) try { await api("/api/auth/vk", { method: "POST", body: JSON.stringify({ accessToken }) }) setVkAuthenticated(true) setMessage("VK ID подтверждён. Можно продолжить или добавить вход по Face ID / Touch ID.") } catch (error) { setMessage(error instanceof Error ? error.message : "VK ID не подтвердил пользователя") } finally { loginInFlightRef.current = false setBusy(false) } }, [onAuthenticated]) useEffect(() => { let cancelled = false const callback = new URLSearchParams(window.location.search) const callbackCode = callback.get("code") const callbackDeviceId = callback.get("device_id") loadVkIdSdk().then((VKID) => { if (cancelled) return VKID.Config.init({ app: 54716062, redirectUrl: `${window.location.origin}/auth/callback/vk`, responseMode: VKID.ConfigResponseMode?.Callback, source: VKID.ConfigSource?.LOWCODE, scope: "", }) const exchange = (code: string, deviceId: string) => VKID.Auth.exchangeCode(code, deviceId).then((tokens) => finishVkLogin(tokens.access_token)) if (callbackCode && callbackDeviceId) { void exchange(callbackCode, callbackDeviceId).catch((error) => setMessage(String(error))) window.history.replaceState({}, "", "/admin") } const oneTap = new VKID.OneTap() const rendered = oneTap.render({ container: vkContainerRef.current, showAlternativeLogin: true }) rendered.on(VKID.OneTapInternalEvents.LOGIN_SUCCESS, (payload) => { if (payload?.code && payload?.device_id) void exchange(payload.code, payload.device_id).catch((error) => setMessage(String(error))) }) rendered.on(VKID.WidgetEvents.ERROR, (error) => setMessage(`Ошибка VK ID: ${JSON.stringify(error)}`)) }).catch((error) => setMessage(error instanceof Error ? error.message : String(error))) return () => { cancelled = true } }, [finishVkLogin]) async function loginWithPasskey() { setBusy(true) setMessage("") try { if (!window.PublicKeyCredential || !navigator.credentials) throw new Error("Passkey не поддерживается этим браузером") const started = await api<{ challengeId: string; options: any }>("/api/auth/login/options", { method: "POST" }) const credential = await navigator.credentials.get({ publicKey: authenticationOptionsForBrowser(started.options) }) as PublicKeyCredential | null if (!credential) throw new Error("Вход по passkey отменён") await api("/api/auth/login/verify", { method: "POST", body: JSON.stringify({ challengeId: started.challengeId, credential: serializePublicKeyCredential(credential) }) }) onAuthenticated() } catch (error) { setMessage(error instanceof Error ? error.message : String(error)) } finally { setBusy(false) } } return (
Логотип Дзен-ассистента

Дзен-ассистент

Вход в редакторскую панель

setMessage("")} />
{hasPasskeys ? ( ) : null} {vkAuthenticated ? ( <> ) : null} {!hasPasskeys ?

После входа через VK ID добавьте биометрию в разделе «Настройки».

: null}
) } 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 imageBlockData(url: string, caption: string) { return { file: { url }, caption, withBorder: false, withBackground: false, stretched: false, } } function nearestHeadingIndex(blocks: EditorBlock[], preferredIndex: number) { const headingIndexes = blocks .map((block, index) => block.type === "header" ? index : -1) .filter((index) => index >= 0) if (!headingIndexes.length) return preferredIndex return headingIndexes.reduce((closest, index) => Math.abs(index - preferredIndex) < Math.abs(closest - preferredIndex) ? index : closest ) } function generatedImagePlacementIndex(data: OutputData, target: Exclude) { const blocks = data.blocks || [] const imageIndexes = blocks.map((block, index) => block.type === "image" ? index : -1).filter((index) => index >= 0) if (target === "middle" && imageIndexes.length) return imageIndexes[0] if (target === "final" && imageIndexes.length > 1) return imageIndexes[imageIndexes.length - 1] const preferredIndex = Math.floor(blocks.length * (target === "middle" ? 1 / 3 : 2 / 3)) return nearestHeadingIndex(blocks, preferredIndex) } function SettingsPanel({ onBack, onSaved }: { onBack: () => void; onSaved: (settings: AppSettings) => void }) { const [settings, setSettings] = useState({ signatureHtml: "", llmInstructions: "", imageApiUrl: "https://polza.ai/api", imageModel: "google/gemini-3.1-flash-image", imageApiTokenConfigured: false, }) const [imageApiToken, setImageApiToken] = useState("") const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [dirty, setDirty] = useState(false) const [message, setMessage] = useState("") const [passkeyBusy, setPasskeyBusy] = useState(false) 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(), imageApiUrl: settings.imageApiUrl.trim(), imageModel: settings.imageModel.trim(), imageApiTokenConfigured: settings.imageApiTokenConfigured, } const payload: Record = { ...next } if (imageApiToken.trim()) payload.imageApiToken = imageApiToken.trim() const saved = await api("/api/settings", { method: "PUT", body: JSON.stringify(payload) }) setSettings(saved) setImageApiToken("") setDirty(false) setMessage("Настройки сохранены") onSaved(saved) } catch (error) { setMessage(`Не удалось сохранить настройки: ${error instanceof Error ? error.message : String(error)}`) } finally { setSaving(false) } } async function clearImageApiToken() { if (!window.confirm("Удалить токен Polza? Генерация изображений станет недоступна до ввода нового токена.")) return setSaving(true) try { const saved = await api("/api/settings", { method: "PUT", body: JSON.stringify({ signatureHtml: settings.signatureHtml, llmInstructions: settings.llmInstructions, imageApiUrl: settings.imageApiUrl.trim(), imageModel: settings.imageModel.trim(), deleteImageApiToken: true, }), }) setSettings(saved) setImageApiToken("") setDirty(false) setMessage("Токен удалён") onSaved(saved) } catch (error) { setMessage(`Не удалось удалить токен: ${error instanceof Error ? error.message : String(error)}`) } finally { setSaving(false) } } async function registerPasskey() { setPasskeyBusy(true) try { const started = await api<{ challengeId: string; options: any }>("/api/auth/register/options", { method: "POST" }) const credential = await navigator.credentials.create({ publicKey: registrationOptionsForBrowser(started.options) }) as PublicKeyCredential | null if (!credential) throw new Error("Регистрация устройства отменена") await api("/api/auth/register/verify", { method: "POST", body: JSON.stringify({ challengeId: started.challengeId, credential: serializePublicKeyCredential(credential) }) }) setMessage("Устройство зарегистрировано для входа по биометрии") } catch (error) { setMessage(`Не удалось зарегистрировать устройство: ${error instanceof Error ? error.message : String(error)}`) } finally { setPasskeyBusy(false) } } return (

    Настройки

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

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