"use client"; import { useEffect, useRef, useState, useSyncExternalStore } from "react"; import { ScissorsIcon } from "lucide-react"; import { ControlButton, usePlayer } from "./PlayerProvider"; import { cancelledSentence, formatBytes, formatClock } from "../lib/localClip"; import { cancelLocalClip, clipKey, closeLocalClip, getIdleLocalClipState, getLocalClipState, prepareLocalClip, saveLocalClip, subscribeLocalClip, type ClipJobState, } from "../lib/localClipJob"; // A CLIP OF THE VISITOR'S OWN COPY (lane browser-clip), in the "Your copy" // bar: the modal's Clip in / Clip out marks (cue clock, the visitor's offset // applied) cut from the picked file by a stream copy, in this browser. The // page says where the clip really starts — the keyframe at or before the in // mark — before anything is saved. // // Screen readers hear it through ONE live region that stays mounted while a // copy is playing (its text changes; the group's own lines are not live), so a // clip cancelled by closing the group is still said. // // Nothing in this file may reach the network or storage; LocalFilePicker.test.ts // reads this source too. The engine is loaded by lib/localClipJob.ts only when // the visitor opens this panel. export const CLIP_BUTTON = "Clip my copy"; const CLIP_BUTTON_OFF = "Mark Clip in and Clip out first"; const LIBRARY_VERSION = "1.45.3"; const LIBRARY_SOURCE = `https://github.com/Vanilagy/mediabunny/tree/v${LIBRARY_VERSION}`; type Picker = (opts: { suggestedName: string; types: { description: string; accept: Record }[]; }) => Promise<{ createWritable: () => Promise }>; function savePicker(): Picker | null { if (typeof window === "undefined") return null; const p = (window as unknown as { showSaveFilePicker?: unknown }).showSaveFilePicker; return typeof p === "function" ? (p.bind(window) as Picker) : null; } const MIME_BY_EXT: Record = { ".mp4": "video/mp4", ".m4a": "audio/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".mkv": "video/x-matroska", ".mka": "audio/x-matroska", }; function extOf(name: string): string { const i = name.lastIndexOf("."); return i >= 0 ? name.slice(i) : ""; } function doneSentence(job: Extract): string { return job.path === "disk" ? `Saved ${job.name} (${formatBytes(job.bytes)}).` : `Your browser is saving ${job.name} (${formatBytes(job.bytes)}).`; } // What the live region says for a state: the sentence that changed, never the // running percentage. function announcement(job: ClipJobState, canClip: boolean): string { if (!canClip && job.phase !== "saving") return job.phase === "idle" ? "" : "Mark Clip in and Clip out first."; switch (job.phase) { case "idle": return ""; case "preparing": return "Finding the keyframe…"; case "refused": case "failed": return job.sentence; case "ready": return [job.range, job.start, job.end, `About ${formatBytes(job.plan.estimate)}, saved as ${job.name}.`] .filter(Boolean) .join(" "); case "saving": return `Saving ${job.name}.`; case "done": return doneSentence(job); case "cancelled": return cancelledSentence(job.path); } } export function LocalClipPanel() { const { data, clipStart, clipEnd, localFile, getLocalFile } = usePlayer(); const job = useSyncExternalStore(subscribeLocalClip, getLocalClipState, getIdleLocalClipState); const [open, setOpen] = useState(false); // Said by the live region after the group closed (a save cancelled by it). const [closedNote, setClosedNote] = useState(""); const triggerRef = useRef(null); const groupRef = useRef(null); const canClip = clipStart !== null && clipEnd !== null && clipEnd > clipStart; const shown = open || job.phase !== "idle"; const offset = localFile?.offset ?? 0; // Prepare (again) whenever what the clip depends on changes, unless one is // being made; a refusal that may not hold (a failed read) is prepared again // when its key is asked for again (the job allows that once). const file = getLocalFile(); const key = file && canClip ? clipKey({ file, cueIn: clipStart!, cueOut: clipEnd!, offset }) : null; useEffect(() => { if (!shown || !file || key === null || !data) return; const st = getLocalClipState(); if (st.phase === "saving") return; if ("key" in st && st.key === key && !(st.phase === "refused" && st.retry)) return; void prepareLocalClip({ file, cueIn: clipStart!, cueOut: clipEnd!, offset, title: data.title, slug: data.slug, canSaveToDisk: savePicker() !== null, }); }, [shown, key, file, data, clipStart, clipEnd, offset]); // Saving moves the focus to Cancel; when Cancel goes (done, cancelled, // failed) and took the focus with it, the focus goes to "Clip my copy". const savingNow = job.phase === "saving"; const wasSaving = useRef(false); useEffect(() => { if (savingNow) { groupRef.current?.querySelector('[data-clip-action="cancel"]')?.focus(); } else if (wasSaving.current) { const active = document.activeElement; if (!active || active === document.body || !active.isConnected) triggerRef.current?.querySelector("button")?.focus(); } wasSaving.current = savingNow; }, [savingNow]); // While the panel shows, the player gives the modal's column room on a // short window (export/app/globals.css, [data-local-clip-open]): once on // opening and once on closing, never on a state change within it. useEffect(() => { if (!shown) return; const root = document.documentElement; root.setAttribute("data-local-clip-open", ""); return () => root.removeAttribute("data-local-clip-open"); }, [shown]); // Opened, or a new state in it (ready, saving, saved…): the group is // brought into the modal column's view, above its pinned action strip. const phase = job.phase; useEffect(() => { if (shown && groupRef.current) revealInScroller(groupRef.current); }, [shown, phase]); const close = () => { const cancelled = closeLocalClip(); setClosedNote(cancelled ? cancelledSentence(cancelled) : ""); setOpen(false); requestAnimationFrame(() => triggerRef.current?.querySelector("button")?.focus()); }; const save = async (st: Extract, to: "memory" | "disk") => { if (to === "disk") { const picker = savePicker(); if (!picker) return; const ext = extOf(st.name); let writable: WritableStream; try { // First, before anything else awaits: the picker needs the click. const handle = await picker({ suggestedName: st.name, types: [{ description: "Clip", accept: { [MIME_BY_EXT[ext] ?? "video/mp4"]: [ext] } }], }); writable = await handle.createWritable(); } catch { return; // The visitor closed the picker: still ready. } await saveLocalClip({ kind: "disk", writable }); } else { await saveLocalClip({ kind: "memory" }); } }; if (!localFile) return null; return ( <> } disabled={!canClip} highlight={shown} aria-expanded={shown} onClick={() => { if (shown) return close(); setClosedNote(""); setOpen(true); }} />

