dzen.nstarikov.ru/dzen-assistant/admin/src/App.tsx

2256 lines
96 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}
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<void>
}
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<string>) {
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: '<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 3h5v5"/><path d="M4 20 21 3"/><path d="M21 16v5h-5"/><path d="m15 15 6 6"/><path d="m4 4 5 5"/></svg>',
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<T>(path: string, init?: RequestInit): Promise<T> {
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<T>
}
type VkIdSdk = {
Config: { init: (config: Record<string, unknown>) => void }
ConfigResponseMode?: { Callback?: unknown }
ConfigSource?: { LOWCODE?: unknown }
OneTap: new () => { render: (options: Record<string, unknown>) => { 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<string, unknown> = {
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<VkIdSdk>((resolve, reject) => {
const existing = document.querySelector<HTMLScriptElement>('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 (
<div className="fixed inset-x-4 top-4 z-[100] flex justify-center pointer-events-none sm:inset-x-6">
<div className="pointer-events-auto flex max-w-xl items-start gap-3 rounded-lg border border-foreground/10 bg-foreground px-4 py-3 text-sm text-background shadow-xl">
<span className="min-w-0 flex-1 break-words">{message}</span>
{onClose ? <button aria-label="Закрыть уведомление" className="shrink-0 rounded-sm opacity-70 transition-opacity hover:opacity-100" onClick={onClose} type="button"><X className="size-4" /></button> : null}
</div>
</div>
)
}
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<HTMLDivElement | null>(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 (
<main className="auth-screen flex min-h-screen items-center justify-center p-4 sm:p-6">
<section className="auth-card w-full max-w-md rounded-lg border bg-background/90 p-4 shadow-xl sm:p-6">
<div className="mb-6 flex items-center gap-3">
<img alt="Логотип Дзен-ассистента" className="size-12 rounded-md" src="/favicon.png" />
<div><h1 className="text-xl font-semibold">Дзен-ассистент</h1><p className="text-sm text-muted-foreground">Вход в редакторскую панель</p></div>
</div>
<ToastNotice message={message} onClose={() => setMessage("")} />
<div ref={vkContainerRef} className="min-h-12" />
{hasPasskeys ? (
<Button className="mt-3 w-full" disabled={busy} onClick={loginWithPasskey}>
{busy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Fingerprint data-icon="inline-start" />}
Войти по Face ID / Touch ID
</Button>
) : null}
{vkAuthenticated ? (
<>
<Button className="mt-3 min-h-11 w-full whitespace-normal px-4 py-3 text-center leading-5" disabled={busy} onClick={onAuthenticated} variant="outline">
Продолжить через VK ID
</Button>
</>
) : null}
{!hasPasskeys ? <p className="mt-4 text-xs text-muted-foreground">После входа через VK ID добавьте биометрию в разделе «Настройки».</p> : null}
</section>
</main>
)
}
function escapeHtml(value: string) {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
}
function normalizeEditorText(value: string) {
const parser = new DOMParser()
const document = parser.parseFromString(`<main>${value || ""}</main>`, "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<string, unknown>).text || ""))
return text === normalizedTitle ? blocks.slice(1) : blocks
}
function htmlToEditorData(html: string, title?: string): OutputData {
const parser = new DOMParser()
const document = parser.parseFromString(`<main>${html || ""}</main>`, "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<string, any>
if (block.type === "header") {
const level = item.level === 3 ? 3 : 2
return `<h${level}>${item.text || ""}</h${level}>`
}
if (block.type === "list") {
const tag = item.style === "ordered" ? "ol" : "ul"
const items = Array.isArray(item.items) ? item.items : []
return `<${tag}>${items.map((value) => `<li>${value}</li>`).join("")}</${tag}>`
}
if (block.type === "quote") {
return `<blockquote>${item.text || ""}</blockquote>`
}
if (block.type === "image") {
const url = item.file?.url || item.url || ""
if (!url) return ""
const caption = item.caption || title
return `<figure><img src="${escapeHtml(url)}" alt="${escapeHtml(caption)}"><figcaption>${caption}</figcaption></figure>`
}
return `<p>${item.text || ""}</p>`
})
.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<string, unknown>).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(`<main>${html || ""}</main>`, "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<string, any>
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<AppSettings>({ signatureHtml: "", llmInstructions: "" })
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<HTMLDivElement | null>(null)
const signatureEditorRef = useRef<EditorJS | null>(null)
useEffect(() => {
api<AppSettings>("/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<AppSettings>("/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)
}
}
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 (
<section className="flex flex-col gap-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="text-xl font-semibold tracking-normal">Настройки</h2>
<p className="text-sm text-muted-foreground">Общая подпись и дополнительные правила редактора.</p>
</div>
<Button variant="outline" onClick={onBack}>
<ArrowLeft data-icon="inline-start" />
К роликам
</Button>
</div>
<ToastNotice message={message} onClose={() => setMessage("")} />
{loading ? (
<Card><CardContent className="p-6 text-sm text-muted-foreground">Загрузка настроек...</CardContent></Card>
) : (
<div className="grid gap-6 xl:grid-cols-[minmax(0,1.15fr)_minmax(360px,0.85fr)]">
<Card>
<CardHeader>
<CardTitle>Подпись статьи</CardTitle>
<CardDescription>Появится последним редактируемым блоком в новых черновиках.</CardDescription>
</CardHeader>
<CardContent>
<div ref={signatureHolderRef} className="article-editor article-editorjs min-h-[180px] rounded-md border bg-background p-3" />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Инструкции для ИИ</CardTitle>
<CardDescription>Будут добавлены к основным редакторским правилам.</CardDescription>
</CardHeader>
<CardContent>
<Textarea
className="min-h-[280px] resize-y"
onChange={(event) => {
setSettings((current) => ({ ...current, llmInstructions: event.target.value }))
setDirty(true)
}}
placeholder="Дополнительные требования к статьям..."
value={settings.llmInstructions}
/>
</CardContent>
</Card>
</div>
)}
<div className="flex justify-end gap-2">
<Button disabled={passkeyBusy || loading} onClick={registerPasskey} variant="outline">
{passkeyBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Fingerprint data-icon="inline-start" />}
Добавить биометрию
</Button>
<Button disabled={saving || loading || !dirty} onClick={saveSettings}>
{saving ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Save data-icon="inline-start" />}
Сохранить
</Button>
</div>
</section>
)
}
async function writeClipboardText(text: string) {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
return
}
const textarea = document.createElement("textarea")
textarea.value = text
textarea.setAttribute("readonly", "true")
textarea.style.position = "fixed"
textarea.style.left = "-9999px"
document.body.appendChild(textarea)
textarea.select()
document.execCommand("copy")
document.body.removeChild(textarea)
}
function formatDuration(seconds?: number) {
if (!seconds) return "—"
const minutes = Math.floor(seconds / 60)
const rest = seconds % 60
return `${minutes}:${String(rest).padStart(2, "0")}`
}
function parseApiDate(value?: string) {
if (!value) return null
const normalized = /(?:z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`
const date = new Date(normalized)
return Number.isNaN(date.getTime()) ? null : date
}
function toDateTimeLocalValue(value?: string) {
const date = parseApiDate(value)
if (!date) return ""
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
return local.toISOString().slice(0, 16)
}
function currentDateTimeLocalValue() {
const date = new Date()
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
return local.toISOString().slice(0, 16)
}
function formatDateTime(value?: string) {
const date = parseApiDate(value)
if (!date) return ""
return new Intl.DateTimeFormat("ru-RU", {
day: "2-digit",
month: "short",
hour: "2-digit",
minute: "2-digit",
}).format(date)
}
function formatVideoDate(value?: string) {
const date = parseApiDate(value)
if (!date) return "дата неизвестна"
return new Intl.DateTimeFormat("ru-RU", {
day: "2-digit",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
}).format(date)
}
function isScheduledForFuture(value?: string) {
const date = parseApiDate(value)
return Boolean(date && date.getTime() > Date.now())
}
function dateSortValue(value?: string) {
return parseApiDate(value)?.getTime() ?? 0
}
function statusVariant(status: string) {
if (status === "published" || status === "drafted") return "default"
if (status === "error") return "destructive"
if (status === "processing") return "secondary"
return "outline"
}
function StatusBadge({ status }: { status: string }) {
const normalized = status.toLowerCase()
if (normalized === "published") {
return (
<Badge className="gap-1.5 border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-50" variant="outline">
<CheckCircle2 className="size-3.5" />
Опубликовано
</Badge>
)
}
if (normalized === "drafted" || normalized === "draft") {
return (
<Badge className="gap-1.5 border-zinc-200 bg-zinc-100 text-zinc-600 hover:bg-zinc-100" variant="outline">
<FilePenLine className="size-3.5" />
Черновик
</Badge>
)
}
if (normalized === "error") {
return (
<Badge className="gap-1.5" variant="destructive">
<AlertTriangle className="size-3.5" />
Ошибка
</Badge>
)
}
if (normalized === "processing" || normalized === "queued") {
return (
<Badge className="gap-1.5 border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-50" variant="outline">
{normalized === "processing" ? <Loader2 className="size-3.5 animate-spin" /> : <Clock3 className="size-3.5" />}
{normalized === "processing" ? "В работе" : "В очереди"}
</Badge>
)
}
return <Badge variant={statusVariant(status)}>{status}</Badge>
}
function ArticlePlaceholder() {
return (
<div className="rounded-md border bg-background p-4">
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<div className="h-6 w-24 animate-pulse rounded-full bg-muted" />
<div className="h-4 flex-1 animate-pulse rounded bg-muted" />
</div>
<div className="mt-3 h-3 w-5/6 animate-pulse rounded bg-muted" />
<div className="mt-2 h-3 w-40 animate-pulse rounded bg-muted" />
</div>
<div className="flex shrink-0 gap-2">
<div className="size-9 animate-pulse rounded-md bg-muted" />
<div className="size-9 animate-pulse rounded-md bg-muted" />
<div className="size-9 animate-pulse rounded-md bg-muted" />
</div>
</div>
</div>
)
}
export default function App() {
const [authState, setAuthState] = useState<"loading" | "unauthenticated" | "authenticated">("loading")
const [hasPasskeys, setHasPasskeys] = useState(false)
const [activeView, setActiveView] = useState<"dashboard" | "settings">("dashboard")
const [appSettings, setAppSettings] = useState<AppSettings>({ signatureHtml: "", llmInstructions: "" })
const [videos, setVideos] = useState<Video[]>([])
const [articles, setArticles] = useState<Article[]>([])
const [articlesHasMore, setArticlesHasMore] = useState(false)
const [articlesLoading, setArticlesLoading] = useState(false)
const [selectedLog, setSelectedLog] = useState<VideoLog | null>(null)
const [selectedArticle, setSelectedArticle] = useState<ArticleDetail | null>(null)
const [chapterPlan, setChapterPlan] = useState<{ video: Video; chapters: VideoChapter[]; recreateDrafts: boolean } | null>(null)
const [selectedChapterIds, setSelectedChapterIds] = useState<Set<string>>(new Set())
const [editorTitle, setEditorTitle] = useState("")
const [publishAt, setPublishAt] = useState("")
const [editorDirty, setEditorDirty] = useState(false)
const [editorBusy, setEditorBusy] = useState(false)
const [featureImageBusy, setFeatureImageBusy] = useState(false)
const [featureImageDragActive, setFeatureImageDragActive] = useState(false)
const [featureImageHoverActive, setFeatureImageHoverActive] = useState(false)
const [copyToast, setCopyToast] = useState("")
const [statusMessage, setStatusMessage] = useState("")
const [busy, setBusy] = useState(false)
const [manualVideoUrl, setManualVideoUrl] = useState("")
const [manualVideoBusy, setManualVideoBusy] = useState(false)
const [videoActionId, setVideoActionId] = useState<number | null>(null)
const editorHolderRef = useRef<HTMLDivElement | null>(null)
const editorInstanceRef = useRef<EditorJS | null>(null)
const featureImageInputRef = useRef<HTMLInputElement | null>(null)
const featureImageHoverRef = useRef(false)
const editorImageHoverBlockRef = useRef<BlockAPI | null>(null)
const pasteImageTargetRef = useRef<"feature" | "editor" | null>(null)
const imageCaptionNormalizeTimerRef = useRef<number[]>([])
const logSocketRef = useRef<WebSocket | null>(null)
const selectedArticleRef = useRef<ArticleDetail | null>(null)
const editorTitleRef = useRef("")
const titleTextareaRef = useRef<HTMLTextAreaElement | null>(null)
const articlesOffsetRef = useRef(0)
const articlesLoadingRef = useRef(false)
const articlesHasMoreRef = useRef(false)
const handleAuthenticated = useCallback(() => {
setAuthState("authenticated")
}, [])
const handleSettingsSaved = useCallback((next: AppSettings) => {
setAppSettings(next)
}, [])
const feedUrl = useMemo(() => `${window.location.origin}/feed`, [])
const productionVideos = useMemo(
() =>
videos
.filter((video) => {
const articles = video.articles ?? []
const hasDrafts = articles.some((article) => article.status !== "published")
const hasPublished = articles.some((article) => article.status === "published")
return hasDrafts || !hasPublished
})
.sort((a, b) => dateSortValue(b.publishedAt || b.createdAt) - dateSortValue(a.publishedAt || a.createdAt)),
[videos]
)
const activeVideos = useMemo(() => productionVideos.filter((video) => ["queued", "processing"].includes(video.status)), [productionVideos])
const publishedArticles = useMemo(
() =>
articles
.filter((article) => article.status === "published")
.sort((a, b) => dateSortValue(b.publishedAt || b.createdAt) - dateSortValue(a.publishedAt || a.createdAt)),
[articles]
)
async function loadArticlesPage(reset = false) {
if (articlesLoadingRef.current) return
const offset = reset ? 0 : articlesOffsetRef.current
articlesLoadingRef.current = true
setArticlesLoading(true)
try {
const page = await api<ArticlesPage>(`/api/articles?status=published&limit=${ARTICLES_PAGE_SIZE}&offset=${offset}`)
articlesOffsetRef.current = offset + page.items.length
articlesHasMoreRef.current = page.hasMore
setArticlesHasMore(page.hasMore)
setArticles((current) => {
if (reset) return page.items
const existingIds = new Set(current.map((article) => article.id))
return [...current, ...page.items.filter((article) => !existingIds.has(article.id))]
})
} finally {
articlesLoadingRef.current = false
setArticlesLoading(false)
}
}
async function refresh() {
const showArticlePlaceholders = articlesOffsetRef.current === 0
if (showArticlePlaceholders) {
setArticlesLoading(true)
}
try {
const [nextVideos, nextArticles] = await Promise.all([
api<Video[]>("/api/videos"),
api<ArticlesPage>(`/api/articles?status=published&limit=${ARTICLES_PAGE_SIZE}&offset=0`),
])
setVideos(nextVideos)
setArticles(nextArticles.items)
articlesOffsetRef.current = nextArticles.items.length
articlesHasMoreRef.current = nextArticles.hasMore
setArticlesHasMore(nextArticles.hasMore)
} finally {
if (showArticlePlaceholders) {
setArticlesLoading(false)
}
}
}
useEffect(() => {
api<{ authenticated: boolean; hasPasskeys: boolean }>("/api/auth/status")
.then((status) => {
setHasPasskeys(status.hasPasskeys)
setAuthState(status.authenticated ? "authenticated" : "unauthenticated")
})
.catch((error) => {
setAuthState("unauthenticated")
setStatusMessage(`Ошибка проверки авторизации: ${error.message}`)
})
}, [])
useEffect(() => {
if (authState !== "authenticated") return
refresh().catch((error) => setStatusMessage(`Ошибка загрузки: ${error.message}`))
api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined)
}, [authState])
useEffect(() => {
if (!statusMessage) return
const timer = window.setTimeout(() => setStatusMessage(""), 4200)
return () => window.clearTimeout(timer)
}, [statusMessage])
useEffect(() => {
if (authState !== "authenticated" || activeVideos.length === 0) return
const timer = window.setInterval(() => {
refresh().catch((error) => {
setStatusMessage(`Ошибка обновления: ${error.message}`)
})
}, 5000)
return () => window.clearInterval(timer)
}, [activeVideos.length, authState])
useEffect(() => {
videos.forEach((video) => {
if (video.status === "drafted" && (video.articles?.length || 0) > 0) {
clearStoredChapterSelection(video.id)
}
})
}, [videos])
useEffect(() => () => {
logSocketRef.current?.close()
clearImageCaptionNormalizationTimers()
}, [])
useEffect(() => {
selectedArticleRef.current = selectedArticle
}, [selectedArticle])
useEffect(() => {
editorTitleRef.current = editorTitle
const element = titleTextareaRef.current
if (element) {
element.style.height = "auto"
element.style.height = `${element.scrollHeight}px`
}
}, [editorTitle])
async function scanSources() {
setBusy(true)
try {
const result = await api<{ taskId: string }>("/api/sources/scan", { method: "POST" })
setStatusMessage(`Проверяю VK Видео. Task: ${result.taskId}`)
await refresh()
} finally {
setBusy(false)
}
}
async function importManualVideo(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const url = manualVideoUrl.trim()
if (!url) return
setManualVideoBusy(true)
try {
const imported = await api<{ id: number; title: string; sourceUrl: string; durationSeconds?: number; status: string }>("/api/videos/import", {
method: "POST",
body: JSON.stringify({ url }),
})
setManualVideoUrl("")
setStatusMessage(`Ссылка проверена через yt-dlp: ${imported.title}. Готовлю ролик к обработке.`)
await refresh()
await prepareVideoProcessing({
id: imported.id,
title: imported.title,
sourceUrl: imported.sourceUrl,
status: imported.status,
progressPercent: 0,
progressStage: "",
durationSeconds: imported.durationSeconds,
articleIds: [],
})
} catch (error) {
setStatusMessage(`Не удалось добавить ролик: ${error instanceof Error ? error.message : String(error)}`)
} finally {
setManualVideoBusy(false)
}
}
async function prepareVideoProcessing(video: Video, recreateDrafts = false) {
if ((video.durationSeconds || 0) < 20 * 60) {
await processVideo(video.id, recreateDrafts)
return
}
setVideoActionId(video.id)
try {
const result = await api<VideoChaptersResponse>(`/api/videos/${video.id}/chapters`)
if (!result.canSplit || result.chapters.length < 2) {
await processVideo(video.id)
return
}
const initiallySelected = result.chapters.filter((chapter) => chapter.selected).map((chapter) => chapter.id)
const storedSelection = loadStoredChapterSelection(video.id)
const availableIds = new Set(result.chapters.map((chapter) => chapter.id))
const restoredSelection = storedSelection?.filter((id) => availableIds.has(id))
setChapterPlan({ video, chapters: result.chapters, recreateDrafts })
setSelectedChapterIds(
new Set(
storedSelection !== null
? restoredSelection
: initiallySelected.length
? initiallySelected
: result.chapters.map((chapter) => chapter.id)
)
)
} finally {
setVideoActionId(null)
}
}
async function processVideo(id: number, restart = false, chapters?: VideoChapter[]) {
setVideoActionId(id)
try {
const result = await api<{ taskId: string }>(`/api/videos/${id}/process`, {
method: "POST",
body: JSON.stringify({
chapters: chapters?.map((chapter) => ({
id: chapter.id,
title: chapter.title,
startSeconds: chapter.startSeconds,
endSeconds: chapter.endSeconds ?? null,
})),
recreateDrafts: restart,
}),
})
const chapterText = chapters?.length ? `, глав: ${chapters.length}` : ""
setStatusMessage(`${restart ? "Перезапустил" : "Поставил"} ролик #${id} в обработку${chapterText}. Task: ${result.taskId}`)
setChapterPlan(null)
await refresh()
} finally {
setVideoActionId(null)
}
}
async function processSelectedChapters() {
if (!chapterPlan) return
const selected = chapterPlan.chapters.filter((chapter) => selectedChapterIds.has(chapter.id))
if (!selected.length) {
setStatusMessage("Выберите хотя бы одну главу для обработки.")
return
}
await processVideo(chapterPlan.video.id, chapterPlan.recreateDrafts, selected)
}
async function reprocessVideo(video: Video) {
const hasDrafts = video.articles?.some((article) => article.status !== "published")
const message = hasDrafts
? "Старые черновики будут скрыты, а ролик уйдет на новую обработку. Продолжить?"
: "Ролик уйдет на новую обработку по текущим правилам. Уже опубликованные статьи останутся в RSS. Продолжить?"
if (!window.confirm(message)) return
await prepareVideoProcessing(video, true)
}
async function openVideoLog(id: number) {
logSocketRef.current?.close()
const result = await api<VideoLog>(`/api/videos/${id}/logs`)
setSelectedLog(result)
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"
const socket = new WebSocket(`${protocol}//${window.location.host}/api/videos/${id}/logs/ws`)
logSocketRef.current = socket
socket.onmessage = (event) => {
try {
setSelectedLog(JSON.parse(event.data) as VideoLog)
} catch {
// Ignore malformed frames; the next server tick will replace the state.
}
}
socket.onerror = () => {
setStatusMessage("Не удалось подключиться к live-логам. Показываю последний полученный лог.")
}
socket.onclose = () => {
if (logSocketRef.current === socket) {
logSocketRef.current = null
}
}
}
function closeVideoLog() {
logSocketRef.current?.close()
logSocketRef.current = null
setSelectedLog(null)
}
async function openArticlePreview(id: number) {
const result = await api<ArticleDetail>(`/api/articles/${id}`)
setSelectedArticle(result)
setEditorTitle(result.title)
setPublishAt(toDateTimeLocalValue(result.publishedAt) || currentDateTimeLocalValue())
setEditorDirty(false)
}
async function publishArticle(id: number, scheduledAt?: string) {
const result = await api<{ url: string; publishedAt?: string }>(`/api/articles/${id}/publish`, {
method: "POST",
body: JSON.stringify({ publishedAt: scheduledAt || null }),
})
const isFuture = isScheduledForFuture(result.publishedAt)
setStatusMessage(isFuture ? `Запланировал статью на ${formatDateTime(result.publishedAt)}: ${result.url}` : `Принял статью и отправил в RSS: ${result.url}`)
await refresh()
}
async function uploadImage(file: File) {
const body = new FormData()
body.append("file", file)
const result = await api<{ url: string }>("/api/uploads/images", {
method: "POST",
body,
})
return result.url
}
async function setFeatureImageFile(file: File) {
if (!file.type.startsWith("image/") || !selectedArticleRef.current) return
setFeatureImageBusy(true)
try {
const url = await uploadImage(file)
setSelectedArticle((current) => (current ? { ...current, featureImageUrl: url } : current))
setEditorDirty(true)
} finally {
setFeatureImageBusy(false)
setFeatureImageDragActive(false)
}
}
useEffect(() => {
function handleImagePaste(event: ClipboardEvent) {
const file = imageFileFromClipboard(event)
if (!file) return
const target = pasteImageTargetRef.current
if (target === "feature" && featureImageHoverRef.current && selectedArticleRef.current) {
event.preventDefault()
event.stopImmediatePropagation()
pasteImageTargetRef.current = null
void setFeatureImageFile(file)
return
}
if (target === "editor" && editorImageHoverBlockRef.current && !featureImageHoverRef.current) {
event.preventDefault()
event.stopImmediatePropagation()
pasteImageTargetRef.current = null
void replaceEditorImageFile(file, editorImageHoverBlockRef.current)
}
}
window.addEventListener("paste", handleImagePaste, true)
return () => window.removeEventListener("paste", handleImagePaste, true)
}, [])
useEffect(() => {
if (!selectedArticle || !editorHolderRef.current) return
editorInstanceRef.current?.destroy()
editorHolderRef.current.innerHTML = ""
const articleData = htmlToEditorData(selectedArticle.editableHtml || selectedArticle.contentHtml, selectedArticle.title)
const editorData = appendSignatureToEditorData(
articleData,
selectedArticle.status !== "published" ? appSettings.signatureHtml : "",
)
if (editorData.blocks.length !== articleData.blocks.length) setEditorDirty(true)
const editor = new EditorJS({
holder: editorHolderRef.current,
data: editorData,
autofocus: false,
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: "",
},
},
image: {
class: ImageTool as unknown as ToolConstructable,
tunes: ["randomFrame"],
config: {
captionPlaceholder: "Подпись к изображению",
uploader: {
uploadByFile: async (file: File) => {
const url = await uploadImage(file)
scheduleEmptyImageCaptionNormalization()
return {
success: 1,
file: { url },
caption: imageCaptionFromPostTitle(),
}
},
uploadByUrl: async (url: string) => {
scheduleEmptyImageCaptionNormalization()
return {
success: 1,
file: { url },
caption: imageCaptionFromPostTitle(),
}
},
},
},
},
randomFrame: {
class: RandomFrameTune as unknown as ToolConstructable,
config: {
onReplace: replaceWithRandomFrame,
},
},
},
onChange: () => {
setEditorDirty(true)
scheduleEmptyImageCaptionNormalization()
},
})
editorInstanceRef.current = editor
editor.isReady.catch((error) => {
setStatusMessage(`Ошибка редактора: ${error}`)
})
const holder = editorHolderRef.current
const handleEditorMouseMove = (event: MouseEvent) => {
if (featureImageHoverRef.current) return
const block = findImageBlockFromElement(event.target)
if (block === editorImageHoverBlockRef.current) return
clearEditorImageHover()
if (block) {
editorImageHoverBlockRef.current = block
pasteImageTargetRef.current = "editor"
block.holder.classList.add("is-image-paste-target")
}
}
const handleEditorMouseLeave = () => {
clearEditorImageHover()
}
const handleEditorDragOver = (event: DragEvent) => {
if (featureImageHoverRef.current) return
const block = findImageBlockFromElement(event.target)
if (!block || !imageFileFromDataTransfer(event.dataTransfer)) return
event.preventDefault()
if (block !== editorImageHoverBlockRef.current) {
clearEditorImageHover()
editorImageHoverBlockRef.current = block
pasteImageTargetRef.current = "editor"
block.holder.classList.add("is-image-paste-target")
}
}
const handleEditorDrop = (event: DragEvent) => {
const file = event.dataTransfer ? imageFileFromDataTransfer(event.dataTransfer) : null
const block = findImageBlockFromElement(event.target)
if (!file || !block) return
event.preventDefault()
event.stopImmediatePropagation()
pasteImageTargetRef.current = null
void replaceEditorImageFile(file, block)
}
holder?.addEventListener("mousemove", handleEditorMouseMove)
holder?.addEventListener("mouseleave", handleEditorMouseLeave)
holder?.addEventListener("dragover", handleEditorDragOver)
holder?.addEventListener("drop", handleEditorDrop, true)
return () => {
holder?.removeEventListener("mousemove", handleEditorMouseMove)
holder?.removeEventListener("mouseleave", handleEditorMouseLeave)
holder?.removeEventListener("dragover", handleEditorDragOver)
holder?.removeEventListener("drop", handleEditorDrop, true)
clearEditorImageHover()
clearImageCaptionNormalizationTimers()
if (editorInstanceRef.current === editor) {
editorInstanceRef.current = null
}
editor.destroy()
}
}, [selectedArticle?.id, appSettings.signatureHtml])
function findImageBlockFromElement(target: EventTarget | null) {
const editor = editorInstanceRef.current
if (!editor || !(target instanceof Element)) return null
const holder = target.closest(".ce-block")
if (!holder || !holder.querySelector(".image-tool")) return null
const count = editor.blocks.getBlocksCount()
for (let index = 0; index < count; index += 1) {
const block = editor.blocks.getBlockByIndex(index)
if (block?.holder === holder && block.name === "image") {
return block
}
}
return null
}
function clearEditorImageHover() {
editorImageHoverBlockRef.current?.holder.classList.remove("is-image-paste-target")
editorImageHoverBlockRef.current = null
if (pasteImageTargetRef.current === "editor") {
pasteImageTargetRef.current = null
}
}
function imageCaptionFromPostTitle() {
return (editorTitleRef.current || selectedArticleRef.current?.title || "Изображение").trim()
}
function scheduleEmptyImageCaptionNormalization() {
clearImageCaptionNormalizationTimers()
imageCaptionNormalizeTimerRef.current = [80, 250, 700, 1500, 3000].map((delay) =>
window.setTimeout(() => {
void normalizeEmptyImageCaptions()
}, delay)
)
}
function clearImageCaptionNormalizationTimers() {
imageCaptionNormalizeTimerRef.current.forEach((timer) => window.clearTimeout(timer))
imageCaptionNormalizeTimerRef.current = []
}
async function normalizeEmptyImageCaptions() {
const editor = editorInstanceRef.current
const caption = imageCaptionFromPostTitle()
if (!editor || !caption) return
const count = editor.blocks.getBlocksCount()
for (let index = 0; index < count; index += 1) {
const block = editor.blocks.getBlockByIndex(index)
if (!block || block.name !== "image") continue
try {
const captionNode = block.holder.querySelector<HTMLElement>(".image-tool__caption")
const wrapperNode = block.holder.querySelector<HTMLElement>(".image-tool")
if (captionNode && !captionNode.textContent?.trim()) {
captionNode.innerHTML = caption
wrapperNode?.classList.add("image-tool--caption")
}
const data = await (block as unknown as { save: () => Promise<Record<string, any>> }).save()
if (!data.file?.url || String(data.caption || "").trim()) continue
await editor.blocks.update(block.id, { ...data, caption })
} catch {
// Editor.js briefly exposes uploading image blocks before they are saveable.
}
}
}
async function replaceEditorImageFile(file: File, blockToReplace?: BlockAPI | null) {
if (!file.type.startsWith("image/")) return
const editor = editorInstanceRef.current
const block = blockToReplace ?? editorImageHoverBlockRef.current
if (!editor || !block || block.name !== "image") {
return
}
setEditorBusy(true)
block.holder.classList.add("is-random-frame-loading")
try {
const previousData = await (block as unknown as { save: () => Promise<Record<string, any>> }).save()
const url = await uploadImage(file)
await editor.blocks.update(block.id, {
...previousData,
file: { ...(previousData.file || {}), url },
caption: previousData.caption || editorTitleRef.current || selectedArticleRef.current?.title || file.name,
})
setEditorDirty(true)
} finally {
block.holder.classList.remove("is-random-frame-loading")
setEditorBusy(false)
}
}
async function replaceWithRandomFrame(blockToReplace?: BlockAPI) {
const article = selectedArticleRef.current
if (!article?.videoId || !editorInstanceRef.current) return
const editor = editorInstanceRef.current
const index = editor.blocks.getCurrentBlockIndex()
const block = blockToReplace ?? (index >= 0 ? editor.blocks.getBlockByIndex(index) : undefined)
setEditorBusy(true)
block?.holder.classList.add("is-random-frame-loading")
try {
const result = await api<{ url: string; timestampSeconds: number }>(`/api/articles/${article.id}/random-frame`, { method: "POST" })
const data = {
file: { url: result.url },
caption: `${editorTitleRef.current || article.title} (${formatDuration(result.timestampSeconds)})`,
withBorder: false,
withBackground: false,
stretched: false,
}
if (block?.name === "image") {
await editor.blocks.update(block.id, data)
} else {
editor.blocks.insert("image", data, undefined, index >= 0 ? index + 1 : undefined, true)
}
setEditorDirty(true)
} finally {
block?.holder.classList.remove("is-random-frame-loading")
setEditorBusy(false)
}
}
async function saveArticle(showMessage = true) {
if (!selectedArticle) return selectedArticle
setEditorBusy(true)
try {
const editorData = await editorInstanceRef.current?.save()
const result = await api<ArticleDetail>(`/api/articles/${selectedArticle.id}`, {
method: "PATCH",
body: JSON.stringify({
title: editorTitle,
featureImageUrl: selectedArticle.featureImageUrl || "",
editableHtml: editorDataToHtml(editorData ?? htmlToEditorData("", editorTitle), editorTitle),
}),
})
setSelectedArticle(result)
setEditorTitle(result.title)
setEditorDirty(false)
await refresh()
if (showMessage) {
setStatusMessage(`Сохранил статью: ${result.title}`)
}
return result
} finally {
setEditorBusy(false)
}
}
async function saveAndPublishArticle() {
if (!selectedArticle) return
const article = editorDirty ? await saveArticle(false) : selectedArticle
if (!article) return
const scheduledAt = publishAt ? new Date(publishAt).toISOString() : undefined
await publishArticle(article.id, scheduledAt)
setSelectedArticle(null)
}
async function copyArticleText() {
if (!selectedArticle) return
let text = ""
if (editorInstanceRef.current) {
const editorData = await editorInstanceRef.current.save()
text = editorDataToPlainText(editorData, editorTitle)
}
if (!text) {
text = [editorTitle || selectedArticle.title, htmlToPlainText(selectedArticle.editableHtml || selectedArticle.contentHtml)]
.filter(Boolean)
.join("\n\n")
.trim()
}
if (!text) {
setCopyToast("Нечего копировать")
window.setTimeout(() => setCopyToast(""), 2200)
return
}
try {
await writeClipboardText(text)
setCopyToast("Статья скопирована в буфер обмена")
} catch (error) {
setCopyToast(`Не удалось скопировать: ${error instanceof Error ? error.message : error}`)
}
window.setTimeout(() => setCopyToast(""), 2200)
}
async function deleteArticle(id: number) {
const articleTitle = selectedArticle?.id === id ? selectedArticle.title : articles.find((article) => article.id === id)?.title
if (!window.confirm(`Удалить статью${articleTitle ? ` «${articleTitle}»` : ""}? Она пропадёт из списка и RSS.`)) return
await api<{ id: number; status: string }>(`/api/articles/${id}`, { method: "DELETE" })
setStatusMessage(`Удалил статью${articleTitle ? `: ${articleTitle}` : ""}`)
if (selectedArticle?.id === id) {
setSelectedArticle(null)
}
await refresh()
}
async function deleteVideo(id: number, title?: string) {
if (!window.confirm(`Удалить ролик${title ? ` «${title}»` : ""}? Он исчезнет из списка и больше не будет импортироваться из VK.`)) return
setVideoActionId(id)
try {
await api<{ id: number; status: string }>(`/api/videos/${id}`, { method: "DELETE" })
clearStoredChapterSelection(id)
setStatusMessage(`Удалил ролик${title ? `: ${title}` : ""}. Он исключен из повторного импорта.`)
await refresh()
} finally {
setVideoActionId(null)
}
}
if (authState !== "authenticated") {
return authState === "loading" ? <main className="flex min-h-screen items-center justify-center bg-muted/35 text-sm text-muted-foreground">Проверяю авторизацию...</main> : <AuthScreen hasPasskeys={hasPasskeys} onAuthenticated={handleAuthenticated} />
}
return (
<main className="min-h-screen bg-muted/35 editorial-studio">
<ToastNotice
message={copyToast || statusMessage}
onClose={() => (copyToast ? setCopyToast("") : setStatusMessage(""))}
/>
<div className="mx-auto flex w-full max-w-[1920px] flex-col gap-6 p-4 sm:p-6">
<header className="app-header flex flex-col gap-4 rounded-lg border bg-background p-4 md:flex-row md:items-center md:justify-between">
<div className="flex items-center gap-3">
<img
alt="Логотип Дзен-ассистента"
className="size-10 rounded-md object-cover"
src="/favicon.png"
/>
<div>
<h1 className="text-2xl font-semibold tracking-normal">Дзен-ассистент</h1>
<p className="text-sm text-muted-foreground">RSS-конвейер для статей из видео Николая Старикова</p>
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button variant={activeView === "settings" ? "secondary" : "outline"} onClick={() => setActiveView("settings")}>
<Settings2 data-icon="inline-start" />
Настройки
</Button>
<Button variant="outline" onClick={() => window.open(feedUrl, "_blank")}>
<ExternalLink data-icon="inline-start" />
RSS
</Button>
<Button className="vk-sync-button" disabled={busy} title="Обновить ролики из VK" aria-label="Обновить ролики из VK" onClick={scanSources}>
<RefreshCw data-icon="inline-start" />
VK
</Button>
</div>
</header>
{activeView === "dashboard" ? (
<div className="command-row grid gap-2 lg:grid-cols-2">
<form className="manual-import flex min-w-0 flex-col gap-2 rounded-md border bg-background p-2 sm:flex-row sm:items-center" onSubmit={importManualVideo}>
<Link2 className="hidden size-4 shrink-0 text-muted-foreground sm:block" />
<Input
aria-label="Ссылка на произвольный ролик"
className="min-w-0 flex-1"
onChange={(event) => setManualVideoUrl(event.target.value)}
placeholder="Вставьте ссылку на любой ролик"
value={manualVideoUrl}
/>
<Button disabled={manualVideoBusy || !manualVideoUrl.trim()} type="submit">
{manualVideoBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Link2 data-icon="inline-start" />}
Добавить ролик
</Button>
</form>
</div>
) : null}
{activeView === "settings" ? (
<SettingsPanel onBack={() => setActiveView("dashboard")} onSaved={handleSettingsSaved} />
) : <>
<section className="workspace-grid grid gap-5 xl:grid-cols-2">
<Card className="work-column min-w-0">
<CardHeader>
<div className="flex items-start justify-between gap-4">
<div>
<CardTitle>Ролики</CardTitle>
<CardDescription>Все ролики, прогресс обработки, логи и готовые черновики в одном списке.</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="work-list flex max-h-[72vh] flex-col gap-2 overflow-y-auto">
{productionVideos.length > 0 ? (
productionVideos.map((video) => {
const draftArticles = video.articles?.filter((article) => article.status !== "published") ?? []
const publishedArticle = video.articles?.find((article) => article.status === "published")
const fallbackArticleId = video.articleIds?.[0]
const draftArticleId = draftArticles[0]?.id ?? (publishedArticle ? undefined : fallbackArticleId)
const progress = Math.max(0, Math.min(100, video.progressPercent || 0))
const hasStarted = video.status !== "new" || progress > 0
const isActive = ["queued", "processing"].includes(video.status)
const isSubmitting = videoActionId === video.id
const hasDraftAction = draftArticles.length > 0 || Boolean(draftArticleId)
return (
<div key={video.id} className="production-item rounded-md border bg-background p-3">
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
{hasDraftAction ? <StatusBadge status="draft" /> : null}
{!hasDraftAction && !publishedArticle ? <StatusBadge status={video.status} /> : null}
{publishedArticle ? <StatusBadge status="published" /> : null}
<h3 className="min-w-0 flex-1 truncate text-sm font-semibold">{video.title || `Ролик #${video.id}`}</h3>
</div>
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
<span>{video.manual ? "Добавлено" : "Опубликовано"}: {formatVideoDate(video.publishedAt)}</span>
<span>Длительность: {formatDuration(video.durationSeconds)}</span>
</div>
{hasStarted && video.progressStage ? <p className="mt-2 line-clamp-2 text-sm text-muted-foreground">{video.progressStage}</p> : null}
{video.errorMessage ? <p className="mt-2 text-sm text-destructive">{video.errorMessage}</p> : null}
{draftArticles.length > 0 ? (
<div className="mt-3 space-y-2 rounded-md border border-zinc-200 bg-zinc-50 p-2">
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
<span>{draftArticles.length === 1 ? "Готовый черновик" : `Готовые черновики: ${draftArticles.length}`}</span>
</div>
<div className="space-y-1.5">
{draftArticles.map((article, index) => (
<button
key={article.id}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition hover:bg-background"
onClick={() => openArticlePreview(article.id)}
>
<FilePenLine className="size-4 shrink-0 text-muted-foreground" />
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">{index + 1}.</span>
<span className="min-w-0 flex-1 truncate font-medium">{article.title}</span>
</button>
))}
</div>
</div>
) : null}
</div>
<div className="flex shrink-0 flex-wrap gap-2">
{draftArticles.length > 0 ? (
<>
<Button size="sm" onClick={() => openArticlePreview(draftArticles[0].id)}>
<FileText data-icon="inline-start" />
{draftArticles.length === 1 ? "Черновик" : `${draftArticles.length} черновиков`}
</Button>
<Button
size="icon"
variant="outline"
disabled={isSubmitting}
title="Отправить на переделку"
aria-label="Отправить на переделку"
onClick={() => reprocessVideo(video)}
>
<RefreshCw className={`size-4 ${isSubmitting ? "animate-spin" : ""}`} />
</Button>
</>
) : publishedArticle ? (
<>
<Button size="sm" variant="outline" onClick={() => openArticlePreview(publishedArticle.id)}>
<FileText data-icon="inline-start" />
Статья
</Button>
<Button
size="icon"
variant="outline"
disabled={isSubmitting}
title="Сделать новый черновик по текущим правилам"
aria-label="Сделать новый черновик по текущим правилам"
onClick={() => reprocessVideo(video)}
>
<RefreshCw className={`size-4 ${isSubmitting ? "animate-spin" : ""}`} />
</Button>
</>
) : isActive ? (
<Button
size="sm"
variant="outline"
disabled={isSubmitting}
className="border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100 hover:text-amber-900"
onClick={() => processVideo(video.id, true)}
>
<RefreshCw data-icon="inline-start" className={isSubmitting ? "animate-spin" : ""} />
Перезапустить
</Button>
) : (
<Button
size="icon"
variant="outline"
disabled={isSubmitting}
title="Обработать"
aria-label="Обработать"
onClick={() => prepareVideoProcessing(video)}
>
<RefreshCw className="size-4" />
</Button>
)}
<Button size="icon" variant="outline" title="Логи" aria-label="Логи" onClick={() => openVideoLog(video.id)}>
<FileText className="size-4" />
</Button>
<Button
size="icon"
variant="outline"
disabled={isSubmitting}
title="Удалить ролик и больше не импортировать"
aria-label="Удалить ролик и больше не импортировать"
onClick={() => deleteVideo(video.id, video.title)}
>
<Trash2 className="size-4" />
</Button>
</div>
</div>
{hasStarted ? (
<div className="mt-4 flex items-center gap-3">
<div className="h-2 flex-1 overflow-hidden rounded-full bg-muted">
<div className="h-full rounded-full bg-primary transition-all" style={{ width: `${progress}%` }} />
</div>
<span className="w-12 text-right text-sm tabular-nums text-muted-foreground">{progress}%</span>
</div>
) : null}
</div>
)
})
) : (
<div className="rounded-md border border-dashed p-6 text-sm text-muted-foreground">Новых роликов и черновиков пока нет. Готовые материалы находятся в колонке «Статьи».</div>
)}
</CardContent>
</Card>
<Card className="work-column min-w-0">
<CardHeader>
<CardTitle>Статьи</CardTitle>
<CardDescription>Принятые материалы: уже вышедшие в RSS и отложенные по времени.</CardDescription>
</CardHeader>
<CardContent
className="work-list flex max-h-[72vh] flex-col gap-2 overflow-y-auto"
onScroll={(event) => {
const element = event.currentTarget
const distanceToBottom = element.scrollHeight - element.scrollTop - element.clientHeight
if (distanceToBottom < 180 && articlesHasMoreRef.current) {
void loadArticlesPage()
}
}}
>
{publishedArticles.length > 0 ? (
publishedArticles.map((article) => (
<div key={article.id} className="article-item rounded-md border bg-background p-3">
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
<button className="min-w-0 flex-1 text-left" onClick={() => openArticlePreview(article.id)}>
<div className="flex flex-wrap items-center gap-2">
{isScheduledForFuture(article.publishedAt) ? (
<Badge className="gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant="outline">
<Clock3 className="size-3.5" />
Отложено
</Badge>
) : (
<StatusBadge status={article.status} />
)}
<h3 className="min-w-0 flex-1 truncate text-sm font-semibold">{article.title}</h3>
</div>
<p className="mt-2 truncate text-xs text-muted-foreground">{article.url}</p>
{article.publishedAt ? (
<p className="mt-1 text-xs text-muted-foreground">
{isScheduledForFuture(article.publishedAt) ? "Выйдет в RSS" : "В RSS"}: {formatDateTime(article.publishedAt)}
</p>
) : null}
</button>
<div className="flex shrink-0 flex-wrap gap-2">
<Button size="icon" variant="outline" title="Открыть редактор" aria-label="Открыть редактор" onClick={() => openArticlePreview(article.id)}>
<FileText className="size-4" />
</Button>
<Button size="icon" variant="outline" title="Удалить" aria-label="Удалить" onClick={() => deleteArticle(article.id)}>
<Trash2 className="size-4" />
</Button>
<Button size="icon" variant="outline" title="Открыть на сайте" aria-label="Открыть на сайте" onClick={() => window.open(article.url, "_blank")}>
<ExternalLink className="size-4" />
</Button>
</div>
</div>
</div>
))
) : articlesLoading ? (
Array.from({ length: 5 }).map((_, index) => <ArticlePlaceholder key={`article-placeholder-initial-${index}`} />)
) : (
<div className="rounded-md border border-dashed p-6 text-sm text-muted-foreground">Принятых статей пока нет. Черновики открываются из роликов слева.</div>
)}
{publishedArticles.length > 0 && articlesLoading
? Array.from({ length: 3 }).map((_, index) => <ArticlePlaceholder key={`article-placeholder-more-${index}`} />)
: null}
{articlesHasMore && !articlesLoading ? (
<Button variant="outline" className="mt-1" onClick={() => loadArticlesPage()}>
<RefreshCw data-icon="inline-start" />
Загрузить еще
</Button>
) : null}
</CardContent>
</Card>
</section>
</>}
</div>
{chapterPlan ? (
<div className="modal-overlay fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm">
<div className="modal-panel flex max-h-[86vh] w-full max-w-4xl flex-col rounded-lg border bg-background shadow-lg">
<div className="flex items-start justify-between gap-4 border-b p-5">
<div className="min-w-0">
<h2 className="text-lg font-semibold tracking-normal">Разбить выпуск на статьи</h2>
<p className="mt-1 truncate text-sm text-muted-foreground">{chapterPlan.video.title || `Ролик #${chapterPlan.video.id}`}</p>
</div>
<Button variant="outline" size="icon" title="Закрыть" aria-label="Закрыть" onClick={() => setChapterPlan(null)}>
<X className="size-4" />
</Button>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-5">
<div className="rounded-md border border-sky-200 bg-sky-50 p-3 text-sm text-sky-900">
Найдены таймкоды в описании. Отмеченные пункты будут превращены в отдельные статьи, каждая по своему фрагменту выпуска.
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="text-sm text-muted-foreground">
Выбрано: {selectedChapterIds.size} из {chapterPlan.chapters.length}
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => {
const next = new Set(chapterPlan.chapters.map((chapter) => chapter.id))
storeChapterSelection(chapterPlan.video.id, next)
setSelectedChapterIds(next)
}}
>
Выбрать все
</Button>
<Button
variant="outline"
size="sm"
onClick={() => {
const next = new Set<string>()
storeChapterSelection(chapterPlan.video.id, next)
setSelectedChapterIds(next)
}}
>
Снять все
</Button>
</div>
</div>
<div className="space-y-2">
{chapterPlan.chapters.map((chapter) => {
const checked = selectedChapterIds.has(chapter.id)
return (
<label
key={chapter.id}
className={`flex cursor-pointer gap-3 rounded-md border p-3 transition ${
checked ? "border-primary/40 bg-primary/5" : "bg-background hover:bg-muted/40"
}`}
>
<input
type="checkbox"
className="mt-1 size-4 accent-primary"
checked={checked}
onChange={(event) => {
setSelectedChapterIds((current) => {
const next = new Set(current)
if (event.target.checked) next.add(chapter.id)
else next.delete(chapter.id)
storeChapterSelection(chapterPlan.video.id, next)
return next
})
}}
/>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline">
{chapter.startTimecode}
{chapter.endTimecode ? `–${chapter.endTimecode}` : ""}
</Badge>
<span className="text-xs text-muted-foreground">{formatDuration(chapter.durationSeconds)}</span>
</div>
<p className="mt-1 text-sm font-medium leading-snug">{chapter.title}</p>
</div>
</label>
)
})}
</div>
</div>
<div className="flex flex-wrap items-center justify-end gap-2 border-t p-5">
<Button variant="outline" onClick={() => setChapterPlan(null)}>
Отмена
</Button>
<Button disabled={videoActionId === chapterPlan.video.id || selectedChapterIds.size === 0} onClick={processSelectedChapters}>
<RefreshCw data-icon="inline-start" className={videoActionId === chapterPlan.video.id ? "animate-spin" : ""} />
Обработать выбранные
</Button>
</div>
</div>
</div>
) : null}
{selectedLog ? (
<div className="modal-overlay fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm">
<div className="modal-panel flex max-h-[82vh] w-full max-w-3xl flex-col rounded-lg border bg-background shadow-lg">
<div className="flex items-start justify-between gap-4 border-b p-5">
<div className="min-w-0">
<h2 className="text-lg font-semibold tracking-normal">Логи обработки</h2>
<p className="mt-1 truncate text-sm text-muted-foreground">{selectedLog.title || `Ролик #${selectedLog.id}`}</p>
</div>
<Button variant="outline" size="sm" onClick={closeVideoLog}>
Закрыть
</Button>
</div>
<div className="flex flex-col gap-4 overflow-y-auto p-5">
<div className="grid gap-3 md:grid-cols-3">
<div className="rounded-md border p-3">
<p className="text-xs text-muted-foreground">Статус</p>
<Badge className="mt-2" variant={statusVariant(selectedLog.status)}>
{selectedLog.status}
</Badge>
</div>
<div className="rounded-md border p-3">
<p className="text-xs text-muted-foreground">Этап</p>
<p className="mt-2 text-sm font-medium">{selectedLog.progressStage || "—"}</p>
</div>
<div className="rounded-md border p-3">
<p className="text-xs text-muted-foreground">Прогресс</p>
<p className="mt-2 text-sm font-medium">{selectedLog.progressPercent || 0}%</p>
</div>
</div>
{selectedLog.errorMessage ? <p className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{selectedLog.errorMessage}</p> : null}
<pre className="max-h-[46vh] overflow-auto rounded-md border bg-muted/40 p-4 text-xs leading-5 text-foreground">
{selectedLog.progressLog || "Лог пока пуст."}
</pre>
</div>
</div>
</div>
) : null}
{selectedArticle ? (
<div className="modal-overlay fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-3 backdrop-blur-sm">
<div className="modal-panel flex max-h-[92vh] w-full max-w-[1280px] flex-col overflow-hidden rounded-lg border bg-background shadow-lg">
<div className="article-modal-header flex min-w-0 items-start justify-between gap-4 border-b p-5">
<div className="article-modal-intro min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
{isScheduledForFuture(selectedArticle.publishedAt) ? (
<Badge className="gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant="outline">
<Clock3 className="size-3.5" />
Отложено
</Badge>
) : (
<StatusBadge status={selectedArticle.status} />
)}
<h2 className="min-w-0 flex-1 truncate text-lg font-semibold tracking-normal">Редактирование статьи</h2>
{editorDirty ? <Badge variant="secondary">есть правки</Badge> : null}
</div>
<p className="mt-1 text-sm text-muted-foreground">Редактируйте блоки как в Medium. Для картинки выберите image-блок и нажмите кнопку случайного кадра.</p>
</div>
<div className="article-modal-actions flex shrink-0 flex-wrap justify-end gap-2">
<input
ref={featureImageInputRef}
className="hidden"
type="file"
accept="image/*"
onChange={async (event) => {
const file = event.currentTarget.files?.[0]
event.currentTarget.value = ""
if (file) await setFeatureImageFile(file)
}}
/>
<Button
size="icon"
variant="outline"
disabled={editorBusy}
title="Скопировать заголовок и текст без картинок"
aria-label="Скопировать заголовок и текст без картинок"
onClick={copyArticleText}
>
<Copy className="size-4" />
</Button>
<Button size="icon" variant="outline" disabled={editorBusy || !editorDirty} title="Сохранить" aria-label="Сохранить" onClick={() => saveArticle()}>
<Save className="size-4" />
</Button>
{selectedArticle.status !== "published" || isScheduledForFuture(selectedArticle.publishedAt) ? (
<>
<label className="article-publish-time flex h-9 items-center gap-2 rounded-md border bg-background px-3 text-xs text-muted-foreground" title="Время выхода в RSS">
<Clock3 className="size-4" />
<input
type="datetime-local"
className="w-[190px] bg-transparent text-sm text-foreground outline-none"
value={publishAt}
onChange={(event) => setPublishAt(event.target.value)}
/>
</label>
<Button size="icon" disabled={editorBusy} title="Запланировать или принять в RSS" aria-label="Запланировать или принять в RSS" onClick={saveAndPublishArticle}>
<Radio className="size-4" />
</Button>
</>
) : (
<Button size="icon" variant="outline" title="Открыть на сайте" aria-label="Открыть на сайте" onClick={() => window.open(selectedArticle.url, "_blank")}>
<ExternalLink className="size-4" />
</Button>
)}
<Button size="icon" variant="outline" disabled={editorBusy} title="Удалить" aria-label="Удалить" onClick={() => deleteArticle(selectedArticle.id)}>
<Trash2 className="size-4" />
</Button>
<Button variant="outline" size="icon" title="Закрыть" aria-label="Закрыть" onClick={() => setSelectedArticle(null)}>
<X className="size-4" />
</Button>
</div>
</div>
<div className="article-modal-body overflow-y-auto bg-zinc-50 p-4 sm:p-6">
<article className="article-modal-content mx-auto w-full max-w-[1024px] rounded-lg border bg-white px-5 py-7 shadow-sm sm:px-8 lg:px-10">
<div className="mb-6">
<div className="mb-2 flex items-center justify-between gap-3">
<div>
<p className="text-sm font-semibold text-zinc-950">Feature Image</p>
<p className="text-xs text-muted-foreground">Главная обложка публикации для RSS и Дзена.</p>
</div>
<Button
size="sm"
variant="outline"
disabled={featureImageBusy}
onClick={() => featureImageInputRef.current?.click()}
>
<ImagePlus data-icon="inline-start" className={featureImageBusy ? "animate-pulse" : ""} />
Выбрать
</Button>
</div>
<div
className={`relative flex aspect-video w-full cursor-pointer items-center justify-center overflow-hidden rounded-md border border-dashed transition ${
featureImageDragActive ? "border-primary bg-primary/5" : "border-zinc-300 bg-zinc-50 hover:bg-zinc-100"
}`}
onClick={() => featureImageInputRef.current?.click()}
onMouseEnter={() => {
clearEditorImageHover()
pasteImageTargetRef.current = "feature"
featureImageHoverRef.current = true
setFeatureImageHoverActive(true)
}}
onMouseLeave={() => {
featureImageHoverRef.current = false
if (pasteImageTargetRef.current === "feature") {
pasteImageTargetRef.current = null
}
setFeatureImageHoverActive(false)
}}
onDragOver={(event) => {
event.preventDefault()
clearEditorImageHover()
pasteImageTargetRef.current = "feature"
setFeatureImageDragActive(true)
}}
onDragLeave={() => {
if (!featureImageHoverRef.current && pasteImageTargetRef.current === "feature") {
pasteImageTargetRef.current = null
}
setFeatureImageDragActive(false)
}}
onDrop={async (event) => {
event.preventDefault()
const file = imageFileFromDataTransfer(event.dataTransfer)
if (file) await setFeatureImageFile(file)
else setFeatureImageDragActive(false)
}}
>
{selectedArticle.featureImageUrl ? (
<img src={selectedArticle.featureImageUrl} alt={selectedArticle.title} className="h-full w-full object-cover" />
) : (
<div className="flex flex-col items-center gap-2 text-center text-sm text-muted-foreground">
<ImagePlus className="size-7" />
<span>Перетащите обложку сюда или выберите файл</span>
</div>
)}
{featureImageBusy ? (
<div className="absolute inset-0 flex items-center justify-center bg-background/70 text-sm font-medium">
Загружаю...
</div>
) : null}
{!featureImageBusy && (featureImageHoverActive || featureImageDragActive) ? (
<div className="absolute inset-0 flex items-center justify-center bg-zinc-950/55 p-4 text-center text-sm font-semibold text-white backdrop-blur-[1px] transition">
<div className="rounded-full border border-white/35 bg-zinc-950/70 px-4 py-2 shadow-lg">
Вставьте изображение из буфера обмена или принесите файл
</div>
</div>
) : null}
</div>
</div>
<Textarea
ref={titleTextareaRef}
rows={1}
className="mx-auto h-auto min-h-0 max-w-3xl resize-none overflow-hidden border-0 bg-transparent px-0 py-0 text-3xl font-bold leading-tight tracking-normal text-zinc-950 shadow-none focus-visible:ring-0 sm:text-4xl"
value={editorTitle}
onChange={(event) => {
setEditorTitle(event.target.value)
setEditorDirty(true)
}}
/>
<div
key={selectedArticle.id}
ref={editorHolderRef}
className="article-editor article-editorjs mt-6"
/>
</article>
</div>
</div>
</div>
) : null}
</main>
)
}