commit c817bf8cf24c23aaf14438f7fff6f81b96da0374
parent 697a4f9f32817ac9ce842e3920edd63a6a88217f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 19 Nov 2026 16:41:07 -0500
common: Clip my copy, in the "Your copy" bar
With a local copy playing and both marks set, "Clip my copy" opens a group
that loads the engine (the one dynamic import, lib/localClipLoader.ts),
probes the file and says, before anything is saved, where the clip really
starts ("Starts 1.0 s earlier, at the nearest keyframe (0:00:04.0)."), the
range with the offset applied, the size and the saved file's name. Save
builds it in memory and hands it over as a download, or writes it to a
file the visitor picks when it is big and the browser can; progress and
Cancel; every refusal one sentence.
The job lives in a module store (lib/localClipJob.ts), so Esc collapsing
the modal does not cancel it; clearing or replacing the copy does. The
provider now keeps the picked File in a ref for exactly as long as its
object URL. The source-scan guard covers the new modules and holds the
loader to its one import and the engine to local sources only.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
6 files changed, 568 insertions(+), 4 deletions(-)
diff --git a/common/components/LocalClipPanel.tsx b/common/components/LocalClipPanel.tsx
@@ -0,0 +1,291 @@
+"use client";
+
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { ScissorsIcon } from "lucide-react";
+import { ControlButton, usePlayer } from "./PlayerProvider";
+import { formatBytes, formatClock } from "../lib/localClip";
+import {
+ cancelLocalClip,
+ clipKey,
+ getIdleLocalClipState,
+ getLocalClipState,
+ prepareLocalClip,
+ resetLocalClip,
+ 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.
+//
+// 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";
+
+type Picker = (opts: {
+ suggestedName: string;
+ types: { description: string; accept: Record<string, string[]> }[];
+}) => Promise<{ createWritable: () => Promise<WritableStream> }>;
+
+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<string, string> = {
+ ".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) : "";
+}
+
+export function LocalClipPanel() {
+ const { data, clipStart, clipEnd, localFile, getLocalFile } = usePlayer();
+ const job = useSyncExternalStore(subscribeLocalClip, getLocalClipState, getIdleLocalClipState);
+ const [open, setOpen] = useState(false);
+ const triggerRef = useRef<HTMLSpanElement | null>(null);
+ const groupRef = useRef<HTMLDivElement | null>(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.
+ 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" || ("key" in st && st.key === key)) 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.
+ const savingNow = job.phase === "saving";
+ useEffect(() => {
+ if (savingNow) groupRef.current?.querySelector<HTMLButtonElement>('[data-clip-action="cancel"]')?.focus();
+ }, [savingNow]);
+
+ const close = () => {
+ resetLocalClip();
+ setOpen(false);
+ requestAnimationFrame(() => triggerRef.current?.querySelector("button")?.focus());
+ };
+
+ const save = async (st: Extract<ClipJobState, { phase: "ready" }>) => {
+ if (st.path === "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 (
+ <>
+ <span ref={triggerRef} className="contents">
+ <ControlButton
+ title={canClip ? CLIP_BUTTON : CLIP_BUTTON_OFF}
+ label="Clip my copy"
+ icon={<ScissorsIcon className="size-4" />}
+ disabled={!canClip}
+ highlight={shown}
+ aria-expanded={shown}
+ onClick={() => (shown ? close() : setOpen(true))}
+ />
+ </span>
+ {shown && (
+ <div
+ ref={groupRef}
+ role="group"
+ aria-label="Clip of your copy"
+ data-testid="local-clip"
+ className="basis-full flex flex-col gap-1.5 rounded-md bg-black/30 p-2"
+ >
+ <ClipBody job={job} canClip={canClip} onSave={save} onClose={close} />
+ <p className="text-[11px] text-zinc-400">
+ Clipping uses Mediabunny {LIBRARY_VERSION} (MPL-2.0):{" "}
+ <a
+ href="https://mozilla.org/MPL/2.0/"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-2 hover:text-white"
+ >
+ licence
+ </a>{" "}
+ ·{" "}
+ <a
+ href="https://github.com/Vanilagy/mediabunny"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-2 hover:text-white"
+ >
+ source
+ </a>
+ </p>
+ </div>
+ )}
+ </>
+ );
+}
+
+function Actions({ children }: { children: React.ReactNode }) {
+ return <div className="flex flex-wrap items-center gap-2">{children}</div>;
+}
+
+function ClipBody({
+ job,
+ canClip,
+ onSave,
+ onClose,
+}: {
+ job: ClipJobState;
+ canClip: boolean;
+ onSave: (st: Extract<ClipJobState, { phase: "ready" }>) => void;
+ onClose: () => void;
+}) {
+ const closeButton = <ControlButton title="Close the clip" label="Close" icon={<span aria-hidden="true" className="hidden" />} onClick={onClose} />;
+ if (!canClip && job.phase !== "saving") {
+ return (
+ <>
+ <p aria-live="polite">Mark Clip in and Clip out first.</p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ }
+ switch (job.phase) {
+ case "idle":
+ case "preparing":
+ return (
+ <>
+ <p role="status" aria-live="polite">Finding the keyframe…</p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ case "refused":
+ case "failed":
+ return (
+ <>
+ <p role="alert" data-testid="local-clip-refusal" className="text-rose-200">
+ {job.sentence}
+ </p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ case "ready":
+ return (
+ <>
+ <div aria-live="polite" data-testid="local-clip-ready" className="flex flex-col gap-0.5">
+ <p>{job.range}</p>
+ <p data-testid="local-clip-start" className="text-amber-200">
+ {job.start}
+ </p>
+ <p>
+ About {formatBytes(job.plan.estimate)} · saved as{" "}
+ <span data-testid="local-clip-name" className="font-mono text-white">
+ {job.name}
+ </span>
+ {job.path === "disk" ? " · you choose where it goes" : ""}
+ </p>
+ {job.plan.extraTracks && <p>Only the main video and audio are kept.</p>}
+ </div>
+ <Actions>
+ <ControlButton title="Save clip" label="Save clip" icon={<span aria-hidden="true" className="hidden" />} onClick={() => onSave(job)} />
+ {closeButton}
+ </Actions>
+ </>
+ );
+ case "saving": {
+ const pct = Math.floor(job.fraction * 100);
+ return (
+ <>
+ <p>
+ Saving <span className="font-mono text-white">{job.name}</span>
+ </p>
+ <div className="flex items-center gap-2">
+ <progress aria-label="Saving clip" max={1} value={job.fraction} className="w-40" />
+ <span data-testid="local-clip-progress" className="font-mono">
+ {pct} % · {formatClock(job.doneSeconds)} of {formatClock(job.totalSeconds)}
+ </span>
+ </div>
+ <Actions>
+ <ControlButton
+ title="Cancel the clip"
+ label="Cancel"
+ icon={<span aria-hidden="true" className="hidden" />}
+ data-clip-action="cancel"
+ onClick={cancelLocalClip}
+ />
+ </Actions>
+ </>
+ );
+ }
+ case "done":
+ return (
+ <>
+ <p role="status" data-testid="local-clip-done">
+ {job.path === "disk" ? (
+ <>
+ Saved <span className="font-mono text-white">{job.name}</span> ({formatBytes(job.bytes)}).
+ </>
+ ) : (
+ <>
+ Your browser is saving <span className="font-mono text-white">{job.name}</span> ({formatBytes(job.bytes)}).
+ </>
+ )}
+ </p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ case "cancelled":
+ return (
+ <>
+ <p role="status" data-testid="local-clip-cancelled">
+ {job.path === "disk"
+ ? "Cancelled; the clip was not written. Your browser may leave an empty file where you chose to save it."
+ : "Cancelled; nothing was saved."}
+ </p>
+ <Actions>{closeButton}</Actions>
+ </>
+ );
+ }
+}
diff --git a/common/components/LocalFileBar.tsx b/common/components/LocalFileBar.tsx
@@ -3,6 +3,7 @@
import { CrosshairIcon, SquareIcon } from "lucide-react";
import { ControlButton, usePlayer } from "./PlayerProvider";
import { LocalFilePicker } from "./LocalFilePicker";
+import { LocalClipPanel } from "./LocalClipPanel";
import { formatOffset } from "../lib/localFileClock";
// THE VISITOR'S OWN COPY, IN THE MODAL (lane missing-source, slice 2).
@@ -11,7 +12,8 @@ import { formatOffset } from "../lib/localFileClock";
// in the player slot's panel, so nothing shows here.)
// - A copy playing: its name, the offset, the four nudges, "This line is
// playing now" (the next cue click sets the offset) and Stop, which gives
-// the focus back to the "Play your own copy" control in its place.
+// the focus back to the "Play your own copy" control in its place; and
+// "Clip my copy" (LocalClipPanel), which cuts the marked clip from it.
//
// Nothing in this file may reach the network or storage (the offset is written
// by the provider through lib/localFileClock.ts); LocalFilePicker.test.ts
@@ -90,6 +92,8 @@ export function LocalFileBar() {
icon={<SquareIcon className="size-4" />}
onClick={stopLocalFile}
/>
+ {/* A clip of this copy, cut in the browser (lane browser-clip). */}
+ <LocalClipPanel />
{localSyncArmed && (
<p role="status" className="basis-full text-amber-200">
Click the line you hear now (Esc cancels).
diff --git a/common/components/LocalFilePicker.test.ts b/common/components/LocalFilePicker.test.ts
@@ -20,6 +20,12 @@ const FILES = [
"./LocalFileBar.tsx",
"../lib/localFileClock.ts",
"../lib/sourceMissing.ts",
+ // The in-browser clipper (lane browser-clip): its panel, its job, its pure
+ // part and the engine that drives the library.
+ "./LocalClipPanel.tsx",
+ "../lib/localClipJob.ts",
+ "../lib/localClip.ts",
+ "../lib/localClipEngine.ts",
];
const FORBIDDEN: ReadonlyArray<[string, RegExp]> = [
@@ -51,3 +57,30 @@ for (const rel of FILES) {
}
});
}
+
+// The clipper's one door: lib/localClipLoader.ts may hold a dynamic import,
+// and only of the engine — so the library loads when a clip is asked for and
+// nothing else rides in with it.
+test("../lib/localClipLoader.ts holds exactly one dynamic import, of the engine, and nothing else forbidden", () => {
+ const src = code(readFileSync(fileURLToPath(new URL("../lib/localClipLoader.ts", import.meta.url)), "utf8"));
+ const imports = src.match(/\bimport\s*\(([^)]*)\)/g) ?? [];
+ assert.deepEqual(imports, ['import("./localClipEngine")']);
+ for (const [name, re] of FORBIDDEN) {
+ if (name === "a dynamic import") continue;
+ assert.ok(!re.test(src), `localClipLoader.ts mentions ${name}`);
+ }
+ assert.ok(!/^\s*import\s/m.test(src), "localClipLoader.ts has a static import");
+});
+
+// The engine takes from the library only what a stream copy of a local Blob
+// needs: no URL, HLS or stream sources (the library's own network doors).
+test("../lib/localClipEngine.ts imports no network source from the library", () => {
+ const src = code(readFileSync(fileURLToPath(new URL("../lib/localClipEngine.ts", import.meta.url)), "utf8"));
+ const m = src.match(/import\s*\{([^}]*)\}\s*from\s*"mediabunny"/);
+ assert.ok(m, "the engine imports from mediabunny");
+ const names = m![1].split(",").map((s) => s.trim().replace(/^type\s+/, "")).filter(Boolean);
+ for (const bad of ["UrlSource", "StreamSource", "ReadableStreamSource", "HLS", "HLS_FORMATS", "ALL_FORMATS", "FilePathSource", "FilePathTarget"]) {
+ assert.ok(!names.includes(bad), `the engine imports ${bad}`);
+ }
+ assert.ok(names.includes("BlobSource"));
+});
diff --git a/common/components/PlayerProvider.tsx b/common/components/PlayerProvider.tsx
@@ -54,6 +54,7 @@ import {
toFileTime,
writeOffset,
} from "../lib/localFileClock";
+import { resetLocalClip } from "../lib/localClipJob";
const ReactPlayer = dynamic(() => import("react-player/youtube"), {
ssr: false,
@@ -244,6 +245,9 @@ type PlayerState = {
localSyncArmed: boolean;
openLocalFile: (file: File) => void;
clearLocalFile: () => void;
+ // The picked File itself, for the in-browser clipper (lane browser-clip),
+ // while its copy is active for this video; null otherwise. Never state.
+ getLocalFile: () => File | null;
// "Stop": clear the copy and give focus back to the "Play your own copy"
// control that takes its place (takeLocalPickerFocus, read once by it).
stopLocalFile: () => void;
@@ -559,9 +563,11 @@ export function PlayerProvider({
const pendingSeekRef = useRef<number | null>(null);
const currentTimeRef = useRef(0);
currentTimeRef.current = currentTime;
- // The visitor's own copy (slice 2). The File itself is never kept: only its
- // object URL (revoked when it is replaced, cleared, the video changes or the
- // provider unmounts) and its name, shown on screen and nowhere else.
+ // The visitor's own copy (slice 2). Its object URL (revoked when it is
+ // replaced, cleared, the video changes or the provider unmounts) and its
+ // name, shown on screen and nowhere else. The File itself is held in a ref
+ // for exactly as long as its URL, for the clipper (lane browser-clip), and
+ // is never put in state.
const [local, setLocal] = useState<{ slug: string; url: string; name: string } | null>(null);
const [localOffset, setLocalOffset] = useState(0);
const [localError, setLocalError] = useState(false);
@@ -571,6 +577,7 @@ export function PlayerProvider({
// The file element's own time, as its last progress event said.
const localRawRef = useRef(0);
const localUrlRef = useRef<string | null>(null);
+ const localFileRef = useRef<File | null>(null);
const readyForSlugRef = useRef<string | null>(null);
// The YouTube embed said it cannot play this video (removed, private,
// embedding off). Its progress events are then the dead player's 0, never
@@ -854,6 +861,9 @@ export function PlayerProvider({
const revokeLocalUrl = useCallback(() => {
if (localUrlRef.current) URL.revokeObjectURL(localUrlRef.current);
localUrlRef.current = null;
+ localFileRef.current = null;
+ // A clip of that copy, prepared or being made, goes with it.
+ resetLocalClip();
}, []);
const openLocalFile = useCallback(
@@ -862,6 +872,7 @@ export function PlayerProvider({
revokeLocalUrl();
const url = URL.createObjectURL(file);
localUrlRef.current = url;
+ localFileRef.current = file;
localRawRef.current = 0;
setLocalError(false);
setLocalSyncArmed(false);
@@ -919,6 +930,11 @@ export function PlayerProvider({
const armLocalSync = useCallback((on: boolean) => setLocalSyncArmed(on), []);
+ const getLocalFile = useCallback(
+ () => (localActive ? localFileRef.current : null),
+ [localActive],
+ );
+
// Another video, or none: the copy belonged to the one it was picked on.
useEffect(() => {
if (local && local.slug !== activeSlug) clearLocalFile();
@@ -1233,6 +1249,7 @@ export function PlayerProvider({
localSyncArmed: localActive && localSyncArmed,
openLocalFile,
clearLocalFile,
+ getLocalFile,
stopLocalFile,
takeLocalPickerFocus,
nudgeLocalOffset,
@@ -1274,6 +1291,7 @@ export function PlayerProvider({
localSyncArmed,
openLocalFile,
clearLocalFile,
+ getLocalFile,
stopLocalFile,
takeLocalPickerFocus,
nudgeLocalOffset,
diff --git a/common/lib/localClipJob.ts b/common/lib/localClipJob.ts
@@ -0,0 +1,210 @@
+// THE ONE CLIP JOB OF THE VISITOR'S OWN COPY (lane browser-clip).
+//
+// A module store, not component state: Esc collapses the modal to the
+// mini-player and unmounts the clip panel, and that must not cancel a clip
+// being made. Clearing the copy, picking another or changing the video does
+// (the provider calls resetLocalClip).
+//
+// The engine (and with it the library) is loaded through localClipLoader's
+// dynamic import on the first prepare — never before a clip is asked for.
+// A clip built in memory becomes a Blob only once the copy is complete, and is
+// handed over as a download from an object URL; nothing here reaches the
+// network or any storage (components/LocalFilePicker.test.ts reads this source).
+
+import type { ClipPlan, SaveTarget } from "./localClipEngine";
+import { loadClipEngine } from "./localClipLoader";
+import {
+ clipFileName,
+ rangeSentence,
+ refusalSentence,
+ savePath,
+ startSentence,
+} from "./localClip";
+
+export type ClipRequest = {
+ file: File;
+ cueIn: number;
+ cueOut: number;
+ offset: number;
+ title: string;
+ slug: string;
+ canSaveToDisk: boolean;
+};
+
+type Prepared = {
+ plan: ClipPlan;
+ name: string;
+ path: "memory" | "disk";
+ range: string;
+ start: string;
+};
+
+export type ClipJobState =
+ | { phase: "idle" }
+ | { phase: "preparing"; key: string }
+ | ({ phase: "ready"; key: string } & Prepared)
+ | { phase: "refused"; key: string; sentence: string }
+ | ({ phase: "saving"; key: string; fraction: number; doneSeconds: number; totalSeconds: number } & Prepared)
+ | { phase: "done"; key: string; name: string; bytes: number; path: "memory" | "disk" }
+ | { phase: "cancelled"; key: string; path: "memory" | "disk" }
+ | { phase: "failed"; key: string; sentence: string };
+
+const IDLE: ClipJobState = { phase: "idle" };
+// How long a finished in-memory clip's object URL stays alive for the download.
+const DOWNLOAD_URL_LIFETIME_MS = 60_000;
+
+type Engine = Awaited<ReturnType<typeof loadClipEngine>>;
+
+let state: ClipJobState = IDLE;
+let engine: Engine | null = null;
+let current: ClipRequest | null = null;
+let token = 0;
+let saving: AbortController | null = null;
+let downloadUrl: string | null = null;
+let downloadTimer: ReturnType<typeof setTimeout> | null = null;
+const listeners = new Set<() => void>();
+const fileIds = new WeakMap<File, number>();
+let nextFileId = 1;
+
+function set(next: ClipJobState) {
+ state = next;
+ for (const l of listeners) l();
+}
+
+export function subscribeLocalClip(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+export function getLocalClipState(): ClipJobState {
+ return state;
+}
+
+export function getIdleLocalClipState(): ClipJobState {
+ return IDLE;
+}
+
+// What a prepared clip depends on: the file, the marks, the offset.
+export function clipKey(req: Pick<ClipRequest, "file" | "cueIn" | "cueOut" | "offset">): string {
+ let id = fileIds.get(req.file);
+ if (id === undefined) {
+ id = nextFileId++;
+ fileIds.set(req.file, id);
+ }
+ return `${id}|${req.cueIn}|${req.cueOut}|${req.offset}`;
+}
+
+function revokeDownload() {
+ if (downloadTimer !== null) clearTimeout(downloadTimer);
+ downloadTimer = null;
+ if (downloadUrl) URL.revokeObjectURL(downloadUrl);
+ downloadUrl = null;
+}
+
+// Probe the file for these marks: where the clip really starts, its name and
+// how it will be saved — or the sentence that says why it cannot be.
+export async function prepareLocalClip(req: ClipRequest): Promise<void> {
+ if (state.phase === "saving") return;
+ const key = clipKey(req);
+ const mine = ++token;
+ current = req;
+ set({ phase: "preparing", key });
+ try {
+ engine ??= await loadClipEngine();
+ const probe = await engine.probeClip(req.file, req.cueIn, req.cueOut, req.offset);
+ if (mine !== token) return;
+ if (!probe.ok) {
+ set({ phase: "refused", key, sentence: refusalSentence(probe.refusal) });
+ return;
+ }
+ const { plan } = probe;
+ const path = savePath(plan.estimate, req.canSaveToDisk);
+ if (path === "too-big") {
+ set({ phase: "refused", key, sentence: refusalSentence({ kind: "too-big", bytes: plan.estimate }) });
+ return;
+ }
+ const realStartCue = plan.startTs - req.offset;
+ const endCue = plan.fileOut - req.offset;
+ set({
+ phase: "ready",
+ key,
+ plan,
+ path,
+ name: clipFileName(req.title, req.slug, realStartCue, endCue, plan.ext),
+ range: rangeSentence(req.cueIn, req.cueOut, req.offset),
+ start: startSentence(plan.fileIn, plan.startTs, req.offset),
+ });
+ } catch {
+ if (mine !== token) return;
+ set({ phase: "refused", key, sentence: refusalSentence({ kind: "copy" }) });
+ }
+}
+
+function startDownload(blob: Blob, name: string) {
+ revokeDownload();
+ downloadUrl = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = downloadUrl;
+ a.download = name;
+ a.rel = "noopener";
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ downloadTimer = setTimeout(revokeDownload, DOWNLOAD_URL_LIFETIME_MS);
+}
+
+// Make the prepared clip. `target` is memory (a download when it is done) or
+// a file the visitor has just picked to write to.
+export async function saveLocalClip(target: SaveTarget): Promise<void> {
+ if (state.phase !== "ready" || !current) return;
+ const prepared = state;
+ const req = current;
+ const mine = ++token;
+ const ac = new AbortController();
+ saving = ac;
+ const { phase: _phase, ...rest } = prepared;
+ void _phase;
+ set({ ...rest, phase: "saving", fraction: 0, doneSeconds: 0, totalSeconds: prepared.plan.fileOut - prepared.plan.startTs });
+ try {
+ const eng = (engine ??= await loadClipEngine());
+ try {
+ const result = await eng.saveClip(
+ req.file,
+ prepared.plan,
+ target,
+ (p) => {
+ if (mine !== token || state.phase !== "saving") return;
+ set({ ...state, fraction: p.fraction, doneSeconds: p.doneSeconds, totalSeconds: p.totalSeconds });
+ },
+ ac.signal,
+ );
+ if (mine !== token) return;
+ if (result.blob) startDownload(result.blob, prepared.name);
+ set({ phase: "done", key: prepared.key, name: prepared.name, bytes: result.bytes, path: prepared.path });
+ } catch (e) {
+ if (mine !== token) return;
+ if (e instanceof eng.ClipCancelled) set({ phase: "cancelled", key: prepared.key, path: prepared.path });
+ else set({ phase: "failed", key: prepared.key, sentence: refusalSentence(eng.saveFailure(e)) });
+ }
+ } finally {
+ if (saving === ac) saving = null;
+ }
+}
+
+// Stop a clip being made. Nothing is handed over as finished: an in-memory
+// clip never becomes a Blob, a disk writer is aborted, not closed.
+export function cancelLocalClip(): void {
+ saving?.abort();
+}
+
+// Forget the job entirely (the copy was cleared or replaced, the video changed,
+// the panel was closed): any clip being made is cancelled.
+export function resetLocalClip(): void {
+ token++;
+ saving?.abort();
+ saving = null;
+ if (engine && current) void engine.forgetClipInput(current.file);
+ current = null;
+ revokeDownload();
+ if (state.phase !== "idle") set(IDLE);
+}
diff --git a/common/lib/localClipLoader.ts b/common/lib/localClipLoader.ts
@@ -0,0 +1,8 @@
+// The ONE door to the clipper's engine (lane browser-clip): a dynamic import,
+// so the engine and the library it bundles are fetched only when a visitor
+// asks for a clip of their own copy, never on the site's first load.
+// components/LocalFilePicker.test.ts holds this file to exactly this import.
+
+export function loadClipEngine() {
+ return import("./localClipEngine");
+}