import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { InputHTMLAttributes } from "react"; import type { FileEntry, Job, DownloadJob, VideoInfo, RemoteEntry, TeleboxEntry, BackblazeEntry, Tab, PixeldrainJob, QueueItem, EncodePreset, RemoteCredentials } from "./types"; import { api } from "./api"; import { CloseIcon, FolderIcon, DownloadIcon, UploadIcon, EditIcon, DeleteIcon, DragHandleIcon, ChevronUpIcon, ChevronDownIcon, SpinnerIcon, ListIcon, SelectAllIcon, ClearIcon } from "./icons"; import { AdvancedTrimCropModal } from "./components/AdvancedTrimCropModal"; import { CredentialsModal } from "./components/Modals"; import { normalizeRemoteUrl } from "./utils/credentials"; // ─── Helpers ────────────────────────────────────────────────────────────────── function fmt(bytes: number): string { if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`; if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(2)} MB`; return `${(bytes / 1024 ** 3).toFixed(2)} GB`; } function fmtEta(s: number): string { if (!Number.isFinite(s) || s <= 0) return "0s"; const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); const sec = Math.floor(s % 60); return [h && `${h}h`, m && `${m}m`, `${sec}s`].filter(Boolean).join(" "); } function secondsToHms(total: number): string { const h = Math.floor(total / 3600); const m = Math.floor((total % 3600) / 60); const s = Math.floor(total % 60); return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`; } function hmsToSeconds(hms: string): number { const parts = hms.split(":").map(Number); if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2]; if (parts.length === 2) return parts[0] * 60 + parts[1]; return parts[0] || 0; } function pad2(v: number): string { return String(Math.max(0, v)).padStart(2, "0"); } function formatAspectRatio(width: number, height: number): string { const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b)); const divisor = gcd(width, height); return `${width / divisor}:${height / divisor}`; } function toHmsString(h: number, m: number, s: number): string { return `${pad2(h)}:${pad2(m)}:${pad2(s)}`; } function clampParts(h: number, m: number, s: number, maxSeconds?: number): { h: number; m: number; s: number } { let hh = Math.max(0, h); let mm = Math.min(59, Math.max(0, m)); let ss = Math.min(59, Math.max(0, s)); if (maxSeconds !== undefined) { const total = Math.max(0, hh * 3600 + mm * 60 + ss); if (total > maxSeconds) { const clamped = Math.max(0, Math.floor(maxSeconds)); hh = Math.floor(clamped / 3600); mm = Math.floor((clamped % 3600) / 60); ss = Math.floor(clamped % 60); } } return { h: hh, m: mm, s: ss }; } function parseHmsParts(value: string): { h: number; m: number; s: number } { const parts = value.split(":").map((p) => parseInt(p, 10)); if (parts.length === 3) return { h: parts[0] || 0, m: parts[1] || 0, s: parts[2] || 0 }; if (parts.length === 2) return { h: 0, m: parts[0] || 0, s: parts[1] || 0 }; if (parts.length === 1 && parts[0]) return { h: 0, m: 0, s: parts[0] || 0 }; return { h: 0, m: 0, s: 0 }; } function parseLooseTimeToSeconds(input: string): number | null { const value = input.trim(); if (!value) return null; const parts = value.split(":").map((p) => p.trim()); if (parts.some((p) => p === "" || Number.isNaN(Number(p)))) return null; if (parts.length === 2) { const [mm, ss] = parts.map(Number); if (mm < 0 || ss < 0 || ss >= 60) return null; return mm * 60 + ss; } if (parts.length === 3) { const [hh, mm, ss] = parts.map(Number); if (hh < 0 || mm < 0 || ss < 0 || mm >= 60 || ss >= 60) return null; return hh * 3600 + mm * 60 + ss; } return null; } function parsePastedSegments(text: string): { start: string; end: string }[] { const lines = text .split(/\r?\n/) .map((line) => line.trim()) .filter(Boolean); const parsed: { start: string; end: string }[] = []; for (const line of lines) { const match = line.match(/(\d{1,2}:\d{2}(?::\d{2})?)\s*-\s*(\d{1,2}:\d{2}(?::\d{2})?)/); if (!match) continue; const startSec = parseLooseTimeToSeconds(match[1]); const endSec = parseLooseTimeToSeconds(match[2]); if (startSec == null || endSec == null || endSec <= startSec) continue; parsed.push({ start: secondsToHms(startSec), end: secondsToHms(endSec), }); } return parsed; } type CropValues = { cropEnabled: boolean; cropLeft: number; cropRight: number; cropTop: number; cropBottom: number; }; type DirectoryInputProps = InputHTMLAttributes & { webkitdirectory?: string; mozdirectory?: string; }; function TimePartsInput({ value, onChange, maxSeconds, allowEmpty = false, }: { value: string; onChange: (next: string) => void; maxSeconds?: number; allowEmpty?: boolean; }) { const parsed = parseHmsParts(value); const [hLocal, setHLocal] = useState(pad2(parsed.h)); const [mLocal, setMLocal] = useState(pad2(parsed.m)); const [sLocal, setSLocal] = useState(pad2(parsed.s)); const hRef = useRef(null); const mRef = useRef(null); const sRef = useRef(null); const vals = useRef({ h: pad2(parsed.h), m: pad2(parsed.m), s: pad2(parsed.s) }); useEffect(() => { const active = document.activeElement; if (active === hRef.current || active === mRef.current || active === sRef.current) return; const p = parseHmsParts(value); const h = pad2(p.h), m = pad2(p.m), s = pad2(p.s); setHLocal(h); setMLocal(m); setSLocal(s); vals.current = { h, m, s }; }, [value]); const commit = () => { const hNum = parseInt(vals.current.h, 10) || 0; const mNum = Math.min(59, parseInt(vals.current.m, 10) || 0); const sNum = Math.min(59, parseInt(vals.current.s, 10) || 0); const clamped = clampParts(hNum, mNum, sNum, maxSeconds); onChange(toHmsString(clamped.h, clamped.m, clamped.s)); }; const handleInput = (field: "h" | "m" | "s", raw: string) => { const digits = raw.replace(/\D/g, "").slice(0, 2); vals.current[field] = digits; if (field === "h") setHLocal(digits); if (field === "m") setMLocal(digits); if (field === "s") setSLocal(digits); if (digits.length >= 2) { if (field === "h") { setTimeout(() => { mRef.current?.focus(); mRef.current?.select(); }, 0); } if (field === "m") { setTimeout(() => { sRef.current?.focus(); sRef.current?.select(); }, 0); } commit(); } }; const handleBlur = (field: "h" | "m" | "s") => { const num = parseInt(vals.current[field], 10) || 0; const clamped = field === "h" ? num : Math.min(59, num); const padded = pad2(clamped); vals.current[field] = padded; if (field === "h") setHLocal(padded); if (field === "m") setMLocal(padded); if (field === "s") setSLocal(padded); commit(); }; const handleKeyDown = (field: "h" | "m" | "s", e: React.KeyboardEvent) => { if (e.key === "Backspace" && e.currentTarget.value === "") { if (field === "m") { hRef.current?.focus(); hRef.current?.select(); } if (field === "s") { mRef.current?.focus(); mRef.current?.select(); } } }; const handleFocus = (e: React.FocusEvent) => { e.target.select(); }; const fieldCls = "w-12 rounded-lg border border-slate-200 px-1 py-2 text-sm font-mono text-center focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100"; return (
handleInput("h", e.target.value)} onBlur={() => handleBlur("h")} onKeyDown={(e) => handleKeyDown("h", e)} onFocus={handleFocus} className={fieldCls} /> : handleInput("m", e.target.value)} onBlur={() => handleBlur("m")} onKeyDown={(e) => handleKeyDown("m", e)} onFocus={handleFocus} className={fieldCls} /> : handleInput("s", e.target.value)} onBlur={() => handleBlur("s")} onKeyDown={(e) => handleKeyDown("s", e)} onFocus={handleFocus} className={fieldCls} /> {allowEmpty && value.trim() && ( )}
); } // ─── File Type Helpers ──────────────────────────────────────────────────────── const MEDIA_EXTS = new Set([ ".mp4",".mkv",".avi",".mov",".webm",".ts",".m2ts",".flv",".wmv",".mpg",".mpeg", ".mp3",".aac",".opus",".flac",".wav",".m4a",".ogg",".wma",".m4v",".3gp",".vob", ]); const ARCHIVE_EXTS = new Set([ ".zip",".tar",".gz",".tgz",".bz2",".xz",".rar",".7z", ]); const SUBTITLE_EXTS = new Set([ ".srt", ".ass", ".ssa", ".vtt", ".sub", ]); function isMediaFile(name: string): boolean { const lower = name.toLowerCase(); for (const ext of MEDIA_EXTS) { if (lower.endsWith(ext)) return true; } return false; } function isSubtitleFile(name: string): boolean { const lower = name.toLowerCase(); for (const ext of SUBTITLE_EXTS) { if (lower.endsWith(ext)) return true; } return false; } function isArchiveFile(name: string): boolean { const lower = name.toLowerCase(); if (lower.endsWith(".tar.gz") || lower.endsWith(".tar.xz") || lower.endsWith(".tar.bz2")) return true; for (const ext of ARCHIVE_EXTS) { if (lower.endsWith(ext)) return true; } return false; } // ─── Help Tooltip ──────────────────────────────────────────────────────────── function HelpTip({ text }: { text: string }) { const [show, setShow] = useState(false); return ( {show && (
{text}
)} ); } // ─── Toast ─────────────────────────────────────────────────────────────────── function Toast({ message, onDone }: { message: string; onDone: () => void }) { useEffect(() => { const t = setTimeout(onDone, 2500); return () => clearTimeout(t); }, [onDone]); return (
{message}
); } // ─── Upload Area ────────────────────────────────────────────────────────────── // Helper to recursively read directory entries from drag-and-drop async function* getFilesFromDataTransferItems(items: DataTransferItemList, prefix = ""): AsyncGenerator { for (let i = 0; i < items.length; i++) { const item = items[i]; if (item.kind === "file") { const entry = item.webkitGetAsEntry?.(); if (entry?.isFile) { const file = item.getAsFile(); if (file) { if (prefix) { (file as any).__folderPath = prefix; } yield file as File & { __folderPath?: string }; } } else if (entry?.isDirectory) { // Pass the directory name as the initial prefix yield* readDirectoryRecursive(entry as any, entry.name); } } } } async function* readDirectoryRecursive(dir: any, prefix = ""): AsyncGenerator { const reader = dir.createReader(); const entries = await new Promise((resolve, reject) => { reader.readEntries(resolve, reject); }); for (const entry of entries) { const newPrefix = prefix ? `${prefix}/${entry.name}` : entry.name; if (entry.isFile) { const file = await new Promise((resolve, reject) => { (entry as any).file(resolve, reject); }); (file as any).__folderPath = prefix; yield file as File & { __folderPath?: string }; } else if (entry.isDirectory) { yield* readDirectoryRecursive(entry, newPrefix); } } } function UploadArea({ onFilesSelected, busy, dragOver, onDragOver, onDragLeave, uploadInputRef, uploadFolderRef, }: { onFilesSelected: (files: FileList | (File & { __folderPath?: string })[]) => void; busy: boolean; dragOver: boolean; onDragOver: (e: React.DragEvent) => void; onDragLeave: (e: React.DragEvent) => void; uploadInputRef: React.RefObject; uploadFolderRef: React.RefObject; }) { const handleDrop = async (e: React.DragEvent) => { e.preventDefault(); onDragLeave(e); if (e.dataTransfer.items?.length) { try { // Try to read directory structure from drag-and-drop const allFiles: (File & { __folderPath?: string })[] = []; for await (const file of getFilesFromDataTransferItems(e.dataTransfer.items)) { allFiles.push(file); } if (allFiles.length > 0) { onFilesSelected(allFiles); } else if (e.dataTransfer.files) { onFilesSelected(e.dataTransfer.files); } } catch (err) { console.error("Error reading drag-and-drop items:", err); if (e.dataTransfer.files) { onFilesSelected(e.dataTransfer.files); } } } else if (e.dataTransfer.files) { onFilesSelected(e.dataTransfer.files); } }; return (
{busy ? "Uploading..." : "Drop files or folders here"}
e.target.files && onFilesSelected(e.target.files)} className="hidden" disabled={busy} /> e.target.files && onFilesSelected(e.target.files), className: "hidden", disabled: busy, } as DirectoryInputProps)} />
); } // ─── Pixeldrain Upload Progress ─────────────────────────────────────────────── function PixeldrainProgress({ jobId, onClose }: { jobId: string; onClose: () => void }) { const [job, setJob] = useState(null); const [copied, setCopied] = useState(false); const pollInProgressRef = useRef(false); useEffect(() => { const poll = async () => { // Prevent concurrent requests if (pollInProgressRef.current) return; pollInProgressRef.current = true; try { const r = await fetch(`/api/pixeldrain-jobs/${jobId}`); const data = await r.json(); setJob(data.job); if (data.job.status !== "running") { clearInterval(iv); } } catch { /* ignore */ } finally { pollInProgressRef.current = false; } }; poll(); // Increased polling interval from 800ms to 1500ms to reduce server load const iv = setInterval(poll, 1500); return () => clearInterval(iv); }, [jobId]); const copyUrl = () => { if (!job?.pixeldrainUrl) return; navigator.clipboard.writeText(job.pixeldrainUrl); setCopied(true); setTimeout(() => setCopied(false), 2000); }; if (!job) return null; const percent = job.totalBytes > 0 ? Math.min(100, (job.bytesUploaded / job.totalBytes) * 100) : null; return (