{shown ? announcement(job, canClip) : closedNote}

{shown && (

Clipping uses Mediabunny {LIBRARY_VERSION} (MPL-2.0):{" "} licence {" "} ·{" "} source

)} ); } // Scrolls the nearest scrolling ancestor — and only it — so `el` is inside its // scrollport less the scroll padding (the modal column pads its bottom by the // sticky action strip's height). scrollIntoView would also scroll every other // ancestor and the page behind the modal; its `container` option is not in // every browser yet. function revealInScroller(el: HTMLElement) { let box = el.parentElement; while (box && !/(auto|scroll)/.test(getComputedStyle(box).overflowY)) box = box.parentElement; if (!box) return; const st = getComputedStyle(box); const b = box.getBoundingClientRect(); const r = el.getBoundingClientRect(); const top = b.top + (parseFloat(st.scrollPaddingTop) || 0); const bottom = b.bottom - (parseFloat(st.scrollPaddingBottom) || 0); // Its bottom edge into view, unless that would hide its top. if (r.bottom > bottom) box.scrollTop += Math.min(r.bottom - bottom, r.top - top); else if (r.top < top) box.scrollTop -= top - r.top; } function Actions({ children }: { children: React.ReactNode }) { return
{children}
; } function ClipBody({ job, canClip, onSave, onClose, }: { job: ClipJobState; canClip: boolean; onSave: (st: Extract, to: "memory" | "disk") => void; onClose: () => void; }) { const closeButton =