2026-08-08 14:02:14 +03:00
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 ,
2026-08-08 14:02:14 +03:00
ArrowLeft ,
2026-06-27 14:07:10 +03:00
CheckCircle2 ,
Clock3 ,
2026-08-08 14:02:14 +03:00
Copy ,
2026-06-27 14:07:10 +03:00
ExternalLink ,
FilePenLine ,
FileText ,
ImagePlus ,
2026-08-08 14:02:14 +03:00
Link2 ,
2026-06-27 14:07:10 +03:00
Loader2 ,
Radio ,
RefreshCw ,
Save ,
2026-08-08 14:02:14 +03:00
Settings2 ,
2026-06-27 14:07:10 +03:00
Trash2 ,
X ,
} from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card , CardContent , CardDescription , CardHeader , CardTitle } from "@/components/ui/card"
import { Textarea } from "@/components/ui/textarea"
2026-08-08 14:02:14 +03:00
import { Input } from "@/components/ui/input"
2026-06-27 14:07:10 +03:00
2026-08-08 14:02:14 +03:00
type AppSettings = {
signatureHtml : string
llmInstructions : string
2026-06-27 14:07:10 +03:00
}
type VideoArticle = {
id : number
title : string
status : string
}
type Video = {
id : number
title : string
sourceUrl : string
2026-08-11 11:56:47 +03:00
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
2026-08-08 14:02:14 +03:00
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
}
type VideoLog = {
id : number
title : string
status : string
progressPercent : number
progressStage : string
progressLog : string
errorMessage? : string
}
2026-08-08 14:02:14 +03:00
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-06-27 14:07:10 +03:00
type EditorBlock = OutputData [ "blocks" ] [ number ]
type RandomFrameTuneConfig = {
onReplace ? : ( block : BlockAPI ) = > void | Promise < void >
}
const ARTICLES_PAGE_SIZE = 10
2026-08-08 14:02:14 +03:00
const CHAPTER_SELECTION_STORAGE_PREFIX = "dzen:selected-chapters:"
function chapterSelectionStorageKey ( videoId : number ) {
return ` ${ CHAPTER_SELECTION_STORAGE_PREFIX } ${ videoId } `
}
function loadStoredChapterSelection ( videoId : number ) : string [ ] | null {
try {
const value = window . localStorage . getItem ( chapterSelectionStorageKey ( videoId ) )
if ( value === null ) return null
const parsed = JSON . parse ( value )
return Array . isArray ( parsed ) ? parsed . filter ( ( item ) : item is string = > typeof item === "string" ) : null
} catch {
return null
}
}
function storeChapterSelection ( videoId : number , ids : Iterable < string > ) {
try {
window . localStorage . setItem ( chapterSelectionStorageKey ( videoId ) , JSON . stringify ( Array . from ( ids ) ) )
} catch {
// Local Storage can be unavailable in restricted browser modes.
}
}
function clearStoredChapterSelection ( videoId : number ) {
try {
window . localStorage . removeItem ( chapterSelectionStorageKey ( videoId ) )
} catch {
// Nothing to clean up if Local Storage is unavailable.
}
}
function imageFileFromClipboard ( event : ClipboardEvent ) {
return (
Array . from ( event . clipboardData ? . files || [ ] ) . find ( ( item ) = > item . type . startsWith ( "image/" ) ) ||
Array . from ( event . clipboardData ? . items || [ ] )
. find ( ( item ) = > item . kind === "file" && item . type . startsWith ( "image/" ) )
? . getAsFile ( ) ||
null
)
}
function imageFileFromDataTransfer ( dataTransfer : DataTransfer | null ) {
return Array . from ( dataTransfer ? . files || [ ] ) . find ( ( item ) = > item . type . startsWith ( "image/" ) ) || null
}
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 )
} ,
}
}
}
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 >
}
function escapeHtml ( value : string ) {
return value
. replace ( /&/g , "&" )
. replace ( /</g , "<" )
. replace ( />/g , ">" )
. replace ( /"/g , """ )
}
function normalizeEditorText ( value : string ) {
const parser = new DOMParser ( )
const document = parser . parseFromString ( ` <main> ${ value || "" } </main> ` , "text/html" )
return ( document . body . textContent || "" )
. replace ( /^#{1,6}\s*/ , "" )
. replace ( /\s+/g , " " )
. trim ( )
. toLowerCase ( )
. replace ( /ё/g , "е " )
}
function stripLeadingDuplicateTitleBlock ( blocks : EditorBlock [ ] , title? : string ) {
const normalizedTitle = normalizeEditorText ( title || "" )
if ( ! normalizedTitle || blocks . length === 0 ) return blocks
const first = blocks [ 0 ]
if ( ! [ "paragraph" , "header" ] . includes ( first . type ) ) return blocks
const text = normalizeEditorText ( String ( ( first . data as Record < string , unknown > ) . text || "" ) )
return text === normalizedTitle ? blocks . slice ( 1 ) : blocks
}
function htmlToEditorData ( html : string , title? : string ) : OutputData {
const parser = new DOMParser ( )
const document = parser . parseFromString ( ` <main> ${ html || "" } </main> ` , "text/html" )
const root = document . querySelector ( "main" )
const blocks : EditorBlock [ ] = [ ]
function pushParagraph ( element : Element ) {
const text = element . innerHTML . trim ( )
if ( text ) {
blocks . push ( { type : "paragraph" , data : { text } } )
}
}
root ? . childNodes . forEach ( ( node ) = > {
if ( node . nodeType === Node . TEXT_NODE ) {
const text = node . textContent ? . trim ( )
if ( text ) {
blocks . push ( { type : "paragraph" , data : { text : escapeHtml ( text ) } } )
}
return
}
if ( ! ( node instanceof Element ) ) return
const tag = node . tagName . toLowerCase ( )
if ( tag === "p" ) {
pushParagraph ( node )
return
}
if ( tag === "h2" || tag === "h3" ) {
blocks . push ( { type : "header" , data : { text : node.innerHTML.trim ( ) , level : tag === "h2" ? 2 : 3 } } )
return
}
if ( tag === "blockquote" ) {
blocks . push ( { type : "quote" , data : { text : node.innerHTML.trim ( ) , caption : "" , alignment : "left" } } )
return
}
if ( tag === "ul" || tag === "ol" ) {
const items = Array . from ( node . querySelectorAll ( ":scope > li" ) ) . map ( ( item ) = > item . innerHTML . trim ( ) ) . filter ( Boolean )
blocks . push ( { type : "list" , data : { style : tag === "ol" ? "ordered" : "unordered" , items } } )
return
}
if ( tag === "figure" ) {
const image = node . querySelector ( "img" )
if ( ! image ) return
blocks . push ( {
type : "image" ,
data : {
file : { url : image.getAttribute ( "src" ) || "" } ,
caption : node.querySelector ( "figcaption" ) ? . innerHTML . trim ( ) || image . getAttribute ( "alt" ) || "" ,
withBorder : false ,
withBackground : false ,
stretched : false ,
} ,
} )
return
}
pushParagraph ( node )
} )
const cleanBlocks = stripLeadingDuplicateTitleBlock ( blocks , title )
return {
time : Date.now ( ) ,
blocks : cleanBlocks.length ? cleanBlocks : [ { type : "paragraph" , data : { text : "" } } ] ,
version : "2.30.8" ,
}
}
function editorDataToHtml ( data : OutputData , title? : string ) : string {
return stripLeadingDuplicateTitleBlock ( data . blocks || [ ] , title )
. map ( ( block ) = > {
const item = block . data as Record < string , any >
if ( block . type === "header" ) {
const level = item . level === 3 ? 3 : 2
return ` <h ${ level } > ${ item . text || "" } </h ${ level } > `
}
if ( block . type === "list" ) {
const tag = item . style === "ordered" ? "ol" : "ul"
const items = Array . isArray ( item . items ) ? item . items : [ ]
return ` < ${ tag } > ${ items . map ( ( value ) = > ` <li> ${ value } </li> ` ) . join ( "" ) } </ ${ tag } > `
}
if ( block . type === "quote" ) {
return ` <blockquote> ${ item . text || "" } </blockquote> `
}
if ( block . type === "image" ) {
const url = item . file ? . url || item . url || ""
if ( ! url ) return ""
2026-08-08 14:02:14 +03:00
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> `
}
return ` <p> ${ item . text || "" } </p> `
} )
. filter ( Boolean )
. join ( "\n" )
}
2026-08-08 14:02:14 +03:00
function appendSignatureToEditorData ( data : OutputData , signatureHtml : string ) : OutputData {
if ( ! signatureHtml . trim ( ) ) return data
const signatureBlocks = htmlToEditorData ( signatureHtml ) . blocks
if ( ! signatureBlocks . length || signatureBlocks . every ( ( block ) = > block . type === "paragraph" && ! String ( ( block . data as Record < string , unknown > ) . text || "" ) . trim ( ) ) ) {
return data
}
const blocks = data . blocks || [ ]
const tail = blocks . slice ( - signatureBlocks . length )
const sameBlock = ( left : EditorBlock , right : EditorBlock ) = >
left . type === right . type && JSON . stringify ( left . data ) === JSON . stringify ( right . data )
if ( tail . length === signatureBlocks . length && tail . every ( ( block , index ) = > sameBlock ( block , signatureBlocks [ index ] ) ) ) {
return data
}
return { . . . data , blocks : [ . . . blocks , . . . signatureBlocks ] }
}
function htmlToPlainText ( html : string ) {
const parser = new DOMParser ( )
const document = parser . parseFromString ( ` <main> ${ html || "" } </main> ` , "text/html" )
return ( document . querySelector ( "main" ) ? . textContent || "" ) . replace ( /\s+\n/g , "\n" ) . replace ( /[ \t]{2,}/g , " " ) . trim ( )
}
function editorDataToPlainText ( data : OutputData , title? : string ) : string {
const parts : string [ ] = [ ]
const normalizedTitle = normalizeEditorText ( title || "" )
const blocks = stripLeadingDuplicateTitleBlock ( data . blocks || [ ] , title )
if ( title ? . trim ( ) ) {
parts . push ( title . trim ( ) )
}
blocks . forEach ( ( block ) = > {
if ( block . type === "image" ) return
const item = block . data as Record < string , any >
let text = ""
if ( block . type === "header" || block . type === "paragraph" ) {
text = htmlToPlainText ( String ( item . text || "" ) )
} else if ( block . type === "quote" ) {
text = htmlToPlainText ( String ( item . text || "" ) )
} else if ( block . type === "list" && Array . isArray ( item . items ) ) {
text = item . items . map ( ( value : unknown ) = > ` - ${ htmlToPlainText ( String ( value || "" ) ) } ` ) . join ( "\n" )
} else {
text = htmlToPlainText ( String ( item . text || "" ) )
}
if ( ! text || normalizeEditorText ( text ) === normalizedTitle ) return
parts . push ( text )
} )
return parts . join ( "\n\n" ) . trim ( )
}
function SettingsPanel ( { onBack , onSaved } : { onBack : ( ) = > void ; onSaved : ( settings : AppSettings ) = > void } ) {
const [ settings , setSettings ] = useState < AppSettings > ( { signatureHtml : "" , llmInstructions : "" } )
const [ loading , setLoading ] = useState ( true )
const [ saving , setSaving ] = useState ( false )
const [ dirty , setDirty ] = useState ( false )
const [ message , setMessage ] = useState ( "" )
const signatureHolderRef = useRef < HTMLDivElement | null > ( null )
const signatureEditorRef = useRef < EditorJS | null > ( null )
useEffect ( ( ) = > {
api < AppSettings > ( "/api/settings" )
. then ( ( result ) = > {
setSettings ( result )
onSaved ( result )
setLoading ( false )
} )
. catch ( ( error ) = > {
setMessage ( ` Н е удалось загрузить настройки: ${ error instanceof Error ? error.message : String ( error ) } ` )
setLoading ( false )
} )
} , [ onSaved ] )
useEffect ( ( ) = > {
if ( loading || ! signatureHolderRef . current ) return
signatureEditorRef . current ? . destroy ( )
signatureHolderRef . current . innerHTML = ""
const editor = new EditorJS ( {
holder : signatureHolderRef.current ,
data : htmlToEditorData ( settings . signatureHtml ) ,
placeholder : "Введите подпись..." ,
inlineToolbar : [ "bold" , "italic" , "link" ] ,
i18n : editorI18n ,
tools : {
header : {
class : Header as unknown as ToolConstructable ,
inlineToolbar : [ "bold" , "italic" , "link" ] ,
config : { levels : [ 2 , 3 ] , defaultLevel : 2 , placeholder : "Введите заголовок" } ,
} ,
list : { class : List as unknown as ToolConstructable , inlineToolbar : true } ,
quote : {
class : Quote as unknown as ToolConstructable ,
inlineToolbar : true ,
config : { quotePlaceholder : "Цитата" , captionPlaceholder : "" } ,
} ,
} ,
onChange : ( ) = > setDirty ( true ) ,
} )
signatureEditorRef . current = editor
return ( ) = > {
if ( signatureEditorRef . current === editor ) signatureEditorRef . current = null
void editor . destroy ( )
}
} , [ loading ] )
async function saveSettings() {
setSaving ( true )
try {
const data = await signatureEditorRef . current ? . save ( )
const serializedSignature = data ? editorDataToHtml ( data ) : settings . signatureHtml
const next : AppSettings = {
signatureHtml : htmlToPlainText ( serializedSignature ) . trim ( ) ? serializedSignature : "" ,
llmInstructions : settings.llmInstructions.trim ( ) ,
}
const saved = await api < AppSettings > ( "/api/settings" , { method : "PUT" , body : JSON.stringify ( next ) } )
setSettings ( saved )
setDirty ( false )
setMessage ( "Настройки сохранены" )
onSaved ( saved )
} catch ( error ) {
setMessage ( ` Н е удалось сохранить настройки: ${ error instanceof Error ? error.message : String ( error ) } ` )
} finally {
setSaving ( false )
}
}
return (
< section className = "flex flex-col gap-6" >
< div className = "flex flex-wrap items-center justify-between gap-3" >
< div >
< h2 className = "text-xl font-semibold tracking-normal" > Н а с т р о й к и < / h2 >
< p className = "text-sm text-muted-foreground" > О б щ а я п о д п и с ь и д о п о л н и т е л ь н ы е п р а в и л а р е д а к т о р а . < / p >
< / div >
< Button variant = "outline" onClick = { onBack } >
< ArrowLeft data-icon = "inline-start" / >
К р о л и к а м
< / Button >
< / div >
{ message ? < div className = "rounded-md border bg-background px-4 py-3 text-sm text-muted-foreground" > { message } < / div > : null }
{ loading ? (
< Card > < CardContent className = "p-6 text-sm text-muted-foreground" > З а г р у з к а н а с т р о е к . . . < / CardContent > < / Card >
) : (
< div className = "grid gap-6 xl:grid-cols-[minmax(0,1.15fr)_minmax(360px,0.85fr)]" >
< Card >
< CardHeader >
< CardTitle > П о д п и с ь с т а т ь и < / CardTitle >
< CardDescription > П о я в и т с я п о с л е д н и м р е д а к т и р у е м ы м б л о к о м в н о в ы х ч е р н о в и к а х . < / CardDescription >
< / CardHeader >
< CardContent >
< div ref = { signatureHolderRef } className = "article-editor article-editorjs min-h-[180px] rounded-md border bg-background p-3" / >
< / CardContent >
< / Card >
< Card >
< CardHeader >
< CardTitle > И н с т р у к ц и и д л я И И < / CardTitle >
< CardDescription > Б у д у т д о б а в л е н ы к о с н о в н ы м р е д а к т о р с к и м п р а в и л а м . < / CardDescription >
< / CardHeader >
< CardContent >
< Textarea
className = "min-h-[280px] resize-y"
onChange = { ( event ) = > {
setSettings ( ( current ) = > ( { . . . current , llmInstructions : event.target.value } ) )
setDirty ( true )
} }
placeholder = "Дополнительные требования к статьям..."
value = { settings . llmInstructions }
/ >
< / CardContent >
< / Card >
< / div >
) }
< div className = "flex justify-end gap-2" >
< Button disabled = { saving || loading || ! dirty } onClick = { saveSettings } >
{ saving ? < Loader2 className = "animate-spin" data-icon = "inline-start" / > : < Save data-icon = "inline-start" / > }
С о х р а н и т ь
< / Button >
< / div >
< / section >
)
}
async function writeClipboardText ( text : string ) {
if ( navigator . clipboard ? . writeText ) {
await navigator . clipboard . writeText ( text )
return
}
const textarea = document . createElement ( "textarea" )
textarea . value = text
textarea . setAttribute ( "readonly" , "true" )
textarea . style . position = "fixed"
textarea . style . left = "-9999px"
document . body . appendChild ( textarea )
textarea . select ( )
document . execCommand ( "copy" )
document . body . removeChild ( textarea )
}
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" ) } `
}
function parseApiDate ( value? : string ) {
if ( ! value ) return null
const normalized = /(?:z|[+-]\d{2}:?\d{2})$/i . test ( value ) ? value : ` ${ value } Z `
const date = new Date ( normalized )
return Number . isNaN ( date . getTime ( ) ) ? null : date
}
function toDateTimeLocalValue ( value? : string ) {
const date = parseApiDate ( value )
if ( ! date ) return ""
const local = new Date ( date . getTime ( ) - date . getTimezoneOffset ( ) * 60000 )
return local . toISOString ( ) . slice ( 0 , 16 )
}
function currentDateTimeLocalValue() {
const date = new Date ( )
const local = new Date ( date . getTime ( ) - date . getTimezoneOffset ( ) * 60000 )
return local . toISOString ( ) . slice ( 0 , 16 )
}
function formatDateTime ( value? : string ) {
const date = parseApiDate ( value )
if ( ! date ) return ""
return new Intl . DateTimeFormat ( "ru-RU" , {
day : "2-digit" ,
month : "short" ,
hour : "2-digit" ,
minute : "2-digit" ,
} ) . format ( date )
}
function formatVideoDate ( value? : string ) {
const date = parseApiDate ( value )
if ( ! date ) return "дата неизвестна"
return new Intl . DateTimeFormat ( "ru-RU" , {
day : "2-digit" ,
month : "short" ,
year : "numeric" ,
hour : "2-digit" ,
minute : "2-digit" ,
} ) . format ( date )
}
function isScheduledForFuture ( value? : string ) {
const date = parseApiDate ( value )
return Boolean ( date && date . getTime ( ) > Date . now ( ) )
}
function dateSortValue ( value? : string ) {
return parseApiDate ( value ) ? . getTime ( ) ? ? 0
}
function statusVariant ( status : string ) {
if ( status === "published" || status === "drafted" ) return "default"
if ( status === "error" ) return "destructive"
if ( status === "processing" ) return "secondary"
return "outline"
}
function StatusBadge ( { status } : { status : string } ) {
const normalized = status . toLowerCase ( )
if ( normalized === "published" ) {
return (
< Badge className = "gap-1.5 border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-50" variant = "outline" >
< CheckCircle2 className = "size-3.5" / >
О п у б л и к о в а н о
< / Badge >
)
}
if ( normalized === "drafted" || normalized === "draft" ) {
return (
< Badge className = "gap-1.5 border-zinc-200 bg-zinc-100 text-zinc-600 hover:bg-zinc-100" variant = "outline" >
< FilePenLine className = "size-3.5" / >
Ч е р н о в и к
< / Badge >
)
}
if ( normalized === "error" ) {
return (
< Badge className = "gap-1.5" variant = "destructive" >
< AlertTriangle className = "size-3.5" / >
О ш и б к а
< / Badge >
)
}
if ( normalized === "processing" || normalized === "queued" ) {
return (
< Badge className = "gap-1.5 border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-50" variant = "outline" >
{ normalized === "processing" ? < Loader2 className = "size-3.5 animate-spin" / > : < Clock3 className = "size-3.5" / > }
{ normalized === "processing" ? "В работе" : "В очереди" }
< / Badge >
)
}
return < Badge variant = { statusVariant ( status ) } > { status } < / Badge >
}
function ArticlePlaceholder() {
return (
< div className = "rounded-md border bg-background p-4" >
< div className = "flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between" >
< div className = "min-w-0 flex-1" >
< div className = "flex items-center gap-2" >
< div className = "h-6 w-24 animate-pulse rounded-full bg-muted" / >
< div className = "h-4 flex-1 animate-pulse rounded bg-muted" / >
< / div >
< div className = "mt-3 h-3 w-5/6 animate-pulse rounded bg-muted" / >
< div className = "mt-2 h-3 w-40 animate-pulse rounded bg-muted" / >
< / div >
< div className = "flex shrink-0 gap-2" >
< div className = "size-9 animate-pulse rounded-md bg-muted" / >
< div className = "size-9 animate-pulse rounded-md bg-muted" / >
< div className = "size-9 animate-pulse rounded-md bg-muted" / >
< / div >
< / div >
< / div >
)
}
export default function App() {
2026-08-08 14:02:14 +03:00
const [ activeView , setActiveView ] = useState < "dashboard" | "settings" > ( "dashboard" )
const [ appSettings , setAppSettings ] = useState < AppSettings > ( { signatureHtml : "" , llmInstructions : "" } )
2026-06-27 14:07:10 +03:00
const [ videos , setVideos ] = useState < Video [ ] > ( [ ] )
const [ articles , setArticles ] = useState < Article [ ] > ( [ ] )
const [ articlesHasMore , setArticlesHasMore ] = useState ( false )
const [ articlesLoading , setArticlesLoading ] = useState ( false )
const [ selectedLog , setSelectedLog ] = useState < VideoLog | null > ( null )
const [ selectedArticle , setSelectedArticle ] = useState < ArticleDetail | null > ( null )
2026-08-08 14:02:14 +03:00
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 ( "" )
const [ publishAt , setPublishAt ] = useState ( "" )
const [ editorDirty , setEditorDirty ] = useState ( false )
const [ editorBusy , setEditorBusy ] = useState ( false )
2026-08-08 14:02:14 +03:00
const [ featureImageBusy , setFeatureImageBusy ] = useState ( false )
const [ featureImageDragActive , setFeatureImageDragActive ] = useState ( false )
const [ featureImageHoverActive , setFeatureImageHoverActive ] = useState ( false )
const [ copyToast , setCopyToast ] = useState ( "" )
2026-06-27 14:07:10 +03:00
const [ statusMessage , setStatusMessage ] = useState ( "" )
const [ busy , setBusy ] = useState ( false )
2026-08-08 14:02:14 +03:00
const [ manualVideoUrl , setManualVideoUrl ] = useState ( "" )
const [ manualVideoBusy , setManualVideoBusy ] = 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 )
2026-08-08 14:02:14 +03:00
const featureImageInputRef = useRef < HTMLInputElement | null > ( null )
const featureImageHoverRef = useRef ( false )
const editorImageHoverBlockRef = useRef < BlockAPI | null > ( null )
const pasteImageTargetRef = useRef < "feature" | "editor" | null > ( null )
const imageCaptionNormalizeTimerRef = useRef < number [ ] > ( [ ] )
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 )
const articlesOffsetRef = useRef ( 0 )
const articlesLoadingRef = useRef ( false )
const articlesHasMoreRef = useRef ( false )
2026-08-08 14:02:14 +03:00
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
2026-08-08 14:02:14 +03:00
. 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 ]
)
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-08 14:02:14 +03:00
const [ nextVideos , nextArticles ] = 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 ` ) ,
] )
setVideos ( nextVideos )
setArticles ( nextArticles . items )
articlesOffsetRef . current = nextArticles . items . length
articlesHasMoreRef . current = nextArticles . hasMore
setArticlesHasMore ( nextArticles . hasMore )
} finally {
if ( showArticlePlaceholders ) {
setArticlesLoading ( false )
}
}
}
useEffect ( ( ) = > {
refresh ( ) . catch ( ( error ) = > {
setStatusMessage ( ` Ошибка загрузки: ${ error . message } ` )
} )
2026-08-08 14:02:14 +03:00
api < AppSettings > ( "/api/settings" ) . then ( setAppSettings ) . catch ( ( ) = > undefined )
2026-06-27 14:07:10 +03:00
} , [ ] )
useEffect ( ( ) = > {
if ( activeVideos . length === 0 ) return
const timer = window . setInterval ( ( ) = > {
refresh ( ) . catch ( ( error ) = > {
setStatusMessage ( ` Ошибка обновления: ${ error . message } ` )
} )
} , 5000 )
return ( ) = > window . clearInterval ( timer )
} , [ activeVideos . length ] )
2026-08-08 14:02:14 +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-08 14:02:14 +03:00
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 )
}
}
2026-08-08 14:02:14 +03:00
async function importManualVideo ( event : FormEvent < HTMLFormElement > ) {
event . preventDefault ( )
const url = manualVideoUrl . trim ( )
if ( ! url ) return
setManualVideoBusy ( true )
try {
const imported = await api < { id : number ; title : string ; sourceUrl : string ; durationSeconds? : number ; status : string } > ( "/api/videos/import" , {
method : "POST" ,
body : JSON.stringify ( { url } ) ,
} )
setManualVideoUrl ( "" )
setStatusMessage ( ` Ссылка проверена через yt-dlp: ${ imported . title } . Готовлю ролик к обработке. ` )
await refresh ( )
await prepareVideoProcessing ( {
id : imported.id ,
title : imported.title ,
sourceUrl : imported.sourceUrl ,
status : imported.status ,
progressPercent : 0 ,
progressStage : "" ,
durationSeconds : imported.durationSeconds ,
articleIds : [ ] ,
} )
} catch ( error ) {
setStatusMessage ( ` Н е удалось добавить ролик: ${ error instanceof Error ? error.message : String ( error ) } ` )
} finally {
setManualVideoBusy ( false )
}
}
async function prepareVideoProcessing ( video : Video , recreateDrafts = false ) {
if ( ( video . durationSeconds || 0 ) < 20 * 60 ) {
await processVideo ( video . id , recreateDrafts )
return
}
setVideoActionId ( video . id )
try {
const result = await api < VideoChaptersResponse > ( ` /api/videos/ ${ video . id } /chapters ` )
if ( ! result . canSplit || result . chapters . length < 2 ) {
await processVideo ( video . id )
return
}
const initiallySelected = result . chapters . filter ( ( chapter ) = > chapter . selected ) . map ( ( chapter ) = > chapter . id )
const storedSelection = loadStoredChapterSelection ( video . id )
const availableIds = new Set ( result . chapters . map ( ( chapter ) = > chapter . id ) )
const restoredSelection = storedSelection ? . filter ( ( id ) = > availableIds . has ( id ) )
setChapterPlan ( { video , chapters : result.chapters , recreateDrafts } )
setSelectedChapterIds (
new Set (
storedSelection !== null
? restoredSelection
: initiallySelected . length
? initiallySelected
: result . chapters . map ( ( chapter ) = > chapter . id )
)
)
} finally {
setVideoActionId ( null )
}
}
async function processVideo ( id : number , restart = false , chapters? : VideoChapter [ ] ) {
2026-06-27 14:07:10 +03:00
setVideoActionId ( id )
try {
2026-08-08 14:02:14 +03:00
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 )
}
}
2026-08-08 14:02:14 +03:00
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 )
}
async function openArticlePreview ( id : number ) {
const result = await api < ArticleDetail > ( ` /api/articles/ ${ id } ` )
setSelectedArticle ( result )
setEditorTitle ( result . title )
setPublishAt ( toDateTimeLocalValue ( result . publishedAt ) || currentDateTimeLocalValue ( ) )
setEditorDirty ( false )
}
async function publishArticle ( id : number , scheduledAt? : string ) {
const result = await api < { url : string ; publishedAt? : string } > ( ` /api/articles/ ${ id } /publish ` , {
method : "POST" ,
body : JSON.stringify ( { publishedAt : scheduledAt || null } ) ,
} )
const isFuture = isScheduledForFuture ( result . publishedAt )
setStatusMessage ( isFuture ? ` Запланировал статью на ${ formatDateTime ( result . publishedAt ) } : ${ result . url } ` : ` Принял статью и отправил в RSS: ${ result . url } ` )
await refresh ( )
}
async function uploadImage ( file : File ) {
const body = new FormData ( )
body . append ( "file" , file )
const result = await api < { url : string } > ( "/api/uploads/images" , {
method : "POST" ,
body ,
} )
return result . url
}
2026-08-08 14:02:14 +03:00
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 ( )
2026-08-11 12:05:00 +03:00
event . stopImmediatePropagation ( )
pasteImageTargetRef . current = null
2026-08-08 14:02:14 +03:00
void setFeatureImageFile ( file )
return
}
if ( target === "editor" && editorImageHoverBlockRef . current && ! featureImageHoverRef . current ) {
event . preventDefault ( )
2026-08-11 12:05:00 +03:00
event . stopImmediatePropagation ( )
pasteImageTargetRef . current = null
2026-08-08 14:02:14 +03:00
void replaceEditorImageFile ( file , editorImageHoverBlockRef . current )
}
}
2026-08-11 12:05:00 +03:00
window . addEventListener ( "paste" , handleImagePaste , true )
return ( ) = > window . removeEventListener ( "paste" , handleImagePaste , true )
2026-08-08 14:02:14 +03:00
} , [ ] )
2026-06-27 14:07:10 +03:00
useEffect ( ( ) = > {
if ( ! selectedArticle || ! editorHolderRef . current ) return
editorInstanceRef . current ? . destroy ( )
editorHolderRef . current . innerHTML = ""
2026-08-08 14:02:14 +03:00
const articleData = htmlToEditorData ( selectedArticle . editableHtml || selectedArticle . contentHtml , selectedArticle . title )
const editorData = appendSignatureToEditorData (
articleData ,
selectedArticle . status !== "published" ? appSettings . signatureHtml : "" ,
)
if ( editorData . blocks . length !== articleData . blocks . length ) setEditorDirty ( true )
2026-06-27 14:07:10 +03:00
const editor = new EditorJS ( {
holder : editorHolderRef.current ,
2026-08-08 14:02:14 +03:00
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" ] ,
config : {
captionPlaceholder : "Подпись к изображению" ,
uploader : {
2026-08-08 14:02:14 +03:00
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
} ,
} ,
} ,
randomFrame : {
class : RandomFrameTune as unknown as ToolConstructable ,
config : {
onReplace : replaceWithRandomFrame ,
} ,
} ,
} ,
2026-08-08 14:02:14 +03:00
onChange : ( ) = > {
setEditorDirty ( true )
scheduleEmptyImageCaptionNormalization ( )
} ,
2026-06-27 14:07:10 +03:00
} )
editorInstanceRef . current = editor
editor . isReady . catch ( ( error ) = > {
setStatusMessage ( ` Ошибка редактора: ${ error } ` )
} )
2026-08-08 14:02:14 +03:00
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 ( )
2026-08-11 12:06:19 +03:00
event . stopImmediatePropagation ( )
pasteImageTargetRef . current = null
2026-08-08 14:02:14 +03:00
void replaceEditorImageFile ( file , block )
}
holder ? . addEventListener ( "mousemove" , handleEditorMouseMove )
holder ? . addEventListener ( "mouseleave" , handleEditorMouseLeave )
holder ? . addEventListener ( "dragover" , handleEditorDragOver )
2026-08-11 12:06:19 +03:00
holder ? . addEventListener ( "drop" , handleEditorDrop , true )
2026-06-27 14:07:10 +03:00
return ( ) = > {
2026-08-08 14:02:14 +03:00
holder ? . removeEventListener ( "mousemove" , handleEditorMouseMove )
holder ? . removeEventListener ( "mouseleave" , handleEditorMouseLeave )
holder ? . removeEventListener ( "dragover" , handleEditorDragOver )
2026-08-11 12:06:19 +03:00
holder ? . removeEventListener ( "drop" , handleEditorDrop , true )
2026-08-08 14:02:14 +03:00
clearEditorImageHover ( )
clearImageCaptionNormalizationTimers ( )
2026-06-27 14:07:10 +03:00
if ( editorInstanceRef . current === editor ) {
editorInstanceRef . current = null
}
editor . destroy ( )
}
2026-08-08 14:02:14 +03:00
} , [ selectedArticle ? . id , appSettings . signatureHtml ] )
2026-06-27 14:07:10 +03:00
2026-08-08 14:02:14 +03:00
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 {
2026-08-08 14:02:14 +03:00
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 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-08 14:02:14 +03:00
featureImageUrl : selectedArticle.featureImageUrl || "" ,
2026-06-27 14:07:10 +03:00
editableHtml : editorDataToHtml ( editorData ? ? htmlToEditorData ( "" , editorTitle ) , editorTitle ) ,
} ) ,
} )
setSelectedArticle ( result )
setEditorTitle ( result . title )
setEditorDirty ( false )
await refresh ( )
if ( showMessage ) {
setStatusMessage ( ` Сохранил статью: ${ result . title } ` )
}
return result
} finally {
setEditorBusy ( false )
}
}
async function saveAndPublishArticle() {
if ( ! selectedArticle ) return
const article = editorDirty ? await saveArticle ( false ) : selectedArticle
if ( ! article ) return
const scheduledAt = publishAt ? new Date ( publishAt ) . toISOString ( ) : undefined
await publishArticle ( article . id , scheduledAt )
setSelectedArticle ( null )
}
2026-08-08 14:02:14 +03:00
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" } )
2026-08-08 14:02:14 +03:00
clearStoredChapterSelection ( id )
2026-06-27 14:07:10 +03:00
setStatusMessage ( ` Удалил ролик ${ title ? ` : ${ title } ` : "" } . Он исключен из повторного импорта. ` )
await refresh ( )
} finally {
setVideoActionId ( null )
}
}
return (
2026-08-08 14:02:14 +03:00
< main className = "min-h-screen bg-muted/35 editorial-studio" >
< 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-06-27 14:07:10 +03:00
< div className = "flex items-center gap-3" >
2026-08-08 14:02:14 +03:00
< 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 >
< / div >
< div className = "flex flex-wrap items-center gap-2" >
2026-08-08 14:02:14 +03:00
< 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 >
2026-08-08 14:02:14 +03:00
< 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" / >
2026-08-08 14:02:14 +03:00
VK
2026-06-27 14:07:10 +03:00
< / Button >
< / div >
< / header >
2026-08-08 14:02:14 +03:00
{ 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 >
{ statusMessage ? < div className = "status-message flex min-w-0 items-center rounded-md border bg-background px-4 py-3 text-sm text-muted-foreground" > { statusMessage } < / div > : null }
< / div >
) : null }
2026-06-27 14:07:10 +03:00
2026-08-08 14:02:14 +03:00
{ activeView === "settings" ? (
< SettingsPanel onBack = { ( ) = > setActiveView ( "dashboard" ) } onSaved = { handleSettingsSaved } / >
) : < >
< section className = "workspace-grid grid gap-5 xl:grid-cols-2" >
< Card className = "work-column min-w-0" >
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 >
2026-08-08 14:02:14 +03:00
< 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 ) = > {
2026-08-08 14:02:14 +03:00
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 ]
2026-08-08 14:02:14 +03:00
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
const isActive = [ "queued" , "processing" ] . includes ( video . status )
const isSubmitting = videoActionId === video . id
2026-08-08 14:02:14 +03:00
const hasDraftAction = draftArticles . length > 0 || Boolean ( draftArticleId )
2026-06-27 14:07:10 +03:00
return (
2026-08-08 14:02:14 +03:00
< 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" >
2026-08-08 14:02:14 +03:00
{ 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" >
2026-08-11 11:56:47 +03:00
< 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 }
2026-08-08 14:02:14 +03:00
{ 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" >
2026-08-08 14:02:14 +03:00
{ 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 ? (
2026-08-08 14:02:14 +03:00
< >
< 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"
disabled = { isSubmitting }
className = "border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100 hover:text-amber-900"
onClick = { ( ) = > processVideo ( video . id , true ) }
>
< RefreshCw data-icon = "inline-start" className = { isSubmitting ? "animate-spin" : "" } / >
П е р е з а п у с т и т ь
< / Button >
) : (
< Button
size = "icon"
variant = "outline"
disabled = { isSubmitting }
title = "Обработать"
aria - label = "Обработать"
2026-08-08 14:02:14 +03:00
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 >
2026-08-08 14:02:14 +03:00
< Card className = "work-column min-w-0" >
2026-06-27 14:07:10 +03:00
< CardHeader >
< CardTitle > С т а т ь и < / CardTitle >
< CardDescription > П р и н я т ы е материалы : уже в ы ш е д ш и е в RSS и о т л о ж е н н ы е п о в р е м е н и . < / CardDescription >
< / CardHeader >
< CardContent
2026-08-08 14:02:14 +03:00
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 ( )
}
} }
>
{ publishedArticles . length > 0 ? (
publishedArticles . map ( ( article ) = > (
2026-08-08 14:02:14 +03:00
< 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-08-08 14:02:14 +03:00
< / > }
2026-06-27 14:07:10 +03:00
< / div >
2026-08-08 14:02:14 +03:00
{ 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" >
2026-08-08 14:02:14 +03:00
{ copyToast ? (
< div className = "pointer-events-none fixed left-1/2 top-5 z-[60] -translate-x-1/2 rounded-md border bg-zinc-950 px-4 py-2 text-sm font-medium text-white shadow-lg" >
{ copyToast }
< / div >
) : null }
2026-06-27 14:07:10 +03:00
< 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 = "flex items-start justify-between gap-4 border-b p-5" >
< div className = "min-w-0" >
< div className = "flex flex-wrap items-center gap-2" >
{ isScheduledForFuture ( selectedArticle . publishedAt ) ? (
< Badge className = "gap-1.5 border-sky-200 bg-sky-50 text-sky-700 hover:bg-sky-50" variant = "outline" >
< Clock3 className = "size-3.5" / >
О т л о ж е н о
< / Badge >
) : (
< StatusBadge status = { selectedArticle . status } / >
) }
< h2 className = "min-w-0 flex-1 truncate text-lg font-semibold tracking-normal" > Р е д а к т и р о в а н и е с т а т ь и < / h2 >
{ editorDirty ? < Badge variant = "secondary" > е с т ь п р а в к и < / Badge > : null }
< / div >
< p className = "mt-1 text-sm text-muted-foreground" > Р е д а к т и р у й т е б л о к и к а к в Medium . Д л я к а р т и н к и в ы б е р и т е image - б л о к и н а ж м и т е к н о п к у с л у ч а й н о г о к а д р а . < / p >
< / div >
< div className = "flex shrink-0 flex-wrap justify-end gap-2" >
< input
2026-08-08 14:02:14 +03:00
ref = { featureImageInputRef }
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 = ""
2026-08-08 14:02:14 +03:00
if ( file ) await setFeatureImageFile ( file )
2026-06-27 14:07:10 +03:00
} }
/ >
< Button
size = "icon"
variant = "outline"
disabled = { editorBusy }
2026-08-08 14:02:14 +03:00
title = "Скопировать заголовок и текст без картинок"
aria - label = "Скопировать заголовок и текст без картинок"
onClick = { copyArticleText }
2026-06-27 14:07:10 +03:00
>
2026-08-08 14:02:14 +03:00
< Copy className = "size-4" / >
2026-06-27 14:07:10 +03:00
< / Button >
< Button size = "icon" variant = "outline" disabled = { editorBusy || ! editorDirty } title = "Сохранить" aria-label = "Сохранить" onClick = { ( ) = > saveArticle ( ) } >
< Save className = "size-4" / >
< / Button >
{ selectedArticle . status !== "published" || isScheduledForFuture ( selectedArticle . publishedAt ) ? (
< >
< label className = "flex h-9 items-center gap-2 rounded-md border bg-background px-3 text-xs text-muted-foreground" title = "Время выхода в RSS" >
< Clock3 className = "size-4" / >
< input
type = "datetime-local"
className = "w-[190px] bg-transparent text-sm text-foreground outline-none"
value = { publishAt }
onChange = { ( event ) = > setPublishAt ( event . target . value ) }
/ >
< / label >
< Button size = "icon" disabled = { editorBusy } title = "Запланировать или принять в RSS" aria-label = "Запланировать или принять в RSS" onClick = { saveAndPublishArticle } >
< Radio className = "size-4" / >
< / Button >
< / >
) : (
< Button size = "icon" variant = "outline" title = "Открыть на сайте" aria-label = "Открыть на сайте" onClick = { ( ) = > window . open ( selectedArticle . url , "_blank" ) } >
< ExternalLink className = "size-4" / >
< / Button >
) }
< Button size = "icon" variant = "outline" disabled = { editorBusy } title = "Удалить" aria-label = "Удалить" onClick = { ( ) = > deleteArticle ( selectedArticle . id ) } >
< Trash2 className = "size-4" / >
< / Button >
< Button variant = "outline" size = "icon" title = "Закрыть" aria-label = "Закрыть" onClick = { ( ) = > setSelectedArticle ( null ) } >
< X className = "size-4" / >
< / Button >
< / div >
< / div >
< div className = "overflow-y-auto bg-zinc-50 p-4 sm:p-6" >
< article className = "mx-auto w-full max-w-[1024px] rounded-lg border bg-white px-5 py-7 shadow-sm sm:px-8 lg:px-10" >
2026-08-08 14:02:14 +03:00
< div className = "mb-6" >
< div className = "mb-2 flex items-center justify-between gap-3" >
< div >
< p className = "text-sm font-semibold text-zinc-950" > Feature Image < / p >
< p className = "text-xs text-muted-foreground" > Г л а в н а я о б л о ж к а п у б л и к а ц и и д л я RSS и Д з е н а . < / p >
< / div >
< Button
size = "sm"
variant = "outline"
disabled = { featureImageBusy }
onClick = { ( ) = > featureImageInputRef . current ? . click ( ) }
>
< ImagePlus data-icon = "inline-start" className = { featureImageBusy ? "animate-pulse" : "" } / >
В ы б р а т ь
< / Button >
< / div >
< div
className = { ` relative flex aspect-video w-full cursor-pointer items-center justify-center overflow-hidden rounded-md border border-dashed transition ${
featureImageDragActive ? "border-primary bg-primary/5" : "border-zinc-300 bg-zinc-50 hover:bg-zinc-100"
} ` }
onClick = { ( ) = > featureImageInputRef . current ? . click ( ) }
onMouseEnter = { ( ) = > {
clearEditorImageHover ( )
pasteImageTargetRef . current = "feature"
featureImageHoverRef . current = true
setFeatureImageHoverActive ( true )
} }
onMouseLeave = { ( ) = > {
featureImageHoverRef . current = false
if ( pasteImageTargetRef . current === "feature" ) {
pasteImageTargetRef . current = null
}
setFeatureImageHoverActive ( false )
} }
onDragOver = { ( event ) = > {
event . preventDefault ( )
clearEditorImageHover ( )
pasteImageTargetRef . current = "feature"
setFeatureImageDragActive ( true )
} }
onDragLeave = { ( ) = > {
if ( ! featureImageHoverRef . current && pasteImageTargetRef . current === "feature" ) {
pasteImageTargetRef . current = null
}
setFeatureImageDragActive ( false )
} }
onDrop = { async ( event ) = > {
event . preventDefault ( )
const file = imageFileFromDataTransfer ( event . dataTransfer )
if ( file ) await setFeatureImageFile ( file )
else setFeatureImageDragActive ( false )
} }
>
{ selectedArticle . featureImageUrl ? (
< img src = { selectedArticle . featureImageUrl } alt = { selectedArticle . title } className = "h-full w-full object-cover" / >
) : (
< div className = "flex flex-col items-center gap-2 text-center text-sm text-muted-foreground" >
< ImagePlus className = "size-7" / >
< span > П е р е т а щ и т е о б л о ж к у с ю д а и л и в ы б е р и т е ф а й л < / span >
< / div >
) }
{ featureImageBusy ? (
< div className = "absolute inset-0 flex items-center justify-center bg-background/70 text-sm font-medium" >
З а г р у ж а ю . . .
< / div >
) : null }
{ ! featureImageBusy && ( featureImageHoverActive || featureImageDragActive ) ? (
< div className = "absolute inset-0 flex items-center justify-center bg-zinc-950/55 p-4 text-center text-sm font-semibold text-white backdrop-blur-[1px] transition" >
< div className = "rounded-full border border-white/35 bg-zinc-950/70 px-4 py-2 shadow-lg" >
В с т а в ь т е и з о б р а ж е н и е и з б у ф е р а о б м е н а и л и п р и н е с и т е ф а й л
< / div >
< / div >
) : null }
< / div >
< / div >
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 ) = > {
setEditorTitle ( event . target . value )
setEditorDirty ( true )
} }
/ >
< div
key = { selectedArticle . id }
ref = { editorHolderRef }
className = "article-editor article-editorjs mt-6"
/ >
< / article >
< / div >
< / div >
< / div >
) : null }
< / main >
)
}