☁️ {job.filename}

Uploading to Pixeldrain…

{job.status}
{percent !== null ? (
) : (
)}
{fmt(job.bytesUploaded)}{job.totalBytes > 0 ? ` / ${fmt(job.totalBytes)}` : ""} {percent !== null && {percent.toFixed(1)}%}
{job.status === "done" && job.pixeldrainUrl && (
{job.pixeldrainUrl}
)} {job.status === "failed" && (

{job.error || "Upload failed"}

)}
); } // ─── Merge Modal ────────────────────────────────────────────────────────────── interface MergeItem { uid: string; file: FileEntry; } function MergeModal({ files, onClose, onMergeStarted }: { files: FileEntry[]; onClose: () => void; onMergeStarted: () => void; }) { const [items, setItems] = useState(() => files.map((f) => ({ uid: `$${f.id}_$${Math.random().toString(16).slice(2)}`, file: f })) ); const [outName, setOutName] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const dragUid = useRef(null); const dragOverUid = useRef(null); useEffect(() => { const firstFile = files[0]; if (!firstFile) { setOutName("merged_output.mkv"); return; } const name = firstFile.name; const lastDotIndex = name.lastIndexOf("."); if (lastDotIndex > 0) { const baseName = name.slice(0, lastDotIndex); const ext = name.slice(lastDotIndex); setOutName(`$${baseName}_merged$${ext}`); } else { setOutName(`${name}_merged.mkv`); } }, [files]); const moveUp = (idx: number) => { if (idx === 0) return; const next = [...items]; [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]]; setItems(next); }; const moveDown = (idx: number) => { if (idx === items.length - 1) return; const next = [...items]; [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]]; setItems(next); }; const handleDragStart = (uid: string) => { dragUid.current = uid; }; const handleDragOver = (e: React.DragEvent, uid: string) => { e.preventDefault(); dragOverUid.current = uid; }; const handleDrop = () => { if (!dragUid.current || !dragOverUid.current || dragUid.current === dragOverUid.current) return; const from = items.findIndex((i) => i.uid === dragUid.current); const to = items.findIndex((i) => i.uid === dragOverUid.current); if (from === -1 || to === -1) return; const next = [...items]; const [moved] = next.splice(from, 1); next.splice(to, 0, moved); setItems(next); dragUid.current = null; dragOverUid.current = null; }; const removeItem = (uid: string) => setItems((prev) => prev.filter((i) => i.uid !== uid)); const handleMerge = async () => { if (items.length < 2) { setError("Need at least 2 files to merge"); return; } if (!outName.trim()) { setError("Output filename is required"); return; } setError(null); setBusy(true); try { const r = await fetch("/api/merge", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileIds: items.map((i) => i.file.id), outputFilename: outName.trim() }), }); const data = await r.json(); if (data.error) { setError(data.error); setBusy(false); return; } onMergeStarted(); onClose(); } catch { setError("Failed to start merge"); setBusy(false); } }; return (
e.stopPropagation()}>
🔗

