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

3172 lines
140 KiB
TypeScript
Raw Normal View History

import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from "react"
2026-06-27 14:07:10 +03:00
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,
2026-06-27 14:07:10 +03:00
CheckCircle2,
2026-08-15 13:25:21 +03:00
ChevronDown,
ChevronLeft,
2026-06-27 14:07:10 +03:00
Clock3,
Copy,
2026-06-27 14:07:10 +03:00
ExternalLink,
FilePenLine,
FileText,
Fingerprint,
2026-06-27 14:07:10 +03:00
ImagePlus,
Link2,
2026-06-27 14:07:10 +03:00
Loader2,
Radio,
RefreshCw,
Save,
Settings2,
2026-06-27 14:07:10 +03:00
Trash2,
2026-08-15 11:23:51 +03:00
Upload,
2026-06-27 14:07:10 +03:00
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"
2026-06-27 14:07:10 +03:00
type AppSettings = {
signatureHtml: string
llmInstructions: string
imageApiUrl: string
imageModel: string
imageApiTokenConfigured: boolean
draftApiKeyConfigured: boolean
draftApiKeyPrefix: string
}
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[]
2026-06-27 14:07:10 +03:00
}
type VideoArticle = {
id: number
title: string
status: string
}
type Video = {
id: number
title: string
sourceUrl: string
manual?: boolean
2026-06-27 14:07:10 +03:00
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
2026-06-27 14:07:10 +03:00
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
videoSourceUrl?: string
2026-06-27 14:07:10 +03:00
}
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
}
2026-08-15 11:23:51 +03:00
type VideoStorage = {
totalBytes: number
usedBytes: number
freeBytes: number
usedPercent: number
}
type LocalVideoUpload = {
name: string
loaded: number
total: number
status: "uploading" | "complete" | "cancelled" | "error"
errorMessage?: string
}
2026-06-27 14:07:10 +03:00
type EditorBlock = OutputData["blocks"][number]
type RandomFrameTuneConfig = {
onReplace?: (block: BlockAPI) => void | Promise<void>
}
type ImageGenerationTuneConfig = {
onRegenerate?: (block: BlockAPI) => void | Promise<void>
}
type VkVideoBlockData = { sourceUrl?: string }
class VkVideoTool {
private data: VkVideoBlockData
constructor({ data }: { data: VkVideoBlockData }) {
this.data = data || {}
}
static get isReadOnlySupported() { return true }
render() {
const element = document.createElement("section")
element.className = "editor-vk-video rounded-md border border-sky-200 bg-sky-50 p-4"
const link = document.createElement("a")
link.href = this.data.sourceUrl || "#"
link.target = "_blank"
link.rel = "noreferrer"
link.className = "flex items-center gap-2 font-medium text-sky-900 underline-offset-2 hover:underline"
link.textContent = "Видео VK — можно перемещать как обычный блок"
element.append(link)
return element
}
save() { return this.data }
}
2026-06-27 14:07:10 +03:00
const ARTICLES_PAGE_SIZE = 10
const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:"
2026-08-15 11:23:51 +03:00
const LOCAL_VIDEO_EXTENSIONS = new Set(["mp4", "webm", "mov", "mkv"])
const LOW_STORAGE_WARNING_BYTES = 10 * 1024 * 1024 * 1024
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
}
2026-06-27 14:07:10 +03:00
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)
},
}
}
}
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: '<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="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>',
label: "Перегенерировать по тексту",
onActivate: () => {
void this.config.onRegenerate?.(this.block)
},
}
}
}
2026-06-27 14:07:10 +03:00
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>
}
const slugTransliteration: Record<string, string> = {
а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e", ж: "zh", з: "z", и: "i", й: "y",
к: "k", л: "l", м: "m", н: "n", о: "o", п: "p", р: "r", с: "s", т: "t", у: "u", ф: "f",
х: "h", ц: "ts", ч: "ch", ш: "sh", щ: "shch", ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya",
}
function slugFromTitle(title: string) {
return title
.toLowerCase()
.split("")
.map((character) => slugTransliteration[character] ?? character)
.join("")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 240)
.replace(/-+$/g, "")
}
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 (
2026-08-11 16:27:16 +03:00
<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 ? (
<>
2026-08-11 16:27:16 +03:00
<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>
)
}
2026-06-27 14:07:10 +03:00
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, videoSourceUrl?: string): OutputData {
2026-06-27 14:07:10 +03:00
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") {
if (node.textContent?.trim() === "[[VK_VIDEO]]") {
blocks.push({ type: "vkVideo", data: { sourceUrl: videoSourceUrl || "" } })
return
}
2026-06-27 14:07:10 +03:00
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
2026-06-27 14:07:10 +03:00
return `<figure><img src="${escapeHtml(url)}" alt="${escapeHtml(caption)}"><figcaption>${caption}</figcaption></figure>`
}
if (block.type === "vkVideo") return "<p>[[VK_VIDEO]]</p>"
2026-06-27 14:07:10 +03:00
return `<p>${item.text || ""}</p>`
})
.filter(Boolean)
.join("\n")
}
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 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<ImageGenerationTarget, "cover">) {
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<AppSettings>({
signatureHtml: "",
llmInstructions: "",
imageApiUrl: "https://polza.ai/api",
imageModel: "google/gemini-3.1-flash-image",
imageApiTokenConfigured: false,
draftApiKeyConfigured: false,
draftApiKeyPrefix: "",
})
const [imageApiToken, setImageApiToken] = useState("")
const [draftApiKey, setDraftApiKey] = 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<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(),
imageApiUrl: settings.imageApiUrl.trim(),
imageModel: settings.imageModel.trim(),
imageApiTokenConfigured: settings.imageApiTokenConfigured,
draftApiKeyConfigured: settings.draftApiKeyConfigured,
draftApiKeyPrefix: settings.draftApiKeyPrefix,
}
const payload: Record<string, unknown> = { ...next }
if (imageApiToken.trim()) payload.imageApiToken = imageApiToken.trim()
const saved = await api<AppSettings>("/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<AppSettings>("/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 generateDraftApiKey() {
setSaving(true)
try {
const generated = await api<{ apiKey: string; prefix: string }>("/api/settings/draft-api-key", { method: "POST" })
setDraftApiKey(generated.apiKey)
setSettings((current) => ({ ...current, draftApiKeyConfigured: true, draftApiKeyPrefix: generated.prefix }))
setMessage("API-ключ создан. Скопируйте его сейчас: повторно показать ключ нельзя.")
} catch (error) {
setMessage(`Не удалось создать API-ключ: ${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>
2026-08-24 20:45:58 +03:00
<div className="flex flex-wrap items-center justify-end gap-2">
<Button variant="outline" onClick={onBack}>
<ArrowLeft data-icon="inline-start" />
К роликам
</Button>
<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>
</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>
)}
{!loading ? (
<Card>
<CardHeader>
<CardTitle>Генерация изображений</CardTitle>
<CardDescription>Polza вызывается только с сервера. Токен не возвращается в браузер и не попадает в черновики.</CardDescription>
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
<label className="grid gap-1.5 text-sm font-medium sm:col-span-1">
API URL
<Input
value={settings.imageApiUrl}
placeholder="https://polza.ai/api"
onChange={(event) => { setSettings((current) => ({ ...current, imageApiUrl: event.target.value })); setDirty(true) }}
/>
</label>
<label className="grid gap-1.5 text-sm font-medium sm:col-span-1">
Модель
<Input
value={settings.imageModel}
placeholder="google/gemini-3.1-flash-image"
onChange={(event) => { setSettings((current) => ({ ...current, imageModel: event.target.value })); setDirty(true) }}
/>
</label>
<div className="grid gap-1.5 sm:col-span-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<label className="text-sm font-medium" htmlFor="image-api-token">API-токен</label>
<span className={`text-xs ${settings.imageApiTokenConfigured ? "text-emerald-700" : "text-muted-foreground"}`}>
{settings.imageApiTokenConfigured ? "Токен задан" : "Токен не задан"}
</span>
</div>
<div className="flex flex-wrap gap-2">
<Input
id="image-api-token"
className="min-w-[14rem] flex-1"
type="password"
autoComplete="new-password"
value={imageApiToken}
placeholder={settings.imageApiTokenConfigured ? "Введите новый токен для замены" : "Введите токен Polza"}
onChange={(event) => { setImageApiToken(event.target.value); setDirty(true) }}
/>
{settings.imageApiTokenConfigured ? <Button type="button" variant="outline" disabled={saving} onClick={clearImageApiToken}>Удалить токен</Button> : null}
</div>
<p className="text-xs text-muted-foreground">Пустое поле не меняет уже сохранённый токен.</p>
</div>
</CardContent>
</Card>
) : null}
{!loading ? (
<Card>
<CardHeader>
<CardTitle>API для создания черновиков</CardTitle>
<CardDescription>Внешний ИИ сможет создавать новые черновики через POST-запрос. При перевыпуске старый ключ сразу перестаёт работать.</CardDescription>
</CardHeader>
<CardContent className="grid gap-3">
<div className="flex flex-wrap items-center justify-between gap-2 text-sm">
<span className="font-medium">Статус</span>
<span className={settings.draftApiKeyConfigured ? "text-emerald-700" : "text-muted-foreground"}>
{settings.draftApiKeyConfigured ? `Ключ задан (${settings.draftApiKeyPrefix}...)` : "Ключ ещё не создан"}
</span>
</div>
{draftApiKey ? (
<div className="grid gap-2 rounded-md border border-amber-200 bg-amber-50 p-3">
<p className="text-xs text-amber-900">Скопируйте ключ сейчас. В целях безопасности он больше не будет показан в настройках.</p>
<div className="flex flex-wrap gap-2">
<Input className="min-w-[18rem] flex-1 font-mono text-xs" readOnly value={draftApiKey} />
<Button type="button" variant="outline" onClick={() => void writeClipboardText(draftApiKey).then(() => setMessage("API-ключ скопирован"))}>
<Copy data-icon="inline-start" />
Копировать
</Button>
</div>
</div>
) : null}
<div className="flex flex-wrap items-center gap-2">
<Button type="button" variant="outline" disabled={saving} onClick={() => void generateDraftApiKey()}>
{saving ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <RefreshCw data-icon="inline-start" />}
{settings.draftApiKeyConfigured ? "Перевыпустить ключ" : "Создать API-ключ"}
</Button>
<span className="text-xs text-muted-foreground">Передавайте ключ только в заголовке Authorization: Bearer.</span>
</div>
</CardContent>
</Card>
) : null}
</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)
}
2026-06-27 14:07:10 +03:00
function formatDuration(seconds?: number) {
if (!seconds) return "—"
const minutes = Math.floor(seconds / 60)
const rest = seconds % 60
return `${minutes}:${String(rest).padStart(2, "0")}`
}
2026-08-15 11:23:51 +03:00
function formatFileSize(bytes?: number) {
const value = Math.max(0, bytes || 0)
if (value >= 1024 * 1024 * 1024) {
return `${(value / (1024 * 1024 * 1024)).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} ГБ`
}
if (value >= 1024 * 1024) {
return `${(value / (1024 * 1024)).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} МБ`
}
return `${Math.round(value / 1024).toLocaleString("ru-RU")} КБ`
}
function uploadErrorMessage(responseText: string) {
try {
const payload = JSON.parse(responseText) as { detail?: string }
return payload.detail || responseText
} catch {
return responseText || "Не удалось загрузить видео."
}
}
function localVideoExtension(file: File) {
return file.name.split(".").pop()?.toLowerCase() || ""
}
2026-06-27 14:07:10 +03:00
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>
)
}
2026-08-15 11:35:21 +03:00
if (normalized === "planning") {
return (
<Badge className="gap-1.5 border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-50" variant="outline">
<Loader2 className="size-3.5 animate-spin" />
Хронометраж
</Badge>
)
}
if (normalized === "planned") {
return (
<Badge className="gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant="outline">
<CheckCircle2 className="size-3.5" />
Темы готовы
</Badge>
)
}
2026-06-27 14:07:10 +03:00
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: "",
imageApiUrl: "https://polza.ai/api",
imageModel: "google/gemini-3.1-flash-image",
imageApiTokenConfigured: false,
draftApiKeyConfigured: false,
draftApiKeyPrefix: "",
})
2026-06-27 14:07:10 +03:00
const [videos, setVideos] = useState<Video[]>([])
const [articles, setArticles] = useState<Article[]>([])
2026-08-15 15:00:57 +03:00
const [manualDrafts, setManualDrafts] = useState<Article[]>([])
2026-06-27 14:07:10 +03:00
const [articlesHasMore, setArticlesHasMore] = useState(false)
const [articlesLoading, setArticlesLoading] = useState(false)
2026-08-15 15:00:57 +03:00
const [manualArticleCreating, setManualArticleCreating] = useState(false)
2026-06-27 14:07:10 +03:00
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())
2026-06-27 14:07:10 +03:00
const [editorTitle, setEditorTitle] = useState("")
2026-08-24 11:59:38 +03:00
const [editorSlug, setEditorSlug] = useState("")
2026-06-27 14:07:10 +03:00
const [publishAt, setPublishAt] = useState("")
const [editorDirty, setEditorDirty] = useState(false)
const [editorBusy, setEditorBusy] = useState(false)
2026-08-15 13:25:21 +03:00
const [articleCloseConfirmOpen, setArticleCloseConfirmOpen] = useState(false)
const [articleMoreOpen, setArticleMoreOpen] = useState(false)
const [featureImageBusy, setFeatureImageBusy] = useState(false)
const [featureImageDragActive, setFeatureImageDragActive] = useState(false)
const [featureImageHoverActive, setFeatureImageHoverActive] = useState(false)
const [imageGenerationBatch, setImageGenerationBatch] = useState<ImageGenerationBatch | null>(null)
const [imageGenerationStarting, setImageGenerationStarting] = useState(false)
const [copyToast, setCopyToast] = useState("")
2026-06-27 14:07:10 +03:00
const [statusMessage, setStatusMessage] = useState("")
const [busy, setBusy] = useState(false)
const [manualVideoUrl, setManualVideoUrl] = useState("")
const [manualVideoBusy, setManualVideoBusy] = useState(false)
2026-08-15 11:23:51 +03:00
const [videoStorage, setVideoStorage] = useState<VideoStorage | null>(null)
const [localVideoUpload, setLocalVideoUpload] = useState<LocalVideoUpload | null>(null)
const [localVideoDragActive, setLocalVideoDragActive] = useState(false)
2026-06-27 14:07:10 +03:00
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)
2026-08-15 11:23:51 +03:00
const localVideoInputRef = useRef<HTMLInputElement | null>(null)
const localVideoUploadRequestRef = useRef<XMLHttpRequest | null>(null)
const featureImageHoverRef = useRef(false)
const editorImageHoverBlockRef = useRef<BlockAPI | null>(null)
const pasteImageTargetRef = useRef<"feature" | "editor" | null>(null)
const imageCaptionNormalizeTimerRef = useRef<number[]>([])
2026-06-27 14:07:10 +03:00
const logSocketRef = useRef<WebSocket | null>(null)
const selectedArticleRef = useRef<ArticleDetail | null>(null)
const editorTitleRef = useRef("")
const titleTextareaRef = useRef<HTMLTextAreaElement | null>(null)
2026-08-15 13:25:21 +03:00
const articleBackButtonRef = useRef<HTMLButtonElement | null>(null)
const articleMoreRef = useRef<HTMLDetailsElement | null>(null)
2026-06-27 14:07:10 +03:00
const articlesOffsetRef = useRef(0)
const articlesLoadingRef = useRef(false)
const articlesHasMoreRef = useRef(false)
const appliedImageGenerationJobsRef = useRef<Set<string>>(new Set())
const imageGenerationPollRef = useRef<number | null>(null)
2026-06-27 14:07:10 +03:00
const handleAuthenticated = useCallback(() => {
setAuthState("authenticated")
}, [])
const handleSettingsSaved = useCallback((next: AppSettings) => {
setAppSettings(next)
}, [])
2026-06-27 14:07:10 +03:00
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
})
2026-06-27 14:07:10 +03:00
.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]
)
2026-08-15 11:23:51 +03:00
const localUploadPercent = localVideoUpload?.total ? Math.min(100, Math.round((localVideoUpload.loaded / localVideoUpload.total) * 100)) : 0
const videoStoragePercent = Math.max(0, Math.min(100, videoStorage?.usedPercent ?? 0))
const videoStorageLow = Boolean(videoStorage && videoStorage.freeBytes < LOW_STORAGE_WARNING_BYTES)
2026-06-27 14:07:10 +03:00
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 {
2026-08-15 15:00:57 +03:00
const [nextVideos, nextArticles, nextManualDrafts] = await Promise.all([
2026-06-27 14:07:10 +03:00
api<Video[]>("/api/videos"),
api<ArticlesPage>(`/api/articles?status=published&limit=${ARTICLES_PAGE_SIZE}&offset=0`),
2026-08-15 15:00:57 +03:00
api<ArticlesPage>("/api/articles?status=draft&manual=true&limit=50"),
2026-06-27 14:07:10 +03:00
])
setVideos(nextVideos)
setArticles(nextArticles.items)
2026-08-15 15:00:57 +03:00
setManualDrafts(nextManualDrafts.items)
2026-06-27 14:07:10 +03:00
articlesOffsetRef.current = nextArticles.items.length
articlesHasMoreRef.current = nextArticles.hasMore
setArticlesHasMore(nextArticles.hasMore)
} finally {
if (showArticlePlaceholders) {
setArticlesLoading(false)
}
}
}
2026-08-15 11:23:51 +03:00
async function loadVideoStorage() {
try {
setVideoStorage(await api<VideoStorage>("/api/storage/videos"))
} catch {
setVideoStorage(null)
}
}
2026-06-27 14:07:10 +03:00
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}`)
})
2026-06-27 14:07:10 +03:00
}, [])
2026-08-11 16:23:56 +03:00
useEffect(() => {
if (authState !== "authenticated") return
refresh().catch((error) => setStatusMessage(`Ошибка загрузки: ${error.message}`))
2026-08-15 11:23:51 +03:00
void loadVideoStorage()
2026-08-11 16:23:56 +03:00
api<AppSettings>("/api/settings").then(setAppSettings).catch(() => undefined)
}, [authState])
useEffect(() => {
if (!statusMessage) return
const timer = window.setTimeout(() => setStatusMessage(""), 4200)
return () => window.clearTimeout(timer)
}, [statusMessage])
2026-06-27 14:07:10 +03:00
useEffect(() => {
if (authState !== "authenticated" || activeVideos.length === 0) return
2026-06-27 14:07:10 +03:00
const timer = window.setInterval(() => {
refresh().catch((error) => {
setStatusMessage(`Ошибка обновления: ${error.message}`)
})
}, 5000)
return () => window.clearInterval(timer)
}, [activeVideos.length, authState])
2026-06-27 14:07:10 +03:00
useEffect(() => {
videos.forEach((video) => {
if (video.status === "drafted" && (video.articles?.length || 0) > 0) {
clearStoredChapterSelection(video.id)
}
})
}, [videos])
2026-06-27 14:07:10 +03:00
useEffect(() => () => {
logSocketRef.current?.close()
2026-08-15 11:23:51 +03:00
localVideoUploadRequestRef.current?.abort()
clearImageCaptionNormalizationTimers()
2026-06-27 14:07:10 +03:00
}, [])
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)
}
}
2026-08-15 11:23:51 +03:00
function uploadLocalVideo(file: File) {
if (localVideoUpload?.status === "uploading") return
if (!LOCAL_VIDEO_EXTENSIONS.has(localVideoExtension(file))) {
setLocalVideoUpload({
name: file.name,
loaded: 0,
total: file.size,
status: "error",
errorMessage: "Поддерживаются файлы MP4, WebM, MOV и MKV.",
})
return
}
setLocalVideoUpload({ name: file.name, loaded: 0, total: file.size, status: "uploading" })
const request = new XMLHttpRequest()
localVideoUploadRequestRef.current = request
request.open("POST", "/api/videos/upload")
request.responseType = "text"
request.withCredentials = true
request.upload.onprogress = (event) => {
setLocalVideoUpload((current) => {
if (!current || current.status !== "uploading") return current
return {
...current,
loaded: event.loaded,
total: event.lengthComputable ? event.total : file.size,
}
})
}
request.onload = () => {
if (localVideoUploadRequestRef.current === request) {
localVideoUploadRequestRef.current = null
}
if (request.status < 200 || request.status >= 300) {
setLocalVideoUpload({
name: file.name,
loaded: 0,
total: file.size,
status: "error",
errorMessage: uploadErrorMessage(request.responseText),
})
return
}
setLocalVideoUpload({ name: file.name, loaded: file.size, total: file.size, status: "complete" })
setStatusMessage(`Видео «${file.name}» загружено и готово к обработке.`)
void Promise.all([refresh(), loadVideoStorage()]).catch((error) => {
setStatusMessage(`Видео загружено, но список не обновился: ${error instanceof Error ? error.message : String(error)}`)
})
}
request.onerror = () => {
if (localVideoUploadRequestRef.current === request) {
localVideoUploadRequestRef.current = null
}
setLocalVideoUpload({
name: file.name,
loaded: 0,
total: file.size,
status: "error",
errorMessage: "Сеть прервала загрузку. Попробуйте ещё раз.",
})
}
request.onabort = () => {
if (localVideoUploadRequestRef.current === request) {
localVideoUploadRequestRef.current = null
}
setLocalVideoUpload((current) => current ? { ...current, status: "cancelled" } : current)
}
const formData = new FormData()
formData.append("file", file)
request.send(formData)
}
function selectLocalVideo(file?: File | null) {
if (!file) return
uploadLocalVideo(file)
}
function cancelLocalVideoUpload() {
localVideoUploadRequestRef.current?.abort()
}
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) {
2026-08-15 11:35:21 +03:00
if (video.sourceUrl.startsWith("upload://")) {
const task = await api<{ taskId: string }>(`/api/videos/${video.id}/chapter-plan`, { method: "POST" })
setStatusMessage(`Строю хронометраж ролика. Транскрибация и темы появятся в журнале. Task: ${task.taskId}`)
await refresh()
return
}
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[]) {
2026-06-27 14:07:10 +03:00
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)
2026-06-27 14:07:10 +03:00
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)
}
2026-06-27 14:07:10 +03:00
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)
}
2026-08-15 15:00:57 +03:00
async function initializeArticleEditor(result: ArticleDetail) {
2026-06-27 14:07:10 +03:00
setSelectedArticle(result)
setEditorTitle(result.title)
setEditorSlug(slugFromTitle(result.title))
2026-06-27 14:07:10 +03:00
setPublishAt(toDateTimeLocalValue(result.publishedAt) || currentDateTimeLocalValue())
setEditorDirty(false)
2026-08-15 13:25:21 +03:00
setArticleCloseConfirmOpen(false)
setArticleMoreOpen(false)
appliedImageGenerationJobsRef.current = new Set()
try {
2026-08-15 15:00:57 +03:00
const active = await fetch(`/api/articles/${result.id}/image-generations/active`)
if (active.status === 204) {
setImageGenerationBatch(null)
} else if (active.ok) {
setImageGenerationBatch(await active.json() as ImageGenerationBatch)
}
} catch {
// The editor itself remains usable if a status recovery request fails.
}
2026-06-27 14:07:10 +03:00
}
2026-08-15 15:00:57 +03:00
async function openArticlePreview(id: number) {
await initializeArticleEditor(await api<ArticleDetail>(`/api/articles/${id}`))
}
async function createManualArticle() {
setManualArticleCreating(true)
try {
const article = await api<ArticleDetail>("/api/articles", { method: "POST" })
setManualDrafts((current) => [article, ...current.filter((currentArticle) => currentArticle.id !== article.id)])
await initializeArticleEditor(article)
} finally {
setManualArticleCreating(false)
}
}
2026-06-27 14:07:10 +03:00
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)
}, [])
2026-06-27 14:07:10 +03:00
useEffect(() => {
if (!selectedArticle || !editorHolderRef.current) return
editorInstanceRef.current?.destroy()
editorHolderRef.current.innerHTML = ""
const editorData = htmlToEditorData(
selectedArticle.editableHtml || selectedArticle.contentHtml,
selectedArticle.title,
selectedArticle.videoSourceUrl,
)
2026-06-27 14:07:10 +03:00
const editor = new EditorJS({
holder: editorHolderRef.current,
data: editorData,
2026-06-27 14:07:10 +03:00
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", "imageGeneration"],
2026-06-27 14:07:10 +03:00
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(),
}
},
2026-06-27 14:07:10 +03:00
},
},
},
vkVideo: {
class: VkVideoTool as unknown as ToolConstructable,
},
2026-06-27 14:07:10 +03:00
randomFrame: {
class: RandomFrameTune as unknown as ToolConstructable,
config: {
onReplace: replaceWithRandomFrame,
},
},
imageGeneration: {
class: ImageGenerationTune as unknown as ToolConstructable,
config: {
onRegenerate: (block: BlockAPI) => startImageGeneration(inlineImageGenerationTarget(block), block),
},
},
2026-06-27 14:07:10 +03:00
},
onChange: () => {
setEditorDirty(true)
scheduleEmptyImageCaptionNormalization()
},
2026-06-27 14:07:10 +03:00
})
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)
2026-06-27 14:07:10 +03:00
return () => {
holder?.removeEventListener("mousemove", handleEditorMouseMove)
holder?.removeEventListener("mouseleave", handleEditorMouseLeave)
holder?.removeEventListener("dragover", handleEditorDragOver)
holder?.removeEventListener("drop", handleEditorDrop, true)
clearEditorImageHover()
clearImageCaptionNormalizationTimers()
2026-06-27 14:07:10 +03:00
if (editorInstanceRef.current === editor) {
editorInstanceRef.current = null
}
editor.destroy()
}
}, [selectedArticle?.id, selectedArticle?.videoSourceUrl])
2026-06-27 14:07:10 +03:00
2026-08-15 13:25:21 +03:00
useEffect(() => {
if (!selectedArticle) return
function handleArticleKeyDown(event: KeyboardEvent) {
if (event.key !== "Escape") return
if (articleMoreOpen) {
event.preventDefault()
articleMoreRef.current?.removeAttribute("open")
setArticleMoreOpen(false)
return
}
if (articleCloseConfirmOpen) {
event.preventDefault()
stayInArticle()
return
}
event.preventDefault()
requestArticleClose()
}
window.addEventListener("keydown", handleArticleKeyDown)
return () => window.removeEventListener("keydown", handleArticleKeyDown)
}, [selectedArticle, articleCloseConfirmOpen, articleMoreOpen, editorDirty])
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,
})
2026-06-27 14:07:10 +03:00
setEditorDirty(true)
} finally {
block.holder.classList.remove("is-random-frame-loading")
2026-06-27 14:07:10 +03:00
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 applyGeneratedImage(job: ImageGenerationJob) {
const article = selectedArticleRef.current
const editor = editorInstanceRef.current
if (!article || !job.localUrl || appliedImageGenerationJobsRef.current.has(job.id)) return false
if (job.target === "cover") {
setSelectedArticle((current) => current ? { ...current, featureImageUrl: job.localUrl } : current)
setEditorDirty(true)
appliedImageGenerationJobsRef.current.add(job.id)
return true
}
if (!editor) return false
await editor.isReady
const count = editor.blocks.getBlocksCount()
let targetBlock: BlockAPI | null = null
if (job.targetBlockId) {
for (let index = 0; index < count; index += 1) {
const candidate = editor.blocks.getBlockByIndex(index)
if (candidate?.id === job.targetBlockId && candidate.name === "image") {
targetBlock = candidate
break
}
}
if (!targetBlock) return false
} else {
const data = await editor.save()
const placement = generatedImagePlacementIndex(data, job.target)
const candidate = editor.blocks.getBlockByIndex(placement)
if (candidate?.name === "image") targetBlock = candidate
else {
editor.blocks.insert("image", imageBlockData(job.localUrl, imageCaptionFromPostTitle()), undefined, Math.min(placement, count), true)
setEditorDirty(true)
appliedImageGenerationJobsRef.current.add(job.id)
return true
}
}
const previousData = await (targetBlock as unknown as { save: () => Promise<Record<string, any>> }).save()
await editor.blocks.update(targetBlock.id, {
...previousData,
file: { ...(previousData.file || {}), url: job.localUrl },
caption: previousData.caption || imageCaptionFromPostTitle(),
})
setEditorDirty(true)
appliedImageGenerationJobsRef.current.add(job.id)
return true
}
async function applyReadyImageGenerationJobs(batch: ImageGenerationBatch) {
for (const job of batch.jobs) {
if (job.status !== "ready" || !job.localUrl || appliedImageGenerationJobsRef.current.has(job.id)) continue
const applied = await applyGeneratedImage(job)
if (!applied && job.targetBlockId) {
setStatusMessage("Исходное изображение было изменено. Готовый результат сохранён — выберите «Применить» в списке генерации.")
}
}
}
async function pollImageGeneration(batchId: string, articleId: number) {
const batch = await api<ImageGenerationBatch>(`/api/articles/${articleId}/image-generations/${batchId}`)
setImageGenerationBatch(batch)
await applyReadyImageGenerationJobs(batch)
}
function inlineImageGenerationTarget(block: BlockAPI): Exclude<ImageGenerationTarget, "cover"> {
const editor = editorInstanceRef.current
if (!editor) return "middle"
const imageBlocks: BlockAPI[] = []
for (let index = 0; index < editor.blocks.getBlocksCount(); index += 1) {
const candidate = editor.blocks.getBlockByIndex(index)
if (candidate?.name === "image") imageBlocks.push(candidate)
}
return imageBlocks.length > 1 && imageBlocks[imageBlocks.length - 1]?.id === block.id ? "final" : "middle"
}
async function startImageGeneration(mode: "all" | ImageGenerationTarget, block?: BlockAPI) {
const article = selectedArticleRef.current
const editor = editorInstanceRef.current
if (!article || !editor || imageGenerationStarting) return
if (!appSettings.imageApiTokenConfigured) {
setStatusMessage("Для генерации изображений сначала укажите токен Polza в настройках.")
return
}
setImageGenerationStarting(true)
try {
const editorData = await editor.save()
const snapshotId = crypto.randomUUID()
const payload: Record<string, unknown> = {
mode,
title: editorTitleRef.current.trim() || article.title,
featureImageUrl: article.featureImageUrl || "",
editorData,
snapshotId,
}
if (block?.name === "image") payload.targetBlockId = block.id
const batch = await api<ImageGenerationBatch>(`/api/articles/${article.id}/image-generations`, {
method: "POST",
body: JSON.stringify(payload),
})
setImageGenerationBatch(batch)
await applyReadyImageGenerationJobs(batch)
} catch (error) {
setStatusMessage(`Не удалось запустить генерацию: ${error instanceof Error ? error.message : String(error)}`)
} finally {
setImageGenerationStarting(false)
}
}
useEffect(() => {
if (!selectedArticle || !imageGenerationBatch || ["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status)) return
const poll = () => {
void pollImageGeneration(imageGenerationBatch.batchId, selectedArticle.id).catch((error) => {
setStatusMessage(`Не удалось обновить генерацию: ${error instanceof Error ? error.message : String(error)}`)
})
}
poll()
imageGenerationPollRef.current = window.setInterval(poll, 2200)
return () => {
if (imageGenerationPollRef.current !== null) window.clearInterval(imageGenerationPollRef.current)
imageGenerationPollRef.current = null
}
}, [selectedArticle?.id, imageGenerationBatch?.batchId, imageGenerationBatch?.status])
2026-06-27 14:07:10 +03:00
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,
2026-08-24 11:59:38 +03:00
slug: editorSlug,
featureImageUrl: selectedArticle.featureImageUrl || "",
2026-06-27 14:07:10 +03:00
editableHtml: editorDataToHtml(editorData ?? htmlToEditorData("", editorTitle), editorTitle),
}),
})
setSelectedArticle(result)
setEditorTitle(result.title)
2026-08-24 11:59:38 +03:00
setEditorSlug(result.slug)
2026-06-27 14:07:10 +03:00
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)
}
2026-08-15 13:25:21 +03:00
function requestArticleClose() {
if (!editorDirty) {
setSelectedArticle(null)
return
}
setArticleCloseConfirmOpen(true)
}
function stayInArticle() {
setArticleCloseConfirmOpen(false)
window.requestAnimationFrame(() => articleBackButtonRef.current?.focus())
}
function discardArticleChanges() {
setArticleCloseConfirmOpen(false)
setSelectedArticle(null)
}
async function saveAndCloseArticle() {
const saved = await saveArticle(false)
if (!saved) return
setArticleCloseConfirmOpen(false)
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)
}
2026-06-27 14:07:10 +03:00
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)
2026-06-27 14:07:10 +03:00
setStatusMessage(`Удалил ролик${title ? `: ${title}` : ""}. Он исключен из повторного импорта.`)
await refresh()
2026-08-15 11:23:51 +03:00
await loadVideoStorage()
2026-06-27 14:07:10 +03:00
} 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} />
}
2026-06-27 14:07:10 +03:00
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">
2026-08-11 19:55:12 +03:00
<a
aria-label="Дзен-ассистент — главная страница"
className="flex items-center gap-3 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
href="/admin"
>
<img
alt="Логотип Дзен-ассистента"
className="size-10 rounded-md object-cover"
src="/favicon.png"
/>
2026-06-27 14:07:10 +03:00
<div>
<h1 className="text-2xl font-semibold tracking-normal">Дзен-ассистент</h1>
<p className="text-sm text-muted-foreground">RSS-конвейер для статей из видео Николая Старикова</p>
</div>
2026-08-11 19:55:12 +03:00
</a>
2026-06-27 14:07:10 +03:00
<div className="flex flex-wrap items-center gap-2">
<Button variant={activeView === "settings" ? "secondary" : "outline"} onClick={() => setActiveView("settings")}>
<Settings2 data-icon="inline-start" />
Настройки
</Button>
2026-06-27 14:07:10 +03:00
<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}>
2026-06-27 14:07:10 +03:00
<RefreshCw data-icon="inline-start" />
VK
2026-06-27 14:07:10 +03:00
</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>
2026-08-15 14:08:35 +03:00
<section
className={`local-video-upload rounded-md border border-dashed p-3 transition-colors ${
localVideoDragActive ? "border-primary bg-primary/5" : "border-border bg-background"
}`}
onDragEnter={(event) => {
event.preventDefault()
if (localVideoUpload?.status !== "uploading") setLocalVideoDragActive(true)
}}
onDragOver={(event) => {
event.preventDefault()
event.dataTransfer.dropEffect = "copy"
if (localVideoUpload?.status !== "uploading") setLocalVideoDragActive(true)
}}
onDragLeave={(event) => {
if (event.currentTarget.contains(event.relatedTarget as Node)) return
setLocalVideoDragActive(false)
}}
onDrop={(event) => {
event.preventDefault()
setLocalVideoDragActive(false)
if (localVideoUpload?.status === "uploading") return
selectLocalVideo(event.dataTransfer.files?.[0])
}}
>
<input
ref={localVideoInputRef}
className="hidden"
type="file"
accept="video/mp4,video/webm,video/quicktime,video/x-matroska,.mp4,.webm,.mov,.mkv"
onChange={(event) => {
const file = event.currentTarget.files?.[0]
event.currentTarget.value = ""
selectLocalVideo(file)
}}
/>
<div className="flex flex-wrap items-center gap-3">
<span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
<Upload className="size-4" />
</span>
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold">Загрузить видео с компьютера</p>
<p className="mt-0.5 text-xs text-muted-foreground">MP4, WebM, MOV или MKV. Перетащите файл сюда или выберите его.</p>
</div>
<Button size="sm" variant="outline" disabled={localVideoUpload?.status === "uploading"} onClick={() => localVideoInputRef.current?.click()}>
<Upload data-icon="inline-start" />
Выбрать файл
</Button>
</div>
{localVideoUpload ? (
<div className="mt-3 border-t pt-3" aria-live="polite">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="truncate text-sm font-medium" title={localVideoUpload.name}>{localVideoUpload.name}</p>
<p className={`mt-0.5 text-xs ${localVideoUpload.status === "error" ? "text-destructive" : "text-muted-foreground"}`}>
{localVideoUpload.status === "uploading"
? `Загружено ${formatFileSize(localVideoUpload.loaded)} из ${formatFileSize(localVideoUpload.total)}`
: localVideoUpload.status === "complete"
? `Загружено ${formatFileSize(localVideoUpload.total)}. Файл готов к обработке.`
: localVideoUpload.status === "cancelled"
? "Загрузка отменена."
: localVideoUpload.errorMessage || "Не удалось загрузить файл."}
</p>
</div>
{localVideoUpload.status === "uploading" ? (
<Button size="icon" variant="outline" title="Отменить загрузку" aria-label="Отменить загрузку" onClick={cancelLocalVideoUpload}>
<X className="size-4" />
</Button>
) : (
<Button size="icon" variant="ghost" title="Скрыть статус" aria-label="Скрыть статус" onClick={() => setLocalVideoUpload(null)}>
<X className="size-4" />
</Button>
)}
</div>
<div className="mt-2 flex items-center gap-3">
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
<div
className={localVideoUpload.status === "error" ? "h-full rounded-full bg-destructive transition-all" : "h-full rounded-full bg-primary transition-all"}
style={{ width: `${localVideoUpload.status === "complete" ? 100 : localUploadPercent}%` }}
/>
</div>
<span className="w-10 text-right text-xs tabular-nums text-muted-foreground">
{localVideoUpload.status === "uploading" ? `${localUploadPercent}%` : localVideoUpload.status === "complete" ? "100%" : ""}
</span>
</div>
</div>
) : null}
</section>
</div>
) : null}
2026-06-27 14:07:10 +03:00
{activeView === "settings" ? (
<SettingsPanel onBack={() => setActiveView("dashboard")} onSaved={handleSettingsSaved} />
) : <>
2026-08-15 14:08:35 +03:00
<section className={`video-storage-strip rounded-md border bg-background p-3 ${videoStorageLow ? "border-amber-300 bg-amber-50/60" : "border-border"}`} aria-live="polite">
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Видео на диске</p>
{videoStorage ? <span className="text-xs tabular-nums text-muted-foreground">{videoStoragePercent}%</span> : null}
</div>
{videoStorage ? (
<>
<div className="mt-3 h-1.5 overflow-hidden rounded-full bg-muted">
<div className={`h-full rounded-full transition-all ${videoStorageLow ? "bg-amber-500" : "bg-primary"}`} style={{ width: `${videoStoragePercent}%` }} />
</div>
<p className={`mt-2 text-xs leading-5 ${videoStorageLow ? "text-amber-800" : "text-muted-foreground"}`}>
Свободно {formatFileSize(videoStorage.freeBytes)} из {formatFileSize(videoStorage.totalBytes)}
</p>
</>
) : (
<p className="mt-3 text-xs leading-5 text-muted-foreground">Данные о диске недоступны.</p>
)}
</section>
<section className="workspace-grid grid gap-5 xl:grid-cols-2">
<Card className="work-column min-w-0">
2026-06-27 14:07:10 +03:00
<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">
2026-06-27 14:07:10 +03:00
{productionVideos.length > 0 ? (
productionVideos.map((video) => {
const draftArticles = video.articles?.filter((article) => article.status !== "published") ?? []
2026-06-27 14:07:10 +03:00
const publishedArticle = video.articles?.find((article) => article.status === "published")
const fallbackArticleId = video.articleIds?.[0]
const draftArticleId = draftArticles[0]?.id ?? (publishedArticle ? undefined : fallbackArticleId)
2026-06-27 14:07:10 +03:00
const progress = Math.max(0, Math.min(100, video.progressPercent || 0))
const hasStarted = video.status !== "new" || progress > 0
2026-08-15 11:35:21 +03:00
const isActive = ["queued", "processing", "planning"].includes(video.status)
2026-06-27 14:07:10 +03:00
const isSubmitting = videoActionId === video.id
const hasDraftAction = draftArticles.length > 0 || Boolean(draftArticleId)
2026-06-27 14:07:10 +03:00
return (
<div key={video.id} className="production-item rounded-md border bg-background p-3">
2026-06-27 14:07:10 +03:00
<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}
2026-06-27 14:07:10 +03:00
{!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>
2026-06-27 14:07:10 +03:00
<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}
2026-06-27 14:07:10 +03:00
</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>
</>
2026-06-27 14:07:10 +03:00
) : 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>
</>
2026-06-27 14:07:10 +03:00
) : isActive ? (
<Button
size="sm"
variant="outline"
2026-08-15 11:35:21 +03:00
disabled={isSubmitting || video.status === "planning"}
2026-06-27 14:07:10 +03:00
className="border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100 hover:text-amber-900"
onClick={() => processVideo(video.id, true)}
>
2026-08-15 11:35:21 +03:00
<RefreshCw data-icon="inline-start" className={isSubmitting || video.status === "planning" ? "animate-spin" : ""} />
{video.status === "planning" ? "Хронометраж" : "Перезапустить"}
2026-06-27 14:07:10 +03:00
</Button>
) : (
<Button
size="icon"
variant="outline"
disabled={isSubmitting}
title="Обработать"
aria-label="Обработать"
onClick={() => prepareVideoProcessing(video)}
2026-06-27 14:07:10 +03:00
>
<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">
2026-06-27 14:07:10 +03:00
<CardHeader>
2026-08-15 15:00:57 +03:00
<div className="flex items-start justify-between gap-4">
<div>
<CardTitle>Статьи</CardTitle>
<CardDescription>Черновики, принятые материалы и отложенные публикации.</CardDescription>
</div>
<Button size="sm" disabled={manualArticleCreating} onClick={() => void createManualArticle()}>
{manualArticleCreating ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <FilePenLine data-icon="inline-start" />}
Создать материал
</Button>
</div>
2026-06-27 14:07:10 +03:00
</CardHeader>
<CardContent
className="work-list flex max-h-[72vh] flex-col gap-2 overflow-y-auto"
2026-06-27 14:07:10 +03:00
onScroll={(event) => {
const element = event.currentTarget
const distanceToBottom = element.scrollHeight - element.scrollTop - element.clientHeight
if (distanceToBottom < 180 && articlesHasMoreRef.current) {
void loadArticlesPage()
}
}}
>
2026-08-15 15:00:57 +03:00
{manualDrafts.length > 0 ? (
<section className="space-y-2 border-b pb-4">
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Ручные черновики</p>
{manualDrafts.map((article) => (
<div key={article.id} className="article-item rounded-md border bg-background p-3">
<div className="flex items-start justify-between gap-3">
<button className="min-w-0 flex-1 text-left" onClick={() => void openArticlePreview(article.id)}>
<div className="flex items-center gap-2">
<StatusBadge status="draft" />
<h3 className="min-w-0 flex-1 truncate text-sm font-semibold">{article.title}</h3>
</div>
<p className="mt-2 text-xs text-muted-foreground">Создано: {formatDateTime(article.createdAt)}</p>
</button>
<div className="flex shrink-0 gap-2">
<Button size="icon" variant="outline" title="Открыть редактор" aria-label="Открыть редактор" onClick={() => void 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>
</div>
</div>
</div>
))}
</section>
) : null}
2026-06-27 14:07:10 +03:00
{publishedArticles.length > 0 ? (
publishedArticles.map((article) => (
<div key={article.id} className="article-item rounded-md border bg-background p-3">
2026-06-27 14:07:10 +03:00
<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>
</>}
2026-06-27 14:07:10 +03:00
</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}
2026-06-27 14:07:10 +03:00
{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">
2026-06-27 14:07:10 +03:00
<div className="flex flex-wrap items-center gap-2">
2026-08-15 13:25:21 +03:00
<Button ref={articleBackButtonRef} variant="ghost" size="default" className="article-back-button h-11 shrink-0 px-2" onClick={requestArticleClose}>
<ChevronLeft className="size-5" />
К черновикам
</Button>
2026-06-27 14:07:10 +03:00
{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>
2026-08-15 13:25:21 +03:00
<Badge variant="secondary" className="article-save-state">{editorDirty ? "Есть правки" : "Сохранено"}</Badge>
2026-06-27 14:07:10 +03:00
</div>
<p className="mt-1 text-sm text-muted-foreground">Редактируйте блоки как в Medium. У изображения доступны случайный кадр и перегенерация по смыслу текста.</p>
2026-06-27 14:07:10 +03:00
</div>
2026-08-15 13:25:21 +03:00
<div className="article-modal-actions hidden shrink-0 flex-wrap justify-end gap-2 sm:flex">
2026-06-27 14:07:10 +03:00
<input
ref={featureImageInputRef}
2026-08-15 13:25:21 +03:00
id="article-feature-image-upload"
2026-06-27 14:07:10 +03:00
className="hidden"
type="file"
accept="image/*"
onChange={async (event) => {
const file = event.currentTarget.files?.[0]
event.currentTarget.value = ""
if (file) await setFeatureImageFile(file)
2026-06-27 14:07:10 +03:00
}}
/>
<Button
size="icon"
variant="outline"
disabled={editorBusy}
title="Скопировать заголовок и текст без картинок"
aria-label="Скопировать заголовок и текст без картинок"
onClick={copyArticleText}
2026-06-27 14:07:10 +03:00
>
<Copy className="size-4" />
2026-06-27 14:07:10 +03:00
</Button>
<Button
variant="outline"
disabled={editorBusy || imageGenerationStarting || Boolean(imageGenerationBatch && !["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status))}
onClick={() => startImageGeneration("all")}
>
{imageGenerationStarting ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <ImagePlus data-icon="inline-start" />}
Сгенерировать изображения
</Button>
2026-06-27 14:07:10 +03:00
<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">
2026-06-27 14:07:10 +03:00
<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>
</div>
2026-08-15 13:25:21 +03:00
<details
ref={articleMoreRef}
className="article-more-actions w-full sm:hidden"
onToggle={(event) => setArticleMoreOpen(event.currentTarget.open)}
>
<summary aria-expanded={articleMoreOpen} className="flex h-11 cursor-pointer list-none items-center justify-between rounded-md border bg-background px-3 text-sm font-medium shadow-sm">
Ещё
<ChevronDown className="size-4" aria-hidden="true" />
</summary>
<div className="mt-2 grid gap-2 rounded-md border bg-muted/30 p-2">
<Button variant="outline" className="h-11 justify-start" disabled={editorBusy} onClick={copyArticleText}>
<Copy data-icon="inline-start" />
Скопировать текст
</Button>
<Button
variant="outline"
className="h-11 justify-start whitespace-normal text-left"
disabled={editorBusy || imageGenerationStarting || Boolean(imageGenerationBatch && !["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status))}
onClick={() => startImageGeneration("all")}
>
{imageGenerationStarting ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <ImagePlus data-icon="inline-start" />}
Сгенерировать изображения
</Button>
{selectedArticle.status !== "published" || isScheduledForFuture(selectedArticle.publishedAt) ? (
<label className="article-publish-time flex h-11 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="min-w-0 flex-1 bg-transparent text-sm text-foreground outline-none"
value={publishAt}
onChange={(event) => setPublishAt(event.target.value)}
/>
</label>
) : (
<Button variant="outline" className="h-11 justify-start" onClick={() => window.open(selectedArticle.url, "_blank")}>
<ExternalLink data-icon="inline-start" />
Открыть на сайте
</Button>
)}
<Button variant="outline" className="h-11 justify-start text-destructive hover:text-destructive" disabled={editorBusy} onClick={() => deleteArticle(selectedArticle.id)}>
<Trash2 data-icon="inline-start" />
Удалить
</Button>
</div>
</details>
2026-06-27 14:07:10 +03:00
</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">
2026-08-15 13:25:21 +03:00
<div className="article-feature-image-heading mb-2 flex items-center justify-between gap-3">
<div className="min-w-0">
<p className="text-sm font-semibold text-zinc-950">Feature Image</p>
<p className="text-xs text-muted-foreground">Главная обложка публикации для RSS и Дзена.</p>
</div>
2026-08-15 13:25:21 +03:00
<div className="article-feature-image-controls flex flex-wrap gap-2">
<Button size="sm" variant="outline" disabled={featureImageBusy} onClick={() => featureImageInputRef.current?.click()}>
<ImagePlus data-icon="inline-start" className={featureImageBusy ? "animate-pulse" : ""} />
Выбрать
</Button>
<Button
size="sm"
variant="outline"
disabled={imageGenerationStarting || Boolean(imageGenerationBatch && !["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status))}
onClick={() => startImageGeneration("cover")}
>
<RefreshCw data-icon="inline-start" className={imageGenerationStarting ? "animate-spin" : ""} />
Перегенерировать обложку
</Button>
</div>
</div>
2026-08-15 13:25:21 +03:00
<button
type="button"
className={`relative flex aspect-video w-full cursor-pointer items-center justify-center overflow-hidden rounded-md border border-dashed text-left transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${
featureImageDragActive ? "border-primary bg-primary/5" : "border-zinc-300 bg-zinc-50 hover:bg-zinc-100"
}`}
2026-08-15 13:25:21 +03:00
aria-label="Выбрать обложку статьи"
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}
2026-08-15 13:25:21 +03:00
</button>
</div>
{imageGenerationBatch ? (
<section className="image-generation-status mb-6 rounded-md border bg-zinc-50 p-3" aria-live="polite">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<p className="text-sm font-semibold text-zinc-950">Генерация изображений</p>
<p className="text-xs text-muted-foreground">Статус: {imageGenerationBatch.status}</p>
</div>
{["completed", "completed_with_errors", "failed"].includes(imageGenerationBatch.status) ? <Badge variant="outline">Завершено</Badge> : <Badge variant="secondary"><Loader2 className="mr-1 size-3 animate-spin" />Выполняется</Badge>}
</div>
<div className="mt-3 grid gap-2 sm:grid-cols-3">
{imageGenerationBatch.jobs.map((job) => {
const label = job.target === "cover" ? "Обложка" : job.target === "middle" ? "Вторая часть" : "Финальная часть"
const canApply = job.status === "ready" && Boolean(job.localUrl) && !appliedImageGenerationJobsRef.current.has(job.id)
return (
<div key={job.id} className="rounded border bg-background p-2.5">
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-medium">{label}</span>
<span className="text-xs text-muted-foreground">{job.progress || 0}%</span>
</div>
<div className="mt-2 h-1.5 overflow-hidden rounded bg-muted"><div className="h-full rounded bg-primary transition-all" style={{ width: `${Math.max(0, Math.min(100, job.progress || 0))}%` }} /></div>
<p className={`mt-2 min-h-5 text-xs ${job.status === "failed" ? "text-destructive" : "text-muted-foreground"}`}>{job.errorMessage || job.stage || job.status}</p>
{canApply ? <Button className="mt-2 w-full" size="sm" variant="outline" onClick={() => void applyGeneratedImage(job)}>Применить</Button> : null}
</div>
)
})}
</div>
</section>
) : null}
2026-06-27 14:07:10 +03:00
<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) => {
const title = event.target.value
setEditorTitle(title)
setEditorSlug(slugFromTitle(title))
2026-06-27 14:07:10 +03:00
setEditorDirty(true)
}}
/>
<div
key={selectedArticle.id}
ref={editorHolderRef}
className="article-editor article-editorjs mt-6"
/>
</article>
</div>
2026-08-15 13:25:21 +03:00
<div className="article-mobile-actions grid gap-2 border-t bg-background p-3 sm:hidden">
<Button className="h-11 w-full" variant="outline" disabled={editorBusy || !editorDirty} onClick={() => saveArticle()}>
{editorBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Save data-icon="inline-start" />}
Сохранить
</Button>
{selectedArticle.status !== "published" || isScheduledForFuture(selectedArticle.publishedAt) ? (
<Button className="h-11 w-full" disabled={editorBusy} onClick={saveAndPublishArticle}>
{editorBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : <Radio data-icon="inline-start" />}
{isScheduledForFuture(publishAt) ? "Запланировать" : "Опубликовать"}
</Button>
) : null}
</div>
2026-06-27 14:07:10 +03:00
</div>
2026-08-15 13:25:21 +03:00
{articleCloseConfirmOpen ? (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm" role="presentation">
<section className="w-full max-w-md rounded-lg border bg-background p-5 shadow-lg" role="dialog" aria-modal="true" aria-labelledby="article-close-confirm-title" aria-describedby="article-close-confirm-description">
2026-08-15 13:25:21 +03:00
<h3 id="article-close-confirm-title" className="text-lg font-semibold">Сохранить изменения?</h3>
<p id="article-close-confirm-description" className="mt-2 text-sm text-muted-foreground">Несохранённые правки останутся только в этом браузере и будут потеряны при выходе.</p>
<div className="mt-5 grid gap-2 sm:flex sm:flex-wrap sm:justify-start">
<Button variant="outline" className="h-11 shrink-0" onClick={stayInArticle}>Остаться</Button>
<Button variant="outline" className="h-11 shrink-0" disabled={editorBusy} onClick={discardArticleChanges}>Не сохранять</Button>
<Button className="h-11 shrink-0" disabled={editorBusy} onClick={() => void saveAndCloseArticle()}>
2026-08-15 13:25:21 +03:00
{editorBusy ? <Loader2 className="animate-spin" data-icon="inline-start" /> : null}
Сохранить и выйти
</Button>
</div>
</section>
</div>
) : null}
2026-06-27 14:07:10 +03:00
</div>
) : null}
</main>
)
}