Merge Files

{items.length} files
Drag rows or use ↑↓ to set order. Files joined top→bottom via stream copy (lossless, instant).
{items.map((item, idx) => (
handleDragStart(item.uid)} onDragOver={(e) => handleDragOver(e, item.uid)} onDrop={handleDrop} className="flex items-center gap-3 px-4 py-3 hover:bg-slate-50 cursor-grab active:cursor-grabbing transition-colors"> {idx + 1}

{item.file.name}

{fmt(item.file.sizeBytes)} · {item.file.folder}

{items.length > 2 && ( )}
))}
setOutName(e.target.value)} className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" />
{error &&

{error}

}
💡 Output saved to same folder as the first selected file. Stream copy = instant, lossless.
); } // ─── Move File Modal ────────────────────────────────────────────────────────── function MoveModal({ files, folders, onClose, onMoved }: { files: FileEntry[]; folders: string[]; onClose: () => void; onMoved: () => void; }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const itemCount = files.length; const handleMove = async (targetFolder: string) => { if (files.every((f) => (f.folder || "/") === targetFolder)) { onClose(); return; } setBusy(true); setError(null); try { const ids = files.map((f) => f.id); const data = await api.batchMove(ids, targetFolder); if (data.error) { setError(data.error); setBusy(false); return; } onMoved(); onClose(); } catch { setError("Failed to move file(s)"); setBusy(false); } }; const allFolders = Array.from(new Set(["/", ...folders])).sort((a, b) => { if (a === "/") return -1; if (b === "/") return 1; return a.localeCompare(b); }); return (
e.stopPropagation()}>
↗️

Move {itemCount === 1 ? "File" : `${itemCount} Files`}

{itemCount === 1 ? files[0].name : `${itemCount} selected files`}

Select destination folder:

{error &&

{error}

}
{allFolders.map((folder) => { const isCurrent = files.every((f) => (f.folder || "/") === folder); return ( ); })}
{busy &&

Moving…

}
); } // ─── Create Folder Modal ────────────────────────────────────────────────────── function CreateFolderModal({ onClose, onCreated }: { onClose: () => void; onCreated: (name: string) => void }) { const [name, setName] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const handleCreate = async () => { const trimmed = name.trim(); if (!trimmed) { setError("Folder name is required"); return; } setBusy(true); setError(null); try { const data = await api.createFolder(trimmed); if (data.error) { setError(data.error); setBusy(false); return; } onCreated(data.folder ?? `/${trimmed}`); onClose(); } catch { setError("Failed to create folder"); setBusy(false); } }; return (
e.stopPropagation()}>
📁

New Folder

setName(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") handleCreate(); if (e.key === "Escape") onClose(); }} className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> {error &&

{error}

}
); } // ─── Sub-components ─────────────────────────────────────────────────────────── function Badge({ children, color }: { children: React.ReactNode; color: string }) { return ( {children} ); } function IconBtn({ title, onClick, children, danger, active, disabled }: { title: string; onClick: () => void; children: React.ReactNode; danger?: boolean; active?: boolean; disabled?: boolean; }) { return ( ); } // ─── Info Modal ─────────────────────────────────────────────────────────────── function InfoModal({ file, onClose, initialShowEncode }: { file: FileEntry; onClose: () => void; initialShowEncode?: boolean }) { const [info, setInfo] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [showEncodeSettings, setShowEncodeSettings] = useState(!!initialShowEncode); useEffect(() => { api.getFileInfo(file.id) .then((res) => { if (res.ok) setInfo(res.info); else setError("Failed to load info"); }) .catch(() => setError("Failed to load info")) .finally(() => setLoading(false)); }, [file.id]); const Row = ({ label, value }: { label: string; value: string }) => (
{label} {value}
); return (
e.stopPropagation()}>
🎬

{file.name}

{loading && (
Analyzing file…
)} {error &&
{error}
} {info && (

General

{info.video && (

Video Stream

)} {info.audio && (

Audio Stream

)} {info.audioStreams && info.audioStreams.length > 0 && (

Audio Streams ({info.audioStreams.length})

{info.audioStreams.map((stream, i) => (
Audio #{stream.index}
))}
)} {info.subtitleStreams && info.subtitleStreams.length > 0 && (

Subtitle Streams ({info.subtitleStreams.length})

{info.subtitleStreams.map((stream, i) => (
Subtitle #{stream.index}
))}
)} {!info.video && !info.audio && (!info.audioStreams || info.audioStreams.length === 0) && (!info.subtitleStreams || info.subtitleStreams.length === 0) && (

No stream information available

)} {info.encodeSettings && (
{showEncodeSettings && (
{info.encodeSettings.resolution && ( )} {info.encodeSettings.settings && (() => { const s = info.encodeSettings!.settings as Record; const rows: Array<{ label: string; value: string }> = []; if (s.codec) rows.push({ label: "Codec", value: String(s.codec).toUpperCase() }); if (s.mode) rows.push({ label: "Mode", value: s.mode === "crf-1pass" ? "CRF (1-pass)" : "VBR" }); if (s.crf !== undefined) rows.push({ label: "CRF", value: String(s.crf) }); if (s.videoBitrateKbps) rows.push({ label: "Video Bitrate", value: `${s.videoBitrateKbps} kbps` }); if (s.audioBitrateKbps) rows.push({ label: "Audio Bitrate", value: `${s.audioBitrateKbps} kbps (Opus)` }); if (s.resolution) rows.push({ label: "Resolution", value: String(s.resolution) }); if (s.frameRate) rows.push({ label: "Frame Rate", value: String(s.frameRate) }); if (s.preset !== undefined) rows.push({ label: "Preset", value: String(s.preset) }); if (s.h26xPreset) rows.push({ label: "H26x Preset", value: String(s.h26xPreset) }); if (s.aqMode !== undefined) rows.push({ label: "AQ Mode", value: s.aqMode === 0 ? "0 (Off)" : s.aqMode === 1 ? "1 (Variance)" : "2 (Complexity)" }); if (s.tiles) rows.push({ label: "Tiles", value: String(s.tiles) }); if (s.outputContainer) rows.push({ label: "Container", value: String(s.outputContainer).toUpperCase() }); if (s.audioChannels) rows.push({ label: "Audio Channels", value: String(s.audioChannels) }); if (s.forceStereo) rows.push({ label: "Force Stereo", value: "Yes" }); if (s.sceneChange !== undefined) rows.push({ label: "Scene Change", value: String(s.sceneChange) }); if (s.deinterlace) rows.push({ label: "Deinterlace", value: "Yes" }); if (s.denoise) rows.push({ label: "Denoise", value: "Yes" }); if (s.rotate && s.rotate !== "none") rows.push({ label: "Rotate", value: String(s.rotate) }); if (s.speed && Number(s.speed) !== 1) rows.push({ label: "Speed", value: `${s.speed}×` }); if (s.brightness && Number(s.brightness) !== 0) rows.push({ label: "Brightness", value: String(s.brightness) }); if (s.contrast && Number(s.contrast) !== 1) rows.push({ label: "Contrast", value: String(s.contrast) }); if (s.saturation && Number(s.saturation) !== 1) rows.push({ label: "Saturation", value: String(s.saturation) }); if (s.stripSubtitles) rows.push({ label: "Strip Subtitles", value: "Yes" }); if (s.stripMetadata) rows.push({ label: "Strip Metadata", value: "Yes" }); if (s.subtitleFile) rows.push({ label: "Subtitle File", value: String(s.subtitleFile) }); if (s.subtitleLang) rows.push({ label: "Subtitle Language", value: String(s.subtitleLang) }); if (s.subtitleBurn) rows.push({ label: "Subtitle Burn-in", value: "Yes" }); if (s.startTime) rows.push({ label: "Start Time", value: String(s.startTime) }); if (s.endTime) rows.push({ label: "End Time", value: String(s.endTime) }); return rows.length > 0 ? (
{rows.map((r, i) => (
{r.label}: {r.value}
))}
) : (

No settings available

); })()}
)}
)}
)}
); } function PreviewModal({ title, url, onClose }: { title: string; url: string; onClose: () => void }) { const videoRef = useRef(null); const [seekStep, setSeekStep] = useState(6); const seek = (delta: number) => { const v = videoRef.current; if (!v) return; v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta)); }; useEffect(() => { const onKey = (e: KeyboardEvent) => { const tag = (e.target as HTMLElement).tagName; if (tag === "INPUT" || tag === "TEXTAREA") return; if (e.key === "ArrowLeft") { e.preventDefault(); seek(-seekStep); } if (e.key === "ArrowRight") { e.preventDefault(); seek(seekStep); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [seekStep]); return (
e.stopPropagation()}>

Preview: {title}

Video playback uses the browser's media player.

); } // ─── Crop Modal ───────────────────────────────────────────────────────────── function CropModal({ file, onClose, onDone }: { file: FileEntry; onClose: () => void; onDone: (values: CropValues) => void; }) { const videoRef = useRef(null); const [cropEnabled, setCropEnabled] = useState(false); const [cropLeft, setCropLeft] = useState(0); const [cropRight, setCropRight] = useState(0); const [cropTop, setCropTop] = useState(0); const [cropBottom, setCropBottom] = useState(0); const [seekStep, setSeekStep] = useState(6); const [isVideoPlaying, setIsVideoPlaying] = useState(false); const [videoDimensions, setVideoDimensions] = useState<{ width: number; height: number } | null>(null); const [zoomLevel, setZoomLevel] = useState(100); const [dragAnchor, setDragAnchor] = useState<{ x: number; y: number; left: number; right: number; top: number; bottom: number } | null>(null); const applyPreset = (preset: "lt" | "rt" | "up" | "low") => { const map: Record = { lt: { cropEnabled: true, cropLeft: 20, cropRight: 20, cropTop: 10, cropBottom: 10 }, rt: { cropEnabled: true, cropLeft: 10, cropRight: 20, cropTop: 10, cropBottom: 10 }, up: { cropEnabled: true, cropLeft: 10, cropRight: 10, cropTop: 20, cropBottom: 10 }, low: { cropEnabled: true, cropLeft: 10, cropRight: 10, cropTop: 10, cropBottom: 20 }, }; updateFromValues(map[preset]); }; const updateFromValues = (values: CropValues) => { setCropEnabled(values.cropEnabled); setCropLeft(values.cropLeft); setCropRight(values.cropRight); setCropTop(values.cropTop); setCropBottom(values.cropBottom); }; useEffect(() => { // First check localStorage const saved = localStorage.getItem(`crop-${file.id}`); if (saved) { try { updateFromValues(JSON.parse(saved)); return; // Use localStorage if found } catch {} } // Then check server for savedCropSettings (from .crop.json sidecar) api.getFileInfo(file.id).then((res) => { if (res.ok && res.info?.savedCropSettings) { const s = res.info.savedCropSettings; updateFromValues({ cropEnabled: Boolean(s.cropEnabled), cropLeft: Number(s.cropLeft ?? 0), cropRight: Number(s.cropRight ?? 0), cropTop: Number(s.cropTop ?? 0), cropBottom: Number(s.cropBottom ?? 0), }); } }).catch(() => {}); // Ignore errors }, [file.id]); const handleDone = () => { const values = { cropEnabled, cropLeft, cropRight, cropTop, cropBottom }; try { localStorage.setItem(`crop-${file.id}`, JSON.stringify(values)); } catch {} onDone(values); }; const cropOutputSize = useMemo(() => { if (!videoDimensions) return null; const width = Math.max(1, Math.round(videoDimensions.width * (1 - (cropLeft + cropRight) / 100))); const height = Math.max(1, Math.round(videoDimensions.height * (1 - (cropTop + cropBottom) / 100))); return { width, height }; }, [videoDimensions, cropLeft, cropRight, cropTop, cropBottom]); const seekVideo = (delta: number) => { const v = videoRef.current; if (!v) return; v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta)); }; const togglePlayback = () => { const v = videoRef.current; if (!v) return; if (v.paused) { void v.play(); setIsVideoPlaying(true); } else { v.pause(); setIsVideoPlaying(false); } }; const centerCrop = () => { setCropEnabled(true); setCropLeft(10); setCropRight(10); setCropTop(10); setCropBottom(10); }; const adjustZoom = (delta: number) => { setZoomLevel((prev) => Math.max(50, Math.min(200, prev + delta))); }; const handleCropPointerDown = (event: React.PointerEvent) => { if (!cropEnabled) return; event.preventDefault(); event.currentTarget.setPointerCapture(event.pointerId); setDragAnchor({ x: event.clientX, y: event.clientY, left: cropLeft, right: cropRight, top: cropTop, bottom: cropBottom, }); }; const handleCropPointerMove = (event: React.PointerEvent) => { if (!dragAnchor) return; const rect = event.currentTarget.getBoundingClientRect(); const deltaX = ((event.clientX - dragAnchor.x) / rect.width) * 100; const deltaY = ((event.clientY - dragAnchor.y) / rect.height) * 100; const nextLeft = Math.max(0, Math.min(45, dragAnchor.left + deltaX)); const nextRight = Math.max(0, Math.min(45, dragAnchor.right - deltaX)); const nextTop = Math.max(0, Math.min(45, dragAnchor.top + deltaY)); const nextBottom = Math.max(0, Math.min(45, dragAnchor.bottom - deltaY)); setCropLeft(nextLeft); setCropRight(nextRight); setCropTop(nextTop); setCropBottom(nextBottom); }; const handleCropPointerUp = (event: React.PointerEvent) => { if (dragAnchor) { event.currentTarget.releasePointerCapture(event.pointerId); setDragAnchor(null); } }; useEffect(() => { const onKey = (e: KeyboardEvent) => { const tag = (e.target as HTMLElement).tagName; if (tag === "INPUT" || tag === "TEXTAREA") return; if (e.key === "ArrowLeft") { e.preventDefault(); seekVideo(-seekStep); } if (e.key === "ArrowRight") { e.preventDefault(); seekVideo(seekStep); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [seekStep]); return (
e.stopPropagation()}>

Crop preview

Trim the visible area from the left, right, top, and bottom before encoding.

{zoomLevel === 100 ? "100% (default)" : `${zoomLevel}%`}

Preview

The visible rectangle updates as you adjust the crop values. Drag the highlighted box directly in the preview or use the sliders and the play/seek controls while you crop.

{cropOutputSize && (
Output: {cropOutputSize.width}×{cropOutputSize.height} Aspect: {formatAspectRatio(cropOutputSize.width, cropOutputSize.height)}
)}
{([ ["lt", "LT"], ["rt", "RT"], ["up", "UP"], ["low", "LOW"], ] as const).map(([key, label]) => ( ))}
{[ { key: "cropLeft", label: "Left", value: cropLeft, setter: setCropLeft }, { key: "cropRight", label: "Right", value: cropRight, setter: setCropRight }, { key: "cropTop", label: "Top", value: cropTop, setter: setCropTop }, { key: "cropBottom", label: "Bottom", value: cropBottom, setter: setCropBottom }, ].map((field) => (
{field.label} {field.value}%
field.setter(Number(e.target.value))} className="w-full accent-violet-600 disabled:cursor-not-allowed disabled:opacity-60" />
))}
); } // ─── Trim Modal ─────────────────────────────────────────────────────────────── function TrimModal({ file, onClose, onTrimStarted }: { file: FileEntry; onClose: () => void; onTrimStarted: () => void; }) { type TrimSegment = { id: string; start: string; end: string }; const [duration, setDuration] = useState(null); const [segments, setSegments] = useState([]); const [activeSegmentId, setActiveSegmentId] = useState(""); const [outName, setOutName] = useState(""); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [pasteText, setPasteText] = useState(""); const videoRef = useRef(null); const [previewCurrentTime, setPreviewCurrentTime] = useState(0); const [pendingClipStart, setPendingClipStart] = useState(null); const [seekStep, setSeekStep] = useState(6); const seekVideo = (delta: number) => { const v = videoRef.current; if (!v) return; v.currentTime = Math.max(0, Math.min(isFinite(v.duration) ? v.duration : Infinity, v.currentTime + delta)); }; useEffect(() => { const onKey = (e: KeyboardEvent) => { const tag = (e.target as HTMLElement).tagName; if (tag === "INPUT" || tag === "TEXTAREA") return; if (e.key === "ArrowLeft") { e.preventDefault(); seekVideo(-seekStep); } if (e.key === "ArrowRight") { e.preventDefault(); seekVideo(seekStep); } }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [seekStep]); useEffect(() => { api.getFileInfo(file.id).then((res) => { if (res.ok && res.info.durationSeconds) { const d = res.info.durationSeconds; setDuration(d); } }).finally(() => setLoading(false)); const ext = file.name.match(/(\.[^.]+)$/)?.[1] || ""; const base = file.name.replace(/(\.[^.]+)$/, ""); setOutName(`${base}_trim${ext}`); }, [file]); useEffect(() => { if (segments.length && !segments.some((segment) => segment.id === activeSegmentId)) { setActiveSegmentId(segments[0].id); } if (!segments.length && activeSegmentId) { setActiveSegmentId(""); } }, [segments, activeSegmentId]); const activeSegment = segments.find((segment) => segment.id === activeSegmentId) || segments[0] || null; const startSec = activeSegment ? hmsToSeconds(activeSegment.start) : 0; const endSec = activeSegment ? hmsToSeconds(activeSegment.end) : 0; const trimDuration = Math.max(0, endSec - startSec); const updateSegment = (id: string, field: "start" | "end", value: string) => { setSegments((prev) => prev.map((segment) => segment.id === id ? { ...segment, [field]: value } : segment)); }; const addSegment = () => { const id = `seg_${Math.random().toString(16).slice(2)}`; const lastEnd = segments.length ? hmsToSeconds(segments[segments.length - 1].end) : 0; const nextStart = duration ? Math.min(lastEnd, Math.floor(duration)) : lastEnd; const newSegment = { id, start: secondsToHms(nextStart), end: secondsToHms(nextStart) }; setSegments((prev) => [...prev, newSegment]); setActiveSegmentId(id); }; const removeSegment = (id: string) => { setSegments((prev) => prev.filter((segment) => segment.id !== id)); }; const moveSegment = (idx: number, direction: -1 | 1) => { setSegments((prev) => { const next = [...prev]; const target = idx + direction; if (target < 0 || target >= next.length) return next; [next[idx], next[target]] = [next[target], next[idx]]; return next; }); }; const handlePasteImport = () => { const parsed = parsePastedSegments(pasteText); if (!parsed.length) { setError("No valid clip ranges found in pasted text"); return; } if (duration) { for (const seg of parsed) { if (hmsToSeconds(seg.end) > duration) { setError("One or more pasted segments exceed the file duration"); return; } } } const nextSegments = parsed.map((seg) => ({ id: `seg_${Math.random().toString(16).slice(2)}`, start: seg.start, end: seg.end, })); setSegments(nextSegments); setActiveSegmentId(nextSegments[0].id); setError(null); }; const captureClipStart = () => { const t = Math.floor(videoRef.current?.currentTime ?? 0); setPreviewCurrentTime(t); setPendingClipStart(t); setError(null); }; const captureClipEnd = () => { const t = Math.floor(videoRef.current?.currentTime ?? 0); setPreviewCurrentTime(t); if (pendingClipStart == null) { setError("Set clip start first."); return; } if (t <= pendingClipStart) { setError("Clip end must be after clip start."); return; } const seg = { id: `seg_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`, start: secondsToHms(pendingClipStart), end: secondsToHms(t), }; setSegments((prev) => [...prev, seg]); setActiveSegmentId(seg.id); setPendingClipStart(null); setError(null); }; const undoLastCapturedClip = () => { setSegments((prev) => { if (!prev.length) return prev; const next = prev.slice(0, -1); setActiveSegmentId(next.length ? next[next.length - 1].id : ""); return next; }); setError(null); }; const clearCapturedClips = () => { setSegments([]); setActiveSegmentId(""); setPendingClipStart(null); setError(null); }; const handleTrim = async () => { const normalized = segments.map((segment) => ({ startTime: hmsToSeconds(segment.start), endTime: hmsToSeconds(segment.end), })); for (const segment of normalized) { if (segment.endTime <= segment.startTime) { setError("Each segment needs an end time after its start time"); return; } if (duration && segment.endTime > duration) { setError("One or more segments exceed the file duration"); return; } } if (!outName.trim()) { setError("Output filename is required"); return; } setError(null); setBusy(true); try { await api.trimSegments(file.id, normalized, outName.trim()); onTrimStarted(); onClose(); } catch { setError("Failed to start trim job"); } finally { setBusy(false); } }; return (
✂️

Trim & Merge segments

Create multiple ranges and merge them into one seamless file.

{/* ── Always-visible OSD bar ── */} {!loading && (
Duration:{" "} {duration != null ? secondsToHms(Math.floor(duration)) : "—"} Current:{" "} {secondsToHms(Math.floor(previewCurrentTime))} Pending start:{" "} {pendingClipStart == null ? "—" : secondsToHms(Math.floor(pendingClipStart))}
)}
{loading ? (
Loading file info…
) : ( <> {/* ── Video player + seek + set start/end ── */}
{/* ── Paste clip list ── */}