Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Drag, trim, delete and play back clips on the timeline

Bittif8f16519b626
diff --git a/src/components/ProjectWorkspace.test.ts b/src/components/ProjectWorkspace.test.ts
index 7ed57fb..a51a3a6 100644
--- a/src/components/ProjectWorkspace.test.ts
+++ b/src/components/ProjectWorkspace.test.ts
@@ -215,6 +215,12 @@ describe("project workspace timecode", () => {
};
}
+ /** What a view actually wrote. The timeline hands up UPDATERS rather than
+ * finished configs (see ConfigUpdate), so reading a call means applying it
+ * to the config the view was holding at the time. */
+ const wrote = (call: unknown, current: ProjectConfig): ProjectConfig =>
+ typeof call === "function" ? (call as (value: ProjectConfig) => ProjectConfig)(current) : call as ProjectConfig;
+
/** A project carrying one importable clip of each kind, so the media panel
* has a card that belongs on a video track and one that belongs on audio. */
function projectWithMedia(): ProjectConfig {
@@ -269,7 +275,7 @@ describe("project workspace timecode", () => {
fireEvent.dragOver(videoLane, { dataTransfer });
fireEvent.drop(videoLane, { dataTransfer });
- const next = onChange.mock.calls[0][0] as ProjectConfig;
+ const next = wrote(onChange.mock.calls[0][0], config);
const track = next.timeline.tracks.find((item) => item.kind === "video")!;
const dropped = track.clips.find((clip) => clip.assetId === video.id)!;
expect(dropped.label).toBe(video.name);
@@ -293,7 +299,7 @@ describe("project workspace timecode", () => {
expect(onChange).not.toHaveBeenCalled();
fireEvent.drop(laneFor(container, config, "audio"), { dataTransfer });
- const next = onChange.mock.calls[0][0] as ProjectConfig;
+ const next = wrote(onChange.mock.calls[0][0], config);
const audioTrack = next.timeline.tracks.find((track) => track.kind === "audio")!;
expect(audioTrack.clips.map((clip) => clip.assetId)).toEqual([sound.id]);
expect(next.timeline.tracks.filter((track) => track.kind === "video").every((track) => track.clips.length === 0)).toBe(true);
@@ -317,7 +323,7 @@ describe("project workspace timecode", () => {
Object.defineProperty(drop, "clientX", { value: 350 });
fireEvent(lane, drop);
- const next = onChange.mock.calls[0][0] as ProjectConfig;
+ const next = wrote(onChange.mock.calls[0][0], config);
const dropped = next.timeline.tracks.flatMap((track) => track.clips)[0];
// A quarter of the way along a 30-second canvas, not pinned to zero.
expect(dropped.startMs).toBe(Math.round(0.25 * 30_000));
@@ -362,8 +368,8 @@ describe("project workspace timecode", () => {
}] } : track) },
});
- const droppedClip = (calls: { mock: { calls: unknown[][] } }) =>
- ((calls.mock.calls[0][0] as ProjectConfig).timeline.tracks.flatMap((track) => track.clips))[0];
+ const droppedClip = (calls: { mock: { calls: unknown[][] } }, current: ProjectConfig) =>
+ wrote(calls.mock.calls[0][0], current).timeline.tracks.flatMap((track) => track.clips)[0];
it("drops a clip as long as the footage, and falls back to the stated default only when nothing measured it", () => {
/* B3: every dropped clip used to be five seconds, forever — a 40-second
@@ -373,8 +379,8 @@ describe("project workspace timecode", () => {
const transfer = fakeDataTransfer();
fireEvent.dragStart(cardFor(known.assets[0]), { dataTransfer: transfer });
fireEvent.drop(laneFor(first.container, known, "video"), { dataTransfer: transfer });
- expect(droppedClip(first.onChange).durationMs).toBe(40_000);
- expect(parseProjectConfig(first.onChange.mock.calls[0][0] as ProjectConfig)).toBeTruthy();
+ expect(droppedClip(first.onChange, known).durationMs).toBe(40_000);
+ expect(parseProjectConfig(wrote(first.onChange.mock.calls[0][0], known))).toBeTruthy();
cleanup();
// Nothing has decoded this one, so there is no length to honour and the
@@ -384,19 +390,29 @@ describe("project workspace timecode", () => {
const transferTwo = fakeDataTransfer();
fireEvent.dragStart(cardFor(unknown.assets[0]), { dataTransfer: transferTwo });
fireEvent.drop(laneFor(second.container, unknown, "video"), { dataTransfer: transferTwo });
- expect(droppedClip(second.onChange).durationMs).toBe(5_000);
+ expect(droppedClip(second.onChange, unknown).durationMs).toBe(5_000);
});
it("retimes the selected clip from the Lasts field, and will not run past the footage", () => {
const config = withClip(measuredVideo(projectWithMedia(), 40_000), {});
- const onChange = vi.fn();
- render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));
+ /* Every edit is fed back in, the way the holder does it in the app. It has
+ to be: a typed length is now a trim of the clip’s tail, and a trim is
+ measured against the clip AS IT STANDS — how much footage is left in the
+ file after it, what sits next to it on the track. A harness that
+ swallowed the writes would ask every keystroke about a clip that had
+ already been replaced. */
+ let current = config;
+ const onChange = vi.fn((next: ProjectConfig | ((value: ProjectConfig) => ProjectConfig)) => {
+ current = typeof next === "function" ? next(current) : next;
+ rerender(createElement(TimelineView, { config: current, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));
+ });
+ const { rerender } = render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));
const lasts = screen.getByTitle(/^How long this clip lasts/) as HTMLInputElement;
// It was readOnly, which made the only stated way to fix a clip's length a
// field that could not be typed into.
expect(lasts.readOnly).toBe(false);
expect(lasts.value).toBe("00:40:00");
- const lastDuration = () => (onChange.mock.calls.at(-1)![0] as ProjectConfig).timeline.tracks.flatMap((track) => track.clips)[0].durationMs;
+ const lastDuration = () => current.timeline.tracks.flatMap((track) => track.clips)[0].durationMs;
// Plain seconds, and the minutes:seconds:frames the field itself prints.
fireEvent.change(lasts, { target: { value: "8" } });
@@ -404,7 +420,7 @@ describe("project workspace timecode", () => {
fireEvent.change(lasts, { target: { value: "00:12:15" } });
// 15 frames at the project's 24 fps is 625 ms, not half a second.
expect(lastDuration()).toBe(12_625);
- expect(parseProjectConfig(onChange.mock.calls.at(-1)![0] as ProjectConfig)).toBeTruthy();
+ expect(parseProjectConfig(current)).toBeTruthy();
// Half-typed text is not a length, and must not be turned into one.
const before = onChange.mock.calls.length;
@@ -418,13 +434,202 @@ describe("project workspace timecode", () => {
expect(lastDuration()).toBe(42);
fireEvent.change(lasts, { target: { value: "90" } });
expect(lastDuration()).toBe(40_000);
- expect(parseProjectConfig(onChange.mock.calls.at(-1)![0] as ProjectConfig)).toBeTruthy();
+ expect(parseProjectConfig(current)).toBeTruthy();
// Off the field, the clip's own length is what it shows again.
fireEvent.blur(lasts);
expect(lasts.value).toBe("00:40:00");
});
+ /* --- Dragging clips on the timeline --------------------------------------
+
+ jsdom lays nothing out and has no PointerEvent, so both are supplied here:
+ the lane is told how wide it is (a drag turns pixels into milliseconds
+ against exactly this), and each gesture is a bubbling event carrying the
+ coordinates the handlers read. 1000px over a 30-second canvas makes the
+ arithmetic legible: 1px is 30ms, and the 8px magnet is 240ms.
+ ======================================================================= */
+
+ const LANE_WIDTH = 1000;
+ const LANE_RECT = { left: 0, width: LANE_WIDTH, top: 0, right: LANE_WIDTH, bottom: 72, height: 72, x: 0, y: 0, toJSON: () => ({}) } as DOMRect;
+
+ function pointerEvent(type: string, clientX: number, clientY = 40) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ for (const [key, value] of Object.entries({ clientX, clientY, button: 0, pointerId: 1 })) {
+ Object.defineProperty(event, key, { value });
+ }
+ return event;
+ }
+
+ /** A project with clips cut into one of its tracks. */
+ const withClips = (config: ProjectConfig, clips: Partial<TimelineClip>[], trackId = STORY_TRACK_ID) => parseProjectConfig({
+ ...config,
+ timeline: { tracks: config.timeline.tracks.map((track) => track.id === trackId ? { ...track, clips: clips.map((clip, index) => ({
+ id: `clip-${index}`, assetId: config.assets[0].id, trackId,
+ startMs: 0, durationMs: 4_000, sourceStartMs: 0, label: `Shot ${index + 1}`, color: null, status: "approved", ...clip,
+ })) } : track) },
+ });
+
+ /** Renders the timeline with every lane measured, and hands back what a drag
+ * needs: the lanes, the clips, and whatever was written. */
+ function timeline(config: ProjectConfig) {
+ const onChange = vi.fn();
+ const view = render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));
+ for (const lane of view.container.querySelectorAll(".track-lane")) lane.getBoundingClientRect = () => LANE_RECT;
+ const laneOf = (trackId: string) => view.container.querySelector(`[data-track-id="${trackId}"]`) as HTMLElement;
+ const written = () => onChange.mock.calls.length ? wrote(onChange.mock.calls.at(-1)![0], config) : undefined;
+ const clipsOn = (trackId: string) => written()?.timeline.tracks.find((track) => track.id === trackId)?.clips ?? [];
+ return { ...view, onChange, laneOf, written, clipsOn };
+ }
+
+ /** One whole gesture: press on `grip`, move to `toX`, release. */
+ function drag(grip: Element, fromX: number, toX: number, clientY = 40) {
+ fireEvent(grip, pointerEvent("pointerdown", fromX, clientY));
+ fireEvent(window, pointerEvent("pointermove", toX, clientY));
+ fireEvent(window, pointerEvent("pointerup", toX, clientY));
+ }
+
+ /** Which lane the pointer is over. jsdom cannot hit-test, so this is the one
+ * thing about a cross-lane drag a test has to supply. */
+ const overLane = (lane: HTMLElement) => {
+ (document as unknown as { elementsFromPoint: () => Element[] }).elementsFromPoint = () => [lane];
+ };
+ const stopHitTesting = () => { delete (document as unknown as { elementsFromPoint?: unknown }).elementsFromPoint; };
+
+ it("drags a clip along its own lane and writes where it landed", () => {
+ const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 2_000, durationMs: 4_000 }]);
+ const view = timeline(config);
+ // Taken hold of 1s into the clip and dropped 6s further along: the clip
+ // moves by what the POINTER moved, rather than jumping its head under it.
+ drag(view.container.querySelector(".timeline-clip")!, 100, 300);
+ expect(view.clipsOn(STORY_TRACK_ID)[0]).toMatchObject({ startMs: 8_000, durationMs: 4_000 });
+ expect(parseProjectConfig(view.written()!)).toBeTruthy();
+ });
+
+ it("drags a clip onto another video track, and onto no audio track", () => {
+ const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 0, durationMs: 4_000 }]);
+ const view = timeline(config);
+ overLane(view.laneOf("track-v2"));
+ drag(view.container.querySelector(".timeline-clip")!, 20, 220);
+ expect(view.clipsOn(STORY_TRACK_ID)).toHaveLength(0);
+ expect(view.clipsOn("track-v2")[0]).toMatchObject({ startMs: 6_000, trackId: "track-v2" });
+ expect(parseProjectConfig(view.written()!)).toBeTruthy();
+
+ // A picture held over a sound lane is refused outright: nothing is written,
+ // so the clip stays where it was rather than landing where it cannot play.
+ cleanup();
+ const second = timeline(config);
+ overLane(second.laneOf("track-a1"));
+ drag(second.container.querySelector(".timeline-clip")!, 20, 220);
+ expect(second.onChange).not.toHaveBeenCalled();
+ stopHitTesting();
+ });
+
+ it("moves sound from one sound track to another", () => {
+ const measured = parseProjectConfig({
+ ...projectWithMedia(),
+ assets: projectWithMedia().assets.map((asset) => asset.kind === "audio" ? { ...asset, durationMs: 20_000 } : asset),
+ });
+ const config = withClips(measured, [{ startMs: 0, durationMs: 6_000, assetId: "asset-room", label: "Room tone" }], "track-a1");
+ const view = timeline(config);
+ overLane(view.laneOf("track-a2"));
+ drag(view.container.querySelector(".timeline-clip")!, 10, 110);
+ expect(view.clipsOn("track-a1")).toHaveLength(0);
+ expect(view.clipsOn("track-a2")[0]).toMatchObject({ startMs: 3_000, trackId: "track-a2" });
+ stopHitTesting();
+ });
+
+ it("will not lay one clip over another", () => {
+ const config = withClips(measuredVideo(projectWithMedia(), 40_000), [
+ { startMs: 0, durationMs: 4_000 },
+ { startMs: 12_000, durationMs: 4_000 },
+ ]);
+ const view = timeline(config);
+ // Dragged from 12s back to 1s, right on top of the first clip: it lands
+ // flush against the side it was nearer to, and nothing overlaps.
+ drag(view.container.querySelectorAll(".timeline-clip")[1], 400, 33);
+ expect(view.clipsOn(STORY_TRACK_ID).map((clip) => [clip.startMs, clip.durationMs])).toEqual([[0, 4_000], [4_000, 4_000]]);
+ expect(parseProjectConfig(view.written()!)).toBeTruthy();
+ });
+
+ it("snaps a dragged clip to the cut beside it", () => {
+ const config = withClips(measuredVideo(projectWithMedia(), 40_000), [
+ { startMs: 0, durationMs: 4_000 },
+ { startMs: 20_000, durationMs: 4_000 },
+ ]);
+ const view = timeline(config);
+ /* Dropped with its head 150ms past the first clip's tail — inside the 240ms
+ magnet, so the gap closes completely rather than leaving a hole too small
+ to see and too real for the encoder to ignore. */
+ drag(view.container.querySelectorAll(".timeline-clip")[1], 667, 138);
+ expect(view.clipsOn(STORY_TRACK_ID)[1].startMs).toBe(4_000);
+ });
+
+ it("trims the tail by dragging the right edge, and never past the footage", () => {
+ const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 0, durationMs: 6_000, sourceStartMs: 1_000 }]);
+ const view = timeline(config);
+ drag(view.container.querySelector(".clip-handle--end")!, 200, 100);
+ // Only the length changes: the head of the clip and the point it starts
+ // inside the file are not what the right-hand edge is holding.
+ expect(view.clipsOn(STORY_TRACK_ID)[0]).toMatchObject({ startMs: 0, durationMs: 3_000, sourceStartMs: 1_000 });
+
+ // The file is 40s long and this clip starts 1s into it, so 39s is all the
+ // tail there is, however far the pointer goes.
+ cleanup();
+ const second = timeline(config);
+ drag(second.container.querySelector(".clip-handle--end")!, 200, 1_600);
+ expect(second.clipsOn(STORY_TRACK_ID)[0].durationMs).toBe(39_000);
+ });
+
+ it("trims the head by dragging the left edge, moving the cut and the source together", () => {
+ const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 4_000, durationMs: 6_000, sourceStartMs: 2_000 }]);
+ const view = timeline(config);
+ drag(view.container.querySelector(".clip-handle--start")!, 133, 250);
+ // Three and a half seconds later on the ruler is three and a half seconds
+ // later in the footage.
+ expect(view.clipsOn(STORY_TRACK_ID)[0]).toMatchObject({ startMs: 7_500, durationMs: 2_500, sourceStartMs: 5_500 });
+
+ // Pulled the other way it stops where the file's own head is: only 2s of
+ // footage exists before this clip's first frame.
+ cleanup();
+ const second = timeline(config);
+ drag(second.container.querySelector(".clip-handle--start")!, 133, 0);
+ expect(second.clipsOn(STORY_TRACK_ID)[0]).toMatchObject({ startMs: 2_000, durationMs: 8_000, sourceStartMs: 0 });
+ });
+
+ it("abandons a drag on Escape and writes nothing", () => {
+ const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 2_000, durationMs: 4_000 }]);
+ const view = timeline(config);
+ fireEvent(view.container.querySelector(".timeline-clip")!, pointerEvent("pointerdown", 100));
+ fireEvent(window, pointerEvent("pointermove", 400));
+ fireEvent.keyDown(window, { key: "Escape" });
+ fireEvent(window, pointerEvent("pointerup", 400));
+ expect(view.onChange).not.toHaveBeenCalled();
+ });
+
+ it("refuses to drag or trim anything on a locked track", () => {
+ const config = withClips(measuredVideo(projectWithMedia(), 40_000), [{ startMs: 2_000, durationMs: 4_000 }]);
+ const locked = parseProjectConfig({ ...config, timeline: { tracks: config.timeline.tracks.map((track) => track.id === STORY_TRACK_ID ? { ...track, locked: true } : track) } });
+ const view = timeline(locked);
+ drag(view.container.querySelector(".timeline-clip")!, 100, 400);
+ expect(view.onChange).not.toHaveBeenCalled();
+ // The handles are not merely inert, they are absent: a control that cannot
+ // do anything is worse than no control at all.
+ expect(view.container.querySelector(".clip-handle")).toBeNull();
+ expect(view.container.querySelector(".clip-delete")).toBeNull();
+ });
+
+ it("removes a clip from its track with the control on the clip itself", () => {
+ const config = withClips(measuredVideo(projectWithMedia(), 40_000), [
+ { startMs: 0, durationMs: 4_000, label: "Opening" },
+ { startMs: 8_000, durationMs: 4_000, label: "Closing" },
+ ]);
+ const view = timeline(config);
+ fireEvent.click(screen.getByRole("button", { name: "Delete Opening" }));
+ expect(view.clipsOn(STORY_TRACK_ID).map((clip) => clip.label)).toEqual(["Closing"]);
+ expect(parseProjectConfig(view.written()!)).toBeTruthy();
+ });
+
it("keeps a clip's place in the source when it is duplicated", () => {
// Otherwise every copy replays the head of the file, which is the same five
// seconds the original already showed.
@@ -432,7 +637,7 @@ describe("project workspace timecode", () => {
const onChange = vi.fn();
render(createElement(TimelineView, { config, folderPath: "C:\\Ceramic Lamp", onChange, onOpenGenerator: () => undefined }));
fireEvent.click(screen.getByRole("button", { name: "Duplicate" }));
- const next = onChange.mock.calls[0][0] as ProjectConfig;
+ const next = wrote(onChange.mock.calls[0][0], config);
const clips = next.timeline.tracks.flatMap((track) => track.clips);
expect(clips).toHaveLength(2);
const copy = clips.find((clip) => clip.id !== "clip-macro")!;
diff --git a/src/components/workspace/ProgramMonitor.test.tsx b/src/components/workspace/ProgramMonitor.test.tsx
new file mode 100644
index 0000000..03b0b72
--- /dev/null
+++ b/src/components/workspace/ProgramMonitor.test.tsx
@@ -0,0 +1,78 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createProjectConfig, parseProjectConfig, STORY_TRACK_ID, type ProjectConfig, type TimelineClip } from "../../lib/project";
+import { ProgramMonitor } from "./ProgramMonitor";
+
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+
+afterEach(() => {
+ cleanup();
+ delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;
+});
+
+/* jsdom decodes nothing: it has no media pipeline, so no test here can prove a
+ frame reached the screen. What it CAN prove is everything around the picture
+ — which clip the playhead is over, which file that clip's element is pointed
+ at, and what the monitor says when there is no picture to show. The decode
+ itself is the webview's, and the one thing PolStudio does not implement. */
+
+const clip = (over: Partial<TimelineClip> = {}): TimelineClip => ({
+ id: "clip-1", assetId: "asset-macro", trackId: STORY_TRACK_ID,
+ startMs: 2_000, durationMs: 4_000, sourceStartMs: 8_000,
+ label: "Macro footage", color: null, status: "approved", ...over,
+});
+
+const project = (clips: TimelineClip[]): ProjectConfig => {
+ const fresh = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });
+ return parseProjectConfig({
+ ...fresh,
+ assets: [{
+ id: "asset-macro", kind: "video", name: "Macro footage", sourcePath: "D:/rushes/macro.mp4",
+ mimeType: "video/mp4", durationMs: 40_000, width: 1920, height: 1080, createdAt: fresh.createdAt,
+ }],
+ timeline: { tracks: fresh.timeline.tracks.map((track) => track.id === STORY_TRACK_ID ? { ...track, clips } : track) },
+ });
+};
+
+const monitor = (config: ProjectConfig, playheadMs: number) => render(
+ <ProgramMonitor
+ config={config}
+ folderPath="C:\\Ceramic Lamp"
+ playheadMs={playheadMs}
+ playing={false}
+ onSeek={() => undefined}
+ onPlayingChange={() => undefined}
+ />,
+);
+
+describe("the program monitor", () => {
+ it("says a gap is a gap rather than showing the last shot it played", () => {
+ monitor(project([clip()]), 9_000);
+ expect(screen.getByText("Nothing under the playhead here.")).toBeTruthy();
+ expect(document.querySelector("video")).toBeNull();
+ });
+
+ it("is honest that the browser preview cannot read the project's footage", () => {
+ // The clip IS under the playhead here; what is missing is the desktop shell
+ // that reads files, and saying so beats a black rectangle.
+ monitor(project([clip()]), 3_000);
+ expect(screen.getByText(/Playback needs the desktop app/)).toBeTruthy();
+ });
+
+ it("waits for the file rather than claiming a picture it has not got", () => {
+ // With a Tauri shell present the read is attempted; the mocked invoke never
+ // resolves to bytes, so the monitor stays on "loading" instead of showing
+ // an empty frame as though that were the shot.
+ (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__ = {};
+ monitor(project([clip()]), 3_000);
+ expect(screen.getByText(/Loading Macro footage/)).toBeTruthy();
+ });
+
+ it("shows nothing at all over an empty timeline", () => {
+ const { container } = monitor(project([]), 0);
+ expect(container.querySelector(".program-note")).toBeNull();
+ expect(container.querySelector(".program-picture")).not.toBeNull();
+ });
+});
diff --git a/src/components/workspace/ProgramMonitor.tsx b/src/components/workspace/ProgramMonitor.tsx
new file mode 100644
index 0000000..7ff8bbd
--- /dev/null
+++ b/src/components/workspace/ProgramMonitor.tsx
@@ -0,0 +1,333 @@
+import { Film, TriangleAlert } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { visibleClipAt } from "../../lib/export";
+import { isTauri } from "../../lib/persistence";
+import type { ProjectAsset, ProjectConfig, TimelineClip } from "../../lib/project";
+import { clipEndMs } from "../../lib/timeline";
+import { PreviewSources } from "../../lib/exportPipeline";
+
+/* The picture, played back.
+ *
+ * PolStudio has no player of its own and does not need one: the webview owns a
+ * hardware decoder, and a <video> pointed at the right file at the right offset
+ * IS the shot. What this component adds is the part a media element cannot do —
+ * being a TIMELINE rather than a file:
+ *
+ * * The clip under the playhead decides what is on screen, and crossing a cut
+ * re-points the same element at the next file.
+ * * Timeline time and source time are different numbers. A clip trimmed to
+ * start 8s into a rush shows second 8 of the file at second 0 of the cut.
+ * * Sound on the audio tracks plays alongside, each clip in its own element,
+ * corrected back into step whenever it drifts.
+ *
+ * While playing, the VIDEO element is the clock: the playhead is derived from
+ * where the decoder actually is, not from a timer running beside it, so the
+ * picture and the playhead cannot disagree. Over a gap — or with nothing
+ * readable — a wall clock takes over, because a black stretch still has to
+ * play through.
+ *
+ * The whole file is read into a blob, as everywhere else in PolStudio (see
+ * MediaThumbnail): the project's media lives outside the webview's reach and
+ * comes back through Tauri. Blobs are cached per asset for the life of the
+ * view, so scrubbing back and forth across a cut re-reads nothing. */
+
+/** How far a sound may drift from the cut before it is pulled back. Below this
+ * a correction is more audible than the drift it fixes. */
+const AUDIO_DRIFT_LIMIT_S = 0.25;
+/** Seeks below this are not worth the stutter — a paused element is already
+ * showing that frame. Roughly one frame at 30fps. */
+const SEEK_EPSILON_S = 0.033;
+/** How far outside a clip's own stretch of its file the decoder may read and
+ * still be believed. A frame or two of slack, so ordinary rounding at a cut
+ * does not hand the clock to the wall. */
+const CUT_SLACK_MS = 120;
+
+const isImage = (asset: ProjectAsset) => asset.mimeType.startsWith("image/") || asset.kind === "image";
+
+/** Where inside the FILE this moment of the timeline lives. */
+const sourceTimeMs = (clip: TimelineClip, timelineMs: number) => clip.sourceStartMs + (timelineMs - clip.startMs);
+
+const describe = (reason: unknown) => (reason instanceof Error ? reason.message : String(reason));
+
+/** Set an element's play position without fighting a seek already in flight.
+ * A scrub fires dozens of these a second; a media element that is asked to
+ * seek while seeking drops requests, so the latest target is remembered and
+ * applied when the current one lands. */
+function seekTo(element: HTMLMediaElement, seconds: number, pending: { current: number | null }) {
+ if (!Number.isFinite(seconds)) return;
+ const target = Math.max(0, seconds);
+ if (element.readyState === 0) {
+ pending.current = target;
+ return;
+ }
+ if (element.seeking) {
+ pending.current = target;
+ return;
+ }
+ if (Math.abs(element.currentTime - target) < SEEK_EPSILON_S) return;
+ element.currentTime = target;
+}
+
+export function ProgramMonitor({ config, folderPath, playheadMs, playing, onSeek, onPlayingChange }: {
+ config: ProjectConfig;
+ folderPath: string;
+ playheadMs: number;
+ playing: boolean;
+ /** Where playback has reached. The view owns the playhead; this only ever
+ * reports where the decoder actually is. */
+ onSeek: (ms: number) => void;
+ onPlayingChange: (playing: boolean) => void;
+}) {
+ const tracks = config.timeline.tracks;
+ const clip = useMemo(() => visibleClipAt(tracks, playheadMs), [tracks, playheadMs]);
+ const asset = useMemo(
+ () => (clip ? config.assets.find((candidate) => candidate.id === clip.assetId) : undefined),
+ [clip, config.assets],
+ );
+ /* Sound that should be audible at this moment: every audio clip the playhead
+ is inside, minus the tracks the user has muted. A muted track is dropped
+ here rather than played silently, so nothing is decoded for it at all. */
+ const audioClips = useMemo(() => tracks
+ .filter((track) => track.kind === "audio" && !track.muted)
+ .flatMap((track) => track.clips)
+ .filter((candidate) => playheadMs >= candidate.startMs && playheadMs < clipEndMs(candidate)),
+ [tracks, playheadMs]);
+ const videoTrackMuted = useMemo(
+ () => tracks.find((track) => track.id === clip?.trackId)?.muted ?? false,
+ [tracks, clip],
+ );
+
+ /** Where the picture ends. Playback stops there rather than running the clock
+ * over a timeline that has nothing left on it. */
+ const contentEndMs = useMemo(
+ () => tracks.reduce((end, track) => track.clips.reduce((furthest, item) => Math.max(furthest, clipEndMs(item)), end), 0),
+ [tracks],
+ );
+
+ const videoRef = useRef<HTMLVideoElement>(null);
+ const audioRefs = useRef(new Map<string, HTMLAudioElement>());
+ const pendingVideoSeek = useRef<number | null>(null);
+ /* The last playhead value THIS component produced. Anything else arriving in
+ the prop came from outside — the ruler, the scroll wheel, a scene card —
+ and has to be seeked to even mid-playback. Without this the monitor cannot
+ tell its own echo from a scrub. */
+ const advancedTo = useRef<number | null>(null);
+ const [url, setUrl] = useState<string | null>(null);
+ const [audioUrls, setAudioUrls] = useState<Record<string, string>>({});
+ const [error, setError] = useState<string | null>(null);
+ const [ready, setReady] = useState(false);
+
+ /* One blob per asset, held for the life of this view so that scrubbing back
+ and forth across a cut re-reads nothing. The cost is real and worth stating:
+ a blob is the WHOLE file, so a timeline built from four 300 MB rushes holds
+ 1.2 GB once all four have been under the playhead. Everything else in
+ PolStudio that shows footage does the same (MediaThumbnail, the export
+ preview) because project media lives outside the webview and arrives
+ through Tauri as bytes. The cleanup revokes every URL handed out, so
+ leaving the timeline — or opening another project — gives all of it back. */
+ const sources = useMemo(() => new PreviewSources(folderPath), [folderPath]);
+ useEffect(() => () => sources.dispose(), [sources]);
+
+ /* The playhead as of this render, readable from inside the animation frame
+ without making the clock restart every time it ticks. */
+ const positionRef = useRef(playheadMs);
+ positionRef.current = playheadMs;
+
+ const report = useCallback((ms: number) => {
+ const rounded = Math.round(ms);
+ advancedTo.current = rounded;
+ onSeek(rounded);
+ }, [onSeek]);
+
+ // The picture's file. Nothing is read for a clip the playhead is not inside.
+ useEffect(() => {
+ if (!asset) {
+ setUrl(null);
+ setReady(false);
+ return;
+ }
+ let live = true;
+ setError(null);
+ setReady(false);
+ void sources.url(asset).then(
+ (value) => { if (live) setUrl(value); },
+ (reason) => { if (live) { setUrl(null); setError(describe(reason)); } },
+ );
+ return () => { live = false; };
+ }, [asset, sources]);
+
+ // The sound files. Each audio clip under the playhead gets its own element,
+ // so two tracks can be heard at once rather than one winning.
+ const askedFor = useRef(new Set<string>());
+ useEffect(() => {
+ for (const audioClip of audioClips) {
+ const audioAsset = config.assets.find((candidate) => candidate.id === audioClip.assetId);
+ // This effect re-runs on every frame of playback (the set of audible
+ // clips is recomputed from the playhead), so the guard is what keeps one
+ // sound from being asked for sixty times a second while it loads.
+ if (!audioAsset || askedFor.current.has(audioAsset.id)) continue;
+ askedFor.current.add(audioAsset.id);
+ void sources.url(audioAsset).then(
+ (value) => setAudioUrls((current) => ({ ...current, [audioAsset.id]: value })),
+ // A sound that cannot be read is not worth blanking the picture over;
+ // the monitor says so only when the PICTURE fails.
+ () => undefined,
+ );
+ }
+ }, [audioClips, config.assets, sources]);
+
+ /* Scrubbing, every other jump, and the first frame of every new shot.
+ While playing this deliberately does nothing for the playhead's own
+ advance — the element is the clock then, and seeking it to its own reading
+ would stutter every frame. It does have to fire on the two other cases:
+ a playhead that moved for some other reason (the ruler, the wheel, a scene
+ card), and a CUT. Crossing a cut re-points the element at another file, or
+ at another moment of the same file, and neither knows where in the footage
+ this clip begins until it is told. */
+ const playingClipId = useRef<string | null>(null);
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video || !clip || !url) return;
+ const crossedACut = playingClipId.current !== clip.id;
+ playingClipId.current = clip.id;
+ const external = advancedTo.current === null || Math.abs(advancedTo.current - playheadMs) > 1;
+ if (playing && !external && !crossedACut) return;
+ seekTo(video, sourceTimeMs(clip, playheadMs) / 1000, pendingVideoSeek);
+ }, [playheadMs, playing, clip, url]);
+
+ // A seek that lands while another was queued: apply the newest target.
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) return;
+ const flush = () => {
+ const target = pendingVideoSeek.current;
+ if (target === null) return;
+ pendingVideoSeek.current = null;
+ seekTo(video, target, pendingVideoSeek);
+ };
+ video.addEventListener("seeked", flush);
+ video.addEventListener("loadeddata", flush);
+ return () => {
+ video.removeEventListener("seeked", flush);
+ video.removeEventListener("loadeddata", flush);
+ };
+ }, [url]);
+
+ /* Play and pause the picture. A media element that is asked to play before it
+ has data rejects, which is a promise nobody was awaiting — caught here so a
+ slow file does not throw into the console on every press. */
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) return;
+ if (playing && url) void video.play().catch(() => undefined);
+ else video.pause();
+ }, [playing, url, clip?.id]);
+
+ /* The clock. One frame at a time: read where the decoder is, turn that back
+ into a position on the ruler, and hand it up. With no picture to read —
+ a gap, an unreadable file, a still image — the wall clock stands in, so a
+ black stretch still plays through at the right speed. */
+ useEffect(() => {
+ if (!playing) return;
+ let frame = 0;
+ let lastTick = performance.now();
+ const step = () => {
+ const now = performance.now();
+ const elapsed = now - lastTick;
+ lastTick = now;
+ const video = videoRef.current;
+ /* The decoder is only the clock while it is actually inside THIS clip's
+ stretch of the file. Just after a cut it is not: the element has been
+ re-pointed and its currentTime still reads 0 (or the last shot's
+ position) until the seek lands. Believing it there would put the
+ playhead before the clip that is on screen, which hands the render back
+ to the previous clip and bounces between the two. The wall clock covers
+ those few frames instead. */
+ const sourceNowMs = video ? video.currentTime * 1000 : 0;
+ const insideThisClip = clip !== null
+ && sourceNowMs >= clip.sourceStartMs - CUT_SLACK_MS
+ && sourceNowMs <= clip.sourceStartMs + clip.durationMs + CUT_SLACK_MS;
+ const decoded = clip && video && url && !video.paused && !video.seeking && Number.isFinite(video.currentTime) && insideThisClip
+ ? clip.startMs + (sourceNowMs - clip.sourceStartMs)
+ : null;
+ const next = decoded ?? positionRef.current + elapsed;
+ // Past the end of everything there is nothing left to show, so playback
+ // stops there instead of running the clock over an empty ruler.
+ if (next >= contentEndMs) {
+ report(contentEndMs);
+ onPlayingChange(false);
+ return;
+ }
+ /* Past the end of THIS clip while its file still has footage left: the
+ cut is what ends the shot, not the file. Stepping just past the tail
+ hands the next clip — or the gap after it — to the next render. */
+ if (clip && next >= clipEndMs(clip)) report(clipEndMs(clip));
+ else report(next);
+ frame = requestAnimationFrame(step);
+ };
+ frame = requestAnimationFrame(step);
+ return () => cancelAnimationFrame(frame);
+ }, [playing, clip, url, contentEndMs, report, onPlayingChange]);
+
+ /* Sound, kept in step with the cut. Each element is put where the playhead
+ says it should be, and corrected only once it has drifted audibly — a
+ correction on every frame would be a stutter rather than a soundtrack. */
+ useEffect(() => {
+ for (const audioClip of audioClips) {
+ const element = audioRefs.current.get(audioClip.id);
+ if (!element || element.readyState === 0) continue;
+ const target = sourceTimeMs(audioClip, playheadMs) / 1000;
+ if (Math.abs(element.currentTime - target) > (playing ? AUDIO_DRIFT_LIMIT_S : SEEK_EPSILON_S)) {
+ element.currentTime = Math.max(0, target);
+ }
+ if (playing) void element.play().catch(() => undefined);
+ else element.pause();
+ }
+ }, [audioClips, playheadMs, playing]);
+
+ const hasClips = tracks.some((track) => track.clips.length > 0);
+
+ /* What the monitor can say, in the order the user needs it: nothing cut yet,
+ nothing under the playhead, no way to read the file, or the picture. */
+ let overlay: React.ReactNode = null;
+ if (!hasClips) overlay = null;
+ else if (!clip) overlay = <div className="program-note"><Film size={22} /><span>Nothing under the playhead here.</span></div>;
+ else if (!isTauri()) {
+ overlay = <div className="program-note"><Film size={22} /><span>Playback needs the desktop app — the browser preview has no project folder to read the footage from.</span></div>;
+ } else if (error) {
+ overlay = <div className="program-note program-note--error" role="alert"><TriangleAlert size={22} /><span>{clip.label} could not be played: {error}</span></div>;
+ } else if (!url || (!ready && asset && !isImage(asset))) {
+ overlay = <div className="program-note"><span>Loading {clip.label}…</span></div>;
+ }
+
+ /* The frame is fitted inside the panel and the rest is the project's own
+ background colour — the same letterboxing, against the same colour, that
+ the export writes into the file. Nothing is cropped to fill the panel: a
+ 9:16 cut has to LOOK 9:16 while it is being cut. */
+ return <div className="program-picture" style={{ backgroundColor: config.settings.backgroundColor }}>
+ {/* One element, re-pointed at whatever the playhead is over. Rebuilding it
+ per clip would drop the decoder and re-open the file on every cut. */}
+ {asset && !isImage(asset) && url && <video
+ ref={videoRef}
+ src={url}
+ muted={videoTrackMuted}
+ playsInline
+ preload="auto"
+ onLoadedData={() => setReady(true)}
+ onError={() => setError("This file could not be decoded.")}
+ />}
+ {asset && isImage(asset) && url && <img src={url} alt={clip?.label ?? ""} />}
+ {audioClips.map((audioClip) => {
+ const audioUrl = audioUrls[audioClip.assetId];
+ return audioUrl
+ ? <audio
+ key={audioClip.id}
+ ref={(element) => { if (element) audioRefs.current.set(audioClip.id, element); else audioRefs.current.delete(audioClip.id); }}
+ src={audioUrl}
+ preload="auto"
+ />
+ : null;
+ })}
+ {overlay}
+ </div>;
+}
diff --git a/src/components/workspace/TimelineView.tsx b/src/components/workspace/TimelineView.tsx
index 1f60bae..7c77bdb 100644
--- a/src/components/workspace/TimelineView.tsx
+++ b/src/components/workspace/TimelineView.tsx
@@ -1,14 +1,19 @@
import {
Copy, Film, Layers3, LayoutGrid, List, Lock, LockOpen, Music2,
Pause, Play, Plus, Scissors, SkipBack, SkipForward, Trash2, Upload, Video,
- Volume2, VolumeX,
+ Volume2, VolumeX, X,
} from "lucide-react";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { resolutionLabel } from "../../lib/export";
import { importMediaFiles, isTauri } from "../../lib/persistence";
import { loadMediaLayout, saveMediaLayout, type MediaLayout } from "../../lib/settings";
-import type { ProjectAsset, ProjectConfig, TimelineClip } from "../../lib/project";
+import type { ProjectAsset, ProjectConfig, TimelineClip, TimelineTrack } from "../../lib/project";
+import {
+ clipEndMs, findClip, insertClip, moveClip, removeClip, snapTargets, sourceRoom, trimClip,
+ type SnapOptions, type SourceRoom,
+} from "../../lib/timeline";
import { MediaThumbnail, type MeasuredMedia } from "./MediaThumbnail";
+import { ProgramMonitor } from "./ProgramMonitor";
const MIN_DURATION = 10_000;
const NOT_YET = "Not available yet. This control doesn’t change your project.";
@@ -24,6 +29,56 @@ const DROPPED_CLIP_MS = 5_000;
the desktop, and text dragged from anywhere else, out of the drop handler. */
const ASSET_DRAG_TYPE = "application/x-polstudio-asset";
+/* How close two edges have to be ON SCREEN before they snap together. In
+ pixels, not milliseconds, because that is how close they LOOK — the same
+ 8px feels the same on a 20-second timeline and a 10-minute one, where a fixed
+ number of milliseconds would be unusable at one end and invisible at the
+ other. Converted against the lane's real width at the moment a drag starts. */
+const SNAP_PX = 8;
+/* Below this, a press is a click. Without it the smallest tremor between
+ pointerdown and pointerup would be read as a drag and a clip that was only
+ being selected would be nudged off its cut. */
+const DRAG_THRESHOLD_PX = 3;
+
+type DragMode = "move" | "trim-start" | "trim-end";
+
+/** One drag, from the press that began it. Everything the pointer needs is
+ * measured ONCE, here: the lane's geometry, what may be snapped to, and how
+ * much footage the file has left at each end. Re-measuring per pointermove
+ * would let a re-render mid-drag change the arithmetic under the pointer.
+ *
+ * `baseTracks` is the timeline as it stood when the drag began, and every
+ * preview is computed from it rather than from the last preview — so dragging
+ * back to where you started really does put the clip back. */
+interface DragSession {
+ clipId: string;
+ mode: DragMode;
+ baseTracks: TimelineTrack[];
+ laneLeftPx: number;
+ msPerPx: number;
+ /** Where inside the clip the pointer took hold, so the clip does not jump so
+ * its head is under the cursor. Move only. */
+ grabOffsetMs: number;
+ startXPx: number;
+ snap: SnapOptions;
+ room: SourceRoom;
+ moved: boolean;
+}
+
+/** Which lane the pointer is over, for a drag that has left the lane it started
+ * in. Read from the document rather than from React state because the pointer
+ * is captured elsewhere: what is under it is a question only the DOM can
+ * answer. jsdom has no hit-testing, so a missing method means "the lane it
+ * started on", not a crash. */
+function trackIdAtPoint(x: number, y: number): string | undefined {
+ if (typeof document.elementsFromPoint !== "function") return undefined;
+ for (const element of document.elementsFromPoint(x, y)) {
+ const lane = (element as HTMLElement).closest?.("[data-track-id]") as HTMLElement | null;
+ if (lane?.dataset.trackId) return lane.dataset.trackId;
+ }
+ return undefined;
+}
+
/* The canvas used to be a hard-coded 34s — the seeded fixture's exact length —
so a 60-second project still got a 34-second ruler. Derive it from the real
content, falling back to the duration the user actually asked for. */
@@ -107,26 +162,40 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
must not be snapped back to a formatted timecode mid-keystroke. Null means
nothing is being typed and the clip speaks for itself. */
const [durationDraft, setDurationDraft] = useState<string | null>(null);
+ /* A drag in flight, and the timeline as it would be if the pointer were
+ released right now. The lanes draw the preview, and the release commits
+ exactly it — the drag and the edit are the same calculation, run twice
+ (see src/lib/timeline.ts). Null means the move is refused from here: the
+ clip is drawn where it really is, which is the honest answer to "no". */
+ const dragRef = useRef<DragSession | null>(null);
+ const previewRef = useRef<TimelineTrack[] | null>(null);
+ const [preview, setPreview] = useState<TimelineTrack[] | null>(null);
+ const [dragging, setDragging] = useState(false);
+ /* Whether the pointer is currently dragging the playhead along the ruler.
+ A press alone moves it once; this is what makes the moves keep coming. */
+ const [scrubbing, setScrubbing] = useState(false);
const tracks = config.timeline.tracks;
const selected = useMemo(() => tracks.flatMap((track) => track.clips).find((clip) => clip.id === selectedId), [tracks, selectedId]);
const selectedTrack = tracks.find((track) => track.id === selected?.trackId);
const clipCount = tracks.reduce((total, track) => total + track.clips.length, 0);
+ /** Where the last clip ends — where playback stops, which is not the same as
+ * where the ruler stops (the canvas is at least as long as the film the user
+ * asked for, however little of it is cut yet). */
+ const contentEndMs = tracks.reduce((end, track) => track.clips.reduce((furthest, clip) => Math.max(furthest, clipEndMs(clip)), end), 0);
const sceneClips = tracks.filter((track) => track.kind === "video").flatMap((track) => track.clips);
- const hasVisualOutput = config.assets.some((asset) => asset.kind === "video" || asset.kind === "image" || asset.kind === "generated")
- || config.generationJobs.some((job) => Boolean(job.outputRelativePath));
const duration = useMemo(() => canvasDuration(config), [config]);
const ticks = useMemo(() => rulerTicks(duration), [duration]);
- useEffect(() => {
- // Playing an empty timeline would run the clock over nothing, which reads
- // as playback of footage that does not exist.
- if (!playing || clipCount === 0) return;
- const timer = window.setInterval(() => setPlayhead((current) => current >= duration ? 0 : current + 100), 100);
- return () => window.clearInterval(timer);
- }, [playing, clipCount, duration]);
-
useEffect(() => { if (clipCount === 0 && playing) setPlaying(false); }, [clipCount, playing]);
+ /* The playhead is driven by the program monitor while playing — it reads
+ where the decoder actually is, so the picture and the playhead cannot
+ drift apart. These two are handed down rather than declared inline
+ because the monitor's animation loop depends on their identity: a new
+ closure per render would tear its clock down sixty times a second. */
+ const seek = useCallback((ms: number) => setPlayhead(ms), []);
+ const setPlayingFromMonitor = useCallback((value: boolean) => setPlaying(value), []);
+
// Another clip, another length: what was being typed belonged to the old one.
useEffect(() => { setDurationDraft(null); }, [selectedId]);
@@ -154,24 +223,53 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
return () => grid.removeEventListener("wheel", onWheel);
}, [duration, config.settings.frameRate]);
+ /** Turn a pointer position on the ruler into a playhead position. A ruler
+ * nothing has laid out has no scale, so it is left alone rather than
+ * sending the playhead to NaN. */
+ const scrubTo = (ruler: HTMLElement, clientX: number) => {
+ const rect = ruler.getBoundingClientRect();
+ if (rect.width <= 0) return;
+ setPlayhead(Math.round(Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)) * duration));
+ };
+
const chooseMediaLayout = (layout: MediaLayout) => { setMediaLayout(layout); saveMediaLayout(layout); };
- const updateTracks = (nextTracks: ProjectConfig["timeline"]["tracks"]) => onChange({ ...config, timeline: { tracks: nextTracks } });
+ /* Every timeline write hands up an UPDATER rather than a finished config,
+ for the same reason measurements do (see recordMeasured, and ConfigUpdate).
+ A finished config is built from the props THIS render closed over, and the
+ timeline is not always the most recent thing written: the media panel is
+ recording what its decodes measured the whole time a folder is being
+ imported, and a drag holds the timeline as it stood when the press began.
+ Handing up `{ ...config, timeline }` from either would take those
+ measurements back out again — a rush that had just learned it was 40
+ seconds long would go back to being an unmeasured file, and the next drop
+ of it would be a 5-second stand-in. */
+ const updateTracks = (nextTracks: ProjectConfig["timeline"]["tracks"]) =>
+ onChange((current) => ({ ...current, timeline: { tracks: nextTracks } }));
const renameTrack = (trackId: string, name: string) => updateTracks(tracks.map((track) => track.id === trackId ? { ...track, name } : track));
const updateClip = (clipId: string, updates: Partial<TimelineClip>) => updateTracks(tracks.map((track) => ({ ...track, clips: track.clips.map((clip) => clip.id === clipId ? { ...clip, ...updates } : clip) })));
const toggleTrack = (trackId: string, key: "muted" | "locked") => updateTracks(tracks.map((track) => track.id === trackId ? { ...track, [key]: !track[key] } : track));
- const removeSelected = () => {
- if (!selected || selectedTrack?.locked) return;
- updateTracks(tracks.map((track) => ({ ...track, clips: track.clips.filter((clip) => clip.id !== selected.id) })));
- setSelectedId("");
+ /* Every removal — the toolbar, the key, the × on the clip itself — goes
+ through one function, so a locked track refuses all three. */
+ const deleteClip = (clipId: string) => {
+ const next = removeClip(tracks, clipId);
+ if (!next) return;
+ updateTracks(next);
+ setSelectedId((current) => (current === clipId ? "" : current));
};
+ const removeSelected = () => { if (selected) deleteClip(selected.id); };
const duplicateSelected = () => {
if (!selected || !selectedTrack || selectedTrack.locked) return;
/* The spread carries sourceStartMs with everything else, so duplicating a
clip that was split off the middle of a rush copies THAT range of the
footage, not the head of the file. Only the id, the position on the
ruler, and the name are new. */
- const copy = { ...selected, id: `${selected.id}-copy-${Date.now()}`, startMs: Math.min(duration - selected.durationMs, selected.startMs + selected.durationMs), label: `${selected.label} copy` };
- updateTracks(tracks.map((track) => track.id === selected.trackId ? { ...track, clips: [...track.clips, copy] } : track));
+ const copy = { ...selected, id: `${selected.id}-copy-${Date.now()}`, label: `${selected.label} copy` };
+ // Straight after the original if that is free, and otherwise wherever the
+ // lane has room: a copy laid on top of another clip is not a copy of the
+ // cut, it is two clips claiming one moment.
+ const next = insertClip(tracks, selected.trackId, copy, selected.startMs + selected.durationMs);
+ if (!next) return;
+ updateTracks(next);
setSelectedId(copy.id);
};
const splitSelected = () => {
@@ -311,15 +409,33 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
? Math.max(1, selectedAsset.durationMs - selected.sourceStartMs)
: null;
const minClipMs = Math.max(1, Math.round(1000 / config.settings.frameRate));
+ /** What the FILE has left at each end of a clip. A still image and a file
+ * nothing has measured have no source timeline to run out of, and get no
+ * limit rather than a guessed one. */
+ const roomFor = (clip: TimelineClip) => {
+ const asset = assetById(clip.assetId);
+ return sourceRoom(clip, asset && asset.kind !== "image" ? asset.durationMs ?? null : null);
+ };
+ /* Typing a length is trimming the tail, so it is the same operation the
+ right-hand handle performs — same floor of one frame, same ceiling in the
+ footage, and the same refusal to grow over the next clip on the track. */
const typeDuration = (value: string) => {
setDurationDraft(value);
const parsed = selected ? parseDuration(value, config.settings.frameRate) : null;
if (parsed === null || !selected) return;
- const ceiling = sourceLimitMs ?? Number.MAX_SAFE_INTEGER;
- updateClip(selected.id, { durationMs: Math.min(Math.max(parsed, minClipMs), Math.max(ceiling, minClipMs)) });
+ const next = trimClip(tracks, selected.id, "end", selected.startMs + parsed, { minClipMs, room: roomFor(selected) });
+ if (next) updateTracks(next);
};
- const dropAsset = (trackId: string, assetId: string, ratio: number) => {
+ /* Snapping, measured against a lane that is `widthPx` wide. A lane nothing
+ has laid out yet — jsdom, a panel that has never been painted — gives a
+ tolerance of 0, which turns the magnet off instead of inventing a scale. */
+ const snapFor = (widthPx: number, excludeClipId?: string): SnapOptions => ({
+ targets: snapTargets(tracks, { excludeClipId, playheadMs: playhead }),
+ toleranceMs: widthPx > 0 ? (SNAP_PX * duration) / widthPx : 0,
+ });
+
+ const dropAsset = (trackId: string, assetId: string, ratio: number, laneWidthPx: number) => {
const track = tracks.find((item) => item.id === trackId);
const asset = assetById(assetId);
if (!track || !acceptsAsset(track, asset) || !asset) return;
@@ -347,10 +463,110 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
color: null,
status: "approved",
};
- updateTracks(tracks.map((item) => item.id === track.id ? { ...item, clips: [...item.clips, clip] } : item));
+ /* The same placement a dragged clip gets: snapped to the cuts already on
+ the timeline, and butted up against whatever is in the way rather than
+ laid on top of it. A lane with no room at all refuses the drop. */
+ const next = insertClip(tracks, track.id, clip, startMs, snapFor(laneWidthPx));
+ if (!next) return;
+ updateTracks(next);
+ setSelectedId(clip.id);
+ };
+
+ /* --- Dragging a clip -----------------------------------------------------
+
+ Three gestures, one mechanism: take hold of a clip's body to move it along
+ its lane or into another lane of the same kind, or take hold of either end
+ to trim it. What the pointer produces is a PREVIEW — the lanes draw it and
+ nothing is written — and the release commits that preview unchanged. Escape
+ abandons it, and a gesture the rules refuse simply never produces a preview
+ to commit, so the clip stays where it was.
+ ======================================================================= */
+
+ const beginDrag = (event: React.PointerEvent<HTMLElement>, clip: TimelineClip, mode: DragMode) => {
+ // Left button only: a right-click is a context menu, and a middle-click is
+ // a scroll gesture in most shells.
+ if (event.button !== 0) return;
+ const track = tracks.find((item) => item.id === clip.trackId);
+ if (!track || track.locked) return;
+ const lane = (event.currentTarget as HTMLElement).closest(".track-lane") as HTMLElement | null;
+ const rect = lane?.getBoundingClientRect();
+ // Nothing has been laid out: there is no scale to turn pixels into time
+ // with, and a drag measured against a zero-width lane would put the clip at
+ // an arbitrary place on the ruler. The clip still selects.
+ if (!rect || rect.width <= 0) { setSelectedId(clip.id); return; }
+ const msPerPx = duration / rect.width;
+ dragRef.current = {
+ clipId: clip.id,
+ mode,
+ baseTracks: tracks,
+ laneLeftPx: rect.left,
+ msPerPx,
+ grabOffsetMs: (event.clientX - rect.left) * msPerPx - clip.startMs,
+ startXPx: event.clientX,
+ /* Every lane in the grid shares one column, so a lane's left edge and
+ width are the whole timeline's — which is why a drag that crosses into
+ another lane can keep using the geometry it measured on this one. */
+ snap: snapFor(rect.width, clip.id),
+ room: roomFor(clip),
+ moved: false,
+ };
setSelectedId(clip.id);
+ setDragging(true);
+ };
+
+ const endDrag = (commit: boolean) => {
+ if (commit && previewRef.current) updateTracks(previewRef.current);
+ dragRef.current = null;
+ previewRef.current = null;
+ setPreview(null);
+ setDragging(false);
};
+ useEffect(() => {
+ if (!dragging) return;
+ const show = (next: TimelineTrack[] | null) => { previewRef.current = next; setPreview(next); };
+ const onMove = (event: PointerEvent) => {
+ const session = dragRef.current;
+ if (!session) return;
+ // Until the pointer has travelled far enough to mean it, this is a click.
+ if (!session.moved && Math.abs(event.clientX - session.startXPx) < DRAG_THRESHOLD_PX) return;
+ session.moved = true;
+ const pointerMs = (event.clientX - session.laneLeftPx) * session.msPerPx;
+ if (session.mode === "move") {
+ const overTrack = trackIdAtPoint(event.clientX, event.clientY)
+ ?? findClip(session.baseTracks, session.clipId)?.track.id;
+ show(overTrack ? moveClip(session.baseTracks, session.clipId, overTrack, pointerMs - session.grabOffsetMs, session.snap) : null);
+ return;
+ }
+ show(trimClip(session.baseTracks, session.clipId, session.mode === "trim-start" ? "start" : "end", pointerMs, {
+ minClipMs, room: session.room, snap: session.snap,
+ }));
+ };
+ const onUp = () => endDrag(true);
+ const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") endDrag(false); };
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", onUp);
+ // A drag whose pointer is snatched away — a tablet lifted, a shell that
+ // takes the capture — must not leave the timeline in a half-dragged state.
+ window.addEventListener("pointercancel", onUp);
+ window.addEventListener("keydown", onKey);
+ return () => {
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", onUp);
+ window.removeEventListener("pointercancel", onUp);
+ window.removeEventListener("keydown", onKey);
+ };
+ /* Registered once per drag rather than per render: the handlers read the
+ session out of a ref, so a preview landing mid-drag must not tear the
+ listeners down and put them back. */
+ }, [dragging, minClipMs]);
+
+ /* What the lanes draw: the drag if there is one, and the project otherwise.
+ The inspector deliberately keeps reading the real project — a length that
+ flickered while a clip was being dragged would be a number nobody can
+ read. */
+ const drawnTracks = preview ?? tracks;
+
const addScene = () => {
// A new project already carries an unstarted draft made from the user's own
// words, so open that rather than stacking a near-identical second shot.
@@ -367,9 +583,15 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
};
return (
- <div className="timeline-view" tabIndex={0} onKeyDown={(event) => {
- if ((event.key === "Delete" || event.key === "Backspace") && event.target === event.currentTarget) removeSelected();
- if (event.code === "Space" && event.target === event.currentTarget && clipCount > 0) { event.preventDefault(); setPlaying((value) => !value); }
+ <div className={`timeline-view ${dragging ? "timeline-view--dragging" : ""}`} tabIndex={0} onKeyDown={(event) => {
+ /* Delete works from the view itself and from a focused clip — the clip IS
+ the thing being deleted, and having to leave it first to press the key
+ is the kind of rule only the code knows. It deliberately does NOT fire
+ from a text field: a Backspace in the clip's name is an edit. */
+ const target = event.target as HTMLElement;
+ const fromClip = target.classList?.contains("timeline-clip");
+ if ((event.key === "Delete" || event.key === "Backspace") && (event.target === event.currentTarget || fromClip)) removeSelected();
+ if (event.code === "Space" && (event.target === event.currentTarget || fromClip) && clipCount > 0) { event.preventDefault(); setPlaying((value) => !value); }
}}>
{/* The view had no top-level heading at all, so screen-reader users had
no landmark for it. Sighted users already see the project topbar. */}
@@ -446,21 +668,26 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
<main className="program-panel">
<h2 className="sr-only">Program monitor</h2>
<div className="program-canvas">
- {/* An empty monitor is an empty monitor: the panel that used to sit
- here restated the project's name and prompt — both already in the
- topbar — to say nothing was playing, which the black picture says
- by itself. The note about footage that exists but cannot be played
- back yet is worth making, but only once something is actually cut
- into the timeline; over an empty edit it was a panel about
- nothing, covering the picture. */}
- {hasVisualOutput && clipCount > 0 && (
- <div className="program-empty program-empty--footage">
+ {/* The real picture now: the clip under the playhead, decoded from
+ its own file. What used to stand here was a panel explaining
+ that PolStudio could not play footage back — true when it was
+ written, and no longer. An empty timeline still shows an empty
+ monitor, which says by itself that nothing is cut yet. */}
+ {clipCount > 0
+ ? <ProgramMonitor
+ config={config}
+ folderPath={folderPath}
+ playheadMs={playhead}
+ playing={playing}
+ onSeek={seek}
+ onPlayingChange={setPlayingFromMonitor}
+ />
+ : <div className="program-empty">
<Film size={30} />
<strong>{config.name}</strong>
<span>{config.brief.prompt}</span>
- <small>PolStudio can’t play this footage back yet. {clipCount === 1 ? "1 clip is" : `${clipCount} clips are`} arranged on the timeline below and nothing has been lost.</small>
- </div>
- )}
+ <small>Drop a file from Media onto a track below, or generate a scene, and it plays here.</small>
+ </div>}
</div>
</main>
@@ -535,7 +762,10 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
<button onClick={() => setPlayhead(0)} aria-label="Go to beginning" title={transportBlockedBy ?? "Go to beginning"} disabled={transportBlockedBy !== null}><SkipBack size={18} /></button>
{/* Nothing to play means nothing to play: running the clock over an
empty timeline reads as playback of footage that isn't there. */}
- <button className="play-button" onClick={() => setPlaying((value) => !value)} aria-label={playing ? "Pause" : "Play"} disabled={transportBlockedBy !== null} title={transportBlockedBy ?? (playing ? "Pause" : "Play")}>{playing ? <Pause size={18} fill="currentColor" /> : <Play size={18} fill="currentColor" />}</button>
+ {/* Pressing Play with the playhead already past the last frame used
+ to start playback that immediately stopped, which reads as a
+ broken button. From the end, Play means play it again. */}
+ <button className="play-button" onClick={() => { if (!playing && playhead >= contentEndMs) setPlayhead(0); setPlaying((value) => !value); }} aria-label={playing ? "Pause" : "Play"} disabled={transportBlockedBy !== null} title={transportBlockedBy ?? (playing ? "Pause" : "Play")}>{playing ? <Pause size={18} fill="currentColor" /> : <Play size={18} fill="currentColor" />}</button>
<button onClick={() => setPlayhead(Math.min(duration, playhead + 1000))} aria-label="Step forward one second" title={transportBlockedBy ?? "Step forward one second"} disabled={transportBlockedBy !== null}><SkipForward size={18} /></button>
</div>
<div className="timeline-tools">
@@ -545,16 +775,34 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
<button onClick={removeSelected} disabled={deleteBlockedBy !== null} title={deleteBlockedBy ?? "Delete selected clip"}><Trash2 size={16} /> Delete</button>
</div>
</header>
- <div className="timeline-grid" ref={timelineGrid} title="Scroll to scrub. Hold Shift for one frame at a time.">
+ <div className="timeline-grid" ref={timelineGrid} title="Scroll to scrub, or drag along the ruler. Hold Shift to scrub one frame at a time. Clips snap to the cuts around them; Escape abandons a drag.">
<div className="track-corner"><span>Tracks</span></div>
- <div className="time-ruler" onPointerDown={(event) => { const rect = event.currentTarget.getBoundingClientRect(); setPlayhead(Math.round(Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)) * duration)); }}>
+ {/* Press to jump, hold and drag to scrub. The monitor seeks to wherever
+ this lands, so dragging along the ruler runs the picture past under
+ the pointer — which is what scrubbing IS. Playback stops first:
+ scrubbing while playing would be two things driving one playhead. */}
+ <div
+ className="time-ruler"
+ onPointerDown={(event) => {
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ setPlaying(false);
+ setScrubbing(true);
+ scrubTo(event.currentTarget, event.clientX);
+ }}
+ onPointerMove={(event) => { if (scrubbing) scrubTo(event.currentTarget, event.clientX); }}
+ onPointerUp={(event) => { event.currentTarget.releasePointerCapture?.(event.pointerId); setScrubbing(false); }}
+ onPointerCancel={() => setScrubbing(false)}
+ >
{ticks.map((second) => <span key={second} style={{ left: `${second * 1000 / duration * 100}%` }}><i />{rulerLabel(second)}</span>)}
</div>
- {tracks.map((track) => <TrackRow
+ {drawnTracks.map((track) => <TrackRow
key={track.id}
track={track}
duration={duration}
selectedId={selectedId}
+ draggingId={dragging ? dragRef.current?.clipId : undefined}
+ onClipPointerDown={beginDrag}
+ onDeleteClip={deleteClip}
dropActive={dropTrackId === track.id}
/* A lane that stays dark is indistinguishable from a lane the
pointer simply is not over, so a sound held above a video track
@@ -580,7 +828,7 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
const rect = event.currentTarget.getBoundingClientRect();
// A zero-width lane would make the ratio NaN and the clip's start
// time with it, which zod then refuses to save.
- dropAsset(track.id, assetId, rect.width > 0 ? (event.clientX - rect.left) / rect.width : 0);
+ dropAsset(track.id, assetId, rect.width > 0 ? (event.clientX - rect.left) / rect.width : 0, rect.width);
}}
/>)}
<div className="timeline-playhead" style={{ left: `calc(var(--track-column) + (100% - var(--track-column)) * ${playhead / duration})` }}><span /><i /></div>
@@ -590,15 +838,20 @@ export function TimelineView({ config, folderPath, onChange, onMeasured, onOpenG
);
}
-function TrackRow({ track, duration, selectedId, dropActive, dropBlocked, onSelect, onToggle, onRename, onDragOverLane, onDragLeaveLane, onDropLane }: {
+function TrackRow({ track, duration, selectedId, draggingId, dropActive, dropBlocked, onSelect, onToggle, onRename, onClipPointerDown, onDeleteClip, onDragOverLane, onDragLeaveLane, onDropLane }: {
track: ProjectConfig["timeline"]["tracks"][number];
duration: number;
selectedId: string;
+ /** The clip currently being dragged, so it can be drawn as the thing under
+ * the pointer rather than as one more clip sitting on the lane. */
+ draggingId?: string;
dropActive: boolean;
dropBlocked: boolean;
onSelect: (id: string) => void;
onToggle: (id: string, key: "muted" | "locked") => void;
onRename: (id: string, name: string) => void;
+ onClipPointerDown: (event: React.PointerEvent<HTMLElement>, clip: TimelineClip, mode: DragMode) => void;
+ onDeleteClip: (id: string) => void;
onDragOverLane: (event: React.DragEvent<HTMLDivElement>) => void;
onDragLeaveLane: () => void;
onDropLane: (event: React.DragEvent<HTMLDivElement>) => void;
@@ -627,12 +880,61 @@ function TrackRow({ track, duration, selectedId, dropActive, dropBlocked, onSele
</div>
<div
className={`track-lane ${track.muted ? "muted" : ""} ${dropActive ? "track-lane--drop" : ""} ${dropBlocked ? "track-lane--reject" : ""}`}
+ /* Which track this lane IS, readable from the DOM: a clip dragged across
+ lanes is hit-tested against the document, and the id is how the answer
+ gets back to the model. */
+ data-track-id={track.id}
title={dropBlocked ? (track.locked ? `${track.name} is locked` : `${track.name} only takes ${track.kind === "audio" ? "sound" : "video and pictures"}`) : undefined}
onDragOver={onDragOverLane}
onDragLeave={onDragLeaveLane}
onDrop={onDropLane}
>
- {track.clips.map((clip) => <button key={clip.id} className={`timeline-clip timeline-clip--${track.kind} ${selectedId === clip.id ? "selected" : ""}`} style={{ left: `${clip.startMs / duration * 100}%`, width: `${clip.durationMs / duration * 100}%`, "--clip-color": clip.color } as React.CSSProperties} onClick={() => onSelect(clip.id)} title={`${clip.label} · ${(clip.durationMs / 1000).toFixed(1)} seconds`}><span className="clip-text"><b>{clip.label}</b><small>{track.kind === "audio" ? "▂▅▃▆▂▃▇▅▂▆▃▅▂" : `${(clip.durationMs / 1000).toFixed(1)}s · ${clip.status}`}</small></span></button>)}
+ {track.clips.map((clip) => <div
+ key={clip.id}
+ className={`clip-slot ${selectedId === clip.id ? "selected" : ""} ${draggingId === clip.id ? "clip-slot--dragging" : ""}`}
+ style={{ left: `${clip.startMs / duration * 100}%`, width: `${clip.durationMs / duration * 100}%`, "--clip-color": clip.color } as React.CSSProperties}
+ >
+ {/* The clip is a div with a button's role rather than a <button>: it
+ carries two trim handles and a delete control of its own, and a
+ button inside a button is not a thing a browser or a screen reader
+ can make sense of. Everything a button gave it is still here —
+ focus, Enter, the pressed state, a name. */}
+ <div
+ className={`timeline-clip timeline-clip--${track.kind} ${selectedId === clip.id ? "selected" : ""} ${track.locked ? "timeline-clip--locked" : ""}`}
+ role="button"
+ tabIndex={0}
+ aria-pressed={selectedId === clip.id}
+ aria-label={`${clip.label}, ${(clip.durationMs / 1000).toFixed(1)} seconds, on ${track.name}`}
+ title={track.locked
+ ? `${clip.label} · ${(clip.durationMs / 1000).toFixed(1)} seconds — ${track.name} is locked`
+ : `${clip.label} · ${(clip.durationMs / 1000).toFixed(1)} seconds — drag to move it, drag either end to trim it`}
+ onClick={() => onSelect(clip.id)}
+ onKeyDown={(event) => { if (event.key === "Enter") onSelect(clip.id); }}
+ onPointerDown={(event) => onClipPointerDown(event, clip, "move")}
+ ><span className="clip-text"><b>{clip.label}</b><small>{track.kind === "audio" ? "▂▅▃▆▂▃▇▅▂▆▃▅▂" : `${(clip.durationMs / 1000).toFixed(1)}s · ${clip.status}`}</small></span></div>
+ {/* The two ends, which cut rather than move. They stop the press from
+ reaching the clip body, or every trim would also be a move. A locked
+ track gets none of them: nothing on it can be changed. */}
+ {!track.locked && <>
+ <span
+ className="clip-handle clip-handle--start"
+ title={`Trim the start of ${clip.label}`}
+ onPointerDown={(event) => { event.stopPropagation(); onClipPointerDown(event, clip, "trim-start"); }}
+ />
+ <span
+ className="clip-handle clip-handle--end"
+ title={`Trim the end of ${clip.label}`}
+ onPointerDown={(event) => { event.stopPropagation(); onClipPointerDown(event, clip, "trim-end"); }}
+ />
+ <button
+ className="clip-delete"
+ aria-label={`Delete ${clip.label}`}
+ title={`Delete ${clip.label}`}
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={(event) => { event.stopPropagation(); onDeleteClip(clip.id); }}
+ ><X size={12} /></button>
+ </>}
+ </div>)}
</div>
</>;
}
diff --git a/src/lib/timeline.test.ts b/src/lib/timeline.test.ts
new file mode 100644
index 0000000..f17de34
--- /dev/null
+++ b/src/lib/timeline.test.ts
@@ -0,0 +1,286 @@
+import { describe, expect, it } from "vitest";
+import { parseProjectConfig, type TimelineClip, type TimelineTrack } from "./project";
+import {
+ clipEndMs,
+ freeStart,
+ insertClip,
+ moveClip,
+ removeClip,
+ snapStart,
+ snapTargets,
+ snapTime,
+ sourceRoom,
+ trimClip,
+} from "./timeline";
+
+const clip = (id: string, startMs: number, durationMs: number, over: Partial<TimelineClip> = {}): TimelineClip => ({
+ id, assetId: `asset-${id}`, trackId: "v1", startMs, durationMs, sourceStartMs: 0,
+ label: id, color: null, status: "approved", ...over,
+});
+
+const track = (id: string, kind: "video" | "audio", clips: TimelineClip[], over: Partial<TimelineTrack> = {}): TimelineTrack => ({
+ id, kind, name: id, locked: false, muted: false, clips: clips.map((item) => ({ ...item, trackId: id })), ...over,
+});
+
+/* Two picture lanes and two sound lanes, which is what makes "to another track"
+ testable in both directions and "not onto that one" testable at all. */
+const stage = () => [
+ track("v1", "video", [clip("a", 0, 4_000), clip("b", 6_000, 2_000)]),
+ track("v2", "video", []),
+ track("a1", "audio", [clip("music", 0, 10_000)]),
+ track("a2", "audio", []),
+];
+
+const lane = (tracks: TimelineTrack[], id: string) => tracks.find((item) => item.id === id)!;
+const at = (tracks: TimelineTrack[], trackId: string, clipId: string) => lane(tracks, trackId).clips.find((item) => item.id === clipId);
+
+/** Nothing any of these functions returns may put two clips over each other —
+ * the single invariant the whole module exists to keep. */
+const noOverlaps = (tracks: TimelineTrack[]) =>
+ tracks.every((item) => [...item.clips].sort((a, b) => a.startMs - b.startMs)
+ .every((current, index, sorted) => index === 0 || sorted[index - 1].startMs + sorted[index - 1].durationMs <= current.startMs));
+
+describe("snapping", () => {
+ it("offers the head of the timeline, the playhead, and both ends of every other clip", () => {
+ // 0 and the playhead, plus b (6s–8s) and the music (0–10s) — a's own edges
+ // are missing because a is the clip being dragged.
+ expect(snapTargets(stage(), { excludeClipId: "a", playheadMs: 5_500 }))
+ .toEqual([0, 5_500, 6_000, 8_000, 10_000]);
+ // The dragged clip is not a target for itself, or it could never move.
+ expect(snapTargets(stage(), { excludeClipId: "a" })).not.toContain(4_000);
+ });
+
+ it("takes the nearest target inside the tolerance and leaves everything else alone", () => {
+ const snap = { targets: [0, 6_000, 8_000], toleranceMs: 200 };
+ expect(snapTime(5_900, snap)).toBe(6_000);
+ expect(snapTime(6_250, snap)).toBe(6_250);
+ // A tolerance of zero is how the view says "I have not measured the lane
+ // yet". It must disable the magnet rather than snap everything to 0.
+ expect(snapTime(5_900, { targets: [0, 6_000], toleranceMs: 0 })).toBe(5_900);
+ });
+
+ it("lets the tail of a clip take the magnet, which is how a cut gets closed up", () => {
+ const snap = { targets: [6_000], toleranceMs: 200 };
+ // Head is 4s from anything; the tail is 100ms short of the next clip's head,
+ // so the clip lands flush and the gap disappears.
+ expect(snapStart(5_900 - 4_000, 4_000, snap)).toBe(2_000);
+ // Whichever end is closer wins: here it is the head.
+ expect(snapStart(5_950, 4_000, snap)).toBe(6_000);
+ });
+});
+
+describe("placing a clip where there is room", () => {
+ it("leaves a free position alone", () => {
+ expect(freeStart([clip("a", 0, 4_000)], 5_000, 1_000)).toBe(5_000);
+ });
+
+ it("butts up against whatever is in the way, on the nearer side", () => {
+ const neighbours = [clip("a", 2_000, 4_000)];
+ // Dropped over the head of the neighbour: lands flush in front of it.
+ expect(freeStart(neighbours, 2_300, 1_000)).toBe(1_000);
+ // Dropped over its tail: lands flush after it.
+ expect(freeStart(neighbours, 5_500, 1_000)).toBe(6_000);
+ // And a clip dropped where it already fits is not moved at all.
+ expect(freeStart(neighbours, 500, 1_000)).toBe(500);
+ });
+
+ it("finds a gap big enough and refuses when there is none", () => {
+ const crowd = [clip("a", 0, 4_000), clip("b", 5_000, 4_000)];
+ // The 1s gap takes a 1s clip exactly.
+ expect(freeStart(crowd, 4_400, 1_000)).toBe(4_000);
+ // A 2s clip does not fit in it, so it goes after the crowd rather than on
+ // top of anything.
+ expect(freeStart(crowd, 4_400, 2_000)).toBe(9_000);
+ // Nowhere at all: both edges of the crowd blocked by the timeline head is
+ // impossible, but a lane with no room to the left still answers honestly.
+ expect(freeStart([clip("a", 0, 4_000)], 0, 4_000)).toBe(4_000);
+ });
+
+ it("never lands a clip before the start of the timeline", () => {
+ expect(freeStart([], -5_000, 1_000)).toBe(0);
+ });
+});
+
+describe("moving a clip", () => {
+ it("moves it along its own lane", () => {
+ // b is 2s long and 4s–6s is empty, so this is a plain slide with no
+ // neighbour involved.
+ const next = moveClip(stage(), "b", "v1", 4_200)!;
+ expect(at(next, "v1", "b")!.startMs).toBe(4_200);
+ expect(noOverlaps(next)).toBe(true);
+ });
+
+ it("moves it to another lane of the same kind, and takes it off the old one", () => {
+ const next = moveClip(stage(), "a", "v2", 3_000)!;
+ expect(lane(next, "v1").clips.map((item) => item.id)).toEqual(["b"]);
+ expect(at(next, "v2", "a")).toMatchObject({ startMs: 3_000, trackId: "v2" });
+ // The clip's own record of which track it is on has to move with it, or the
+ // project says one thing and the lane it is drawn in says another.
+ expect(at(next, "v2", "a")!.trackId).toBe("v2");
+ });
+
+ it("moves sound between sound tracks", () => {
+ const next = moveClip(stage(), "music", "a2", 2_000)!;
+ expect(lane(next, "a1").clips).toHaveLength(0);
+ expect(at(next, "a2", "music")!.startMs).toBe(2_000);
+ });
+
+ it("refuses to mix picture and sound, or to touch a locked track", () => {
+ expect(moveClip(stage(), "music", "v2", 0)).toBeNull();
+ expect(moveClip(stage(), "a", "a2", 0)).toBeNull();
+ const lockedTarget = stage().map((item) => (item.id === "v2" ? { ...item, locked: true } : item));
+ expect(moveClip(lockedTarget, "a", "v2", 0)).toBeNull();
+ const lockedSource = stage().map((item) => (item.id === "v1" ? { ...item, locked: true } : item));
+ expect(moveClip(lockedSource, "a", "v2", 0)).toBeNull();
+ });
+
+ it("slides against a neighbour instead of covering it", () => {
+ // Dragged over the middle of b (6s–8s): it cannot land there, so it lands
+ // flush against the side the pointer was nearer to.
+ const next = moveClip(stage(), "a", "v1", 6_500)!;
+ expect(at(next, "v1", "a")!.startMs).toBe(8_000);
+ expect(noOverlaps(next)).toBe(true);
+ });
+
+ it("does not count the clip as its own neighbour when it moves within a lane", () => {
+ // Nudged 100ms right on a lane where the only other clip is far away. If
+ // the clip were still on the lane while being placed, it would block itself
+ // and jump the whole width of itself instead.
+ const next = moveClip(stage(), "a", "v1", 100)!;
+ expect(at(next, "v1", "a")!.startMs).toBe(100);
+ });
+
+ it("reports no move rather than an identical project", () => {
+ expect(moveClip(stage(), "a", "v1", 0)).toBeNull();
+ expect(moveClip(stage(), "nope", "v1", 0)).toBeNull();
+ expect(moveClip(stage(), "a", "no-such-track", 0)).toBeNull();
+ });
+
+ it("snaps to a neighbour while moving", () => {
+ const snap = { targets: snapTargets(stage(), { excludeClipId: "a" }), toleranceMs: 300 };
+ // 4.1s from the head means the tail lands 100ms short of b: close the gap.
+ const next = moveClip(stage(), "a", "v1", 2_100, snap)!;
+ expect(at(next, "v1", "a")!.startMs).toBe(2_000);
+ expect(clipEndMs(at(next, "v1", "a")!)).toBe(6_000);
+ });
+});
+
+describe("trimming a clip by its edges", () => {
+ const room = { headMs: 3_000, tailMs: 3_000 };
+
+ it("moves the head on the ruler and inside the file together", () => {
+ const tracks = [track("v1", "video", [clip("a", 4_000, 4_000, { sourceStartMs: 3_000 })])];
+ const next = trimClip(tracks, "a", "start", 5_000, { minClipMs: 40, room })!;
+ const trimmed = at(next, "v1", "a")!;
+ expect(trimmed.startMs).toBe(5_000);
+ expect(trimmed.durationMs).toBe(3_000);
+ // A second later on the ruler is a second later in the footage, or the
+ // trim would slide the picture under the cut.
+ expect(trimmed.sourceStartMs).toBe(4_000);
+ });
+
+ it("will not pull the head back past the footage the file has", () => {
+ const tracks = [track("v1", "video", [clip("a", 4_000, 4_000, { sourceStartMs: 1_000 })])];
+ // Only 1s of head is left in the file, so 4_000 - 1_000 is the floor.
+ const next = trimClip(tracks, "a", "start", 0, { minClipMs: 40, room: { headMs: 1_000, tailMs: 0 } })!;
+ expect(at(next, "v1", "a")).toMatchObject({ startMs: 3_000, durationMs: 5_000, sourceStartMs: 0 });
+ });
+
+ it("lets a still image be pulled open at either end, because it has no footage to run out of", () => {
+ const tracks = [track("v1", "video", [clip("still", 4_000, 2_000)])];
+ const unbounded = { headMs: null, tailMs: null };
+ expect(at(trimClip(tracks, "still", "start", 500, { minClipMs: 40, room: unbounded })!, "v1", "still"))
+ .toMatchObject({ startMs: 500, durationMs: 5_500, sourceStartMs: 0 });
+ expect(at(trimClip(tracks, "still", "end", 30_000, { minClipMs: 40, room: unbounded })!, "v1", "still"))
+ .toMatchObject({ startMs: 4_000, durationMs: 26_000 });
+ });
+
+ it("stops at the neighbour on that side rather than growing over it", () => {
+ const tracks = stage();
+ // a ends at 4s, b starts at 6s: the tail can reach 6s and no further.
+ const next = trimClip(tracks, "a", "end", 9_000, { minClipMs: 40, room: { headMs: 0, tailMs: 20_000 } })!;
+ expect(clipEndMs(at(next, "v1", "a")!)).toBe(6_000);
+ expect(noOverlaps(next)).toBe(true);
+ // And the head cannot be pulled back over the clip in front of it: b opens
+ // up into the 1s gap and stops dead on a's tail.
+ const crowded = [track("v1", "video", [clip("a", 0, 4_000), clip("b", 5_000, 4_000)])];
+ const pulled = trimClip(crowded, "b", "start", 1_000, { minClipMs: 40, room: { headMs: 9_000, tailMs: 0 } })!;
+ expect(at(pulled, "v1", "b")).toMatchObject({ startMs: 4_000, durationMs: 5_000 });
+ expect(noOverlaps(pulled)).toBe(true);
+ });
+
+ it("keeps at least one frame, from either end", () => {
+ const tracks = [track("v1", "video", [clip("a", 0, 4_000)])];
+ expect(at(trimClip(tracks, "a", "end", 0, { minClipMs: 42, room })!, "v1", "a")!.durationMs).toBe(42);
+ const fromHead = at(trimClip(tracks, "a", "start", 9_999, { minClipMs: 42, room })!, "v1", "a")!;
+ expect(fromHead.durationMs).toBe(42);
+ expect(fromHead.startMs).toBe(4_000 - 42);
+ });
+
+ it("will not run the tail past the end of the footage", () => {
+ const tracks = [track("v1", "video", [clip("a", 0, 4_000, { sourceStartMs: 2_000 })])];
+ // 10s file, starting 2s in, 4s used: 4s of tail left.
+ const measured = sourceRoom(tracks[0].clips[0], 10_000);
+ expect(measured).toEqual({ headMs: 2_000, tailMs: 4_000 });
+ expect(at(trimClip(tracks, "a", "end", 30_000, { minClipMs: 40, room: measured })!, "v1", "a")!.durationMs).toBe(8_000);
+ });
+
+ it("reports no trim rather than an identical project, and refuses a locked track", () => {
+ const tracks = [track("v1", "video", [clip("a", 0, 4_000)])];
+ expect(trimClip(tracks, "a", "end", 4_000, { minClipMs: 40, room })).toBeNull();
+ expect(trimClip(tracks, "a", "start", 0, { minClipMs: 40, room })).toBeNull();
+ const locked = [track("v1", "video", [clip("a", 0, 4_000)], { locked: true })];
+ expect(trimClip(locked, "a", "end", 6_000, { minClipMs: 40, room })).toBeNull();
+ });
+
+ it("snaps a trimmed edge to the clips around it", () => {
+ const tracks = stage();
+ const snap = { targets: snapTargets(tracks, { excludeClipId: "a" }), toleranceMs: 300 };
+ const next = trimClip(tracks, "a", "end", 5_800, { minClipMs: 40, room: { headMs: 0, tailMs: 20_000 }, snap })!;
+ expect(clipEndMs(at(next, "v1", "a")!)).toBe(6_000);
+ });
+});
+
+describe("removing and inserting", () => {
+ it("takes a clip off its track and leaves the rest alone", () => {
+ const next = removeClip(stage(), "a")!;
+ expect(lane(next, "v1").clips.map((item) => item.id)).toEqual(["b"]);
+ expect(lane(next, "a1").clips).toHaveLength(1);
+ });
+
+ it("refuses to remove from a locked track", () => {
+ const locked = stage().map((item) => (item.id === "v1" ? { ...item, locked: true } : item));
+ expect(removeClip(locked, "a")).toBeNull();
+ expect(removeClip(stage(), "not-a-clip")).toBeNull();
+ });
+
+ it("drops a new clip into the first place it fits", () => {
+ const fresh = clip("new", 0, 3_000);
+ const next = insertClip(stage(), "v1", fresh, 3_000)!;
+ // 3s over the top of a (0–4s): it butts up after it instead of covering it.
+ expect(at(next, "v1", "new")!.startMs).toBe(8_000);
+ expect(noOverlaps(next)).toBe(true);
+ expect(insertClip(stage().map((item) => (item.id === "v1" ? { ...item, locked: true } : item)), "v1", fresh, 0)).toBeNull();
+ });
+});
+
+describe("what comes out still parses as a project", () => {
+ it("survives the schema after a move, a trim and a delete", () => {
+ const base = parseProjectConfig({
+ schemaVersion: 1,
+ id: "11111111-1111-4111-8111-111111111111",
+ name: "Edits", createdAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z",
+ thumbnail: null,
+ settings: { aspectRatio: "16:9", resolution: "1080p", frameRate: 24, backgroundColor: "#10131a" },
+ brief: { prompt: "A film", status: "draft", targetDurationSeconds: 30, aspectRatio: "16:9", resolution: "1080p" },
+ assets: [], references: [], generationJobs: [],
+ timeline: { tracks: stage() },
+ exports: [],
+ });
+ const moved = moveClip(base.timeline.tracks, "a", "v2", 1_234)!;
+ const trimmed = trimClip(moved, "b", "start", 6_500, { minClipMs: 42, room: { headMs: 5_000, tailMs: 5_000 } })!;
+ const deleted = removeClip(trimmed, "music")!;
+ expect(parseProjectConfig({ ...base, timeline: { tracks: deleted } })).toBeTruthy();
+ expect(noOverlaps(deleted)).toBe(true);
+ });
+});
diff --git a/src/lib/timeline.ts b/src/lib/timeline.ts
new file mode 100644
index 0000000..066d1f6
--- /dev/null
+++ b/src/lib/timeline.ts
@@ -0,0 +1,278 @@
+import type { TimelineClip, TimelineTrack } from "./project";
+
+/* Editing the timeline, as arithmetic.
+ *
+ * Everything the timeline view can do to a clip by dragging — move it along its
+ * lane, move it to another lane, trim either end, delete it, drop a new one in
+ * — lands here rather than in the pointer handlers. Two reasons, and the second
+ * is the one that matters:
+ *
+ * * A pointer handler cannot be tested without a browser that lays things out;
+ * these functions are numbers in and numbers out.
+ * * The DRAG PREVIEW and the COMMITTED EDIT have to be the same calculation.
+ * The view draws the drag by running these functions and rendering the
+ * result, then commits by running them once more on release. What the user
+ * sees under the pointer is therefore what is written down — a preview that
+ * approximated the commit would put a clip somewhere the user did not aim.
+ *
+ * The one invariant everything here keeps: no two clips on the same track ever
+ * cover the same millisecond. A refused edit returns null rather than a
+ * best-effort overlap, and the caller leaves the project alone. */
+
+/** Where a clip stops. Exclusive: a clip at 0 lasting 1000 ends at 1000, and a
+ * clip starting at 1000 sits flush against it without overlapping. */
+export const clipEndMs = (clip: Pick<TimelineClip, "startMs" | "durationMs">) => clip.startMs + clip.durationMs;
+
+const overlaps = (aStart: number, aEnd: number, bStart: number, bEnd: number) => aStart < bEnd && bStart < aEnd;
+
+/** How close two edges have to be, and what they may line up with. Tolerance is
+ * milliseconds because that is what the model speaks, but the view derives it
+ * from a fixed number of PIXELS — snapping has to feel the same at every zoom,
+ * and a lane it has not measured yet gives 0, which disables it rather than
+ * guessing. */
+export interface SnapOptions {
+ targets: number[];
+ toleranceMs: number;
+}
+
+export const NO_SNAP: SnapOptions = { targets: [], toleranceMs: 0 };
+
+/** Every edge worth lining up with: the head of the timeline, the playhead, and
+ * both ends of every other clip — including clips on other tracks, because
+ * cutting a sound to land on a picture change is the whole point of a magnet.
+ * The clip being dragged is excluded; a clip cannot snap to itself. */
+export function snapTargets(tracks: TimelineTrack[], options: { excludeClipId?: string; playheadMs?: number } = {}): number[] {
+ const targets = new Set<number>([0]);
+ if (options.playheadMs !== undefined && Number.isFinite(options.playheadMs)) targets.add(Math.round(options.playheadMs));
+ for (const track of tracks) {
+ for (const clip of track.clips) {
+ if (clip.id === options.excludeClipId) continue;
+ targets.add(clip.startMs);
+ targets.add(clipEndMs(clip));
+ }
+ }
+ return [...targets].sort((a, b) => a - b);
+}
+
+/** The nearest target within tolerance, or the value untouched. */
+export function snapTime(valueMs: number, snap: SnapOptions): number {
+ if (snap.toleranceMs <= 0) return valueMs;
+ let best = valueMs;
+ let bestDistance = snap.toleranceMs;
+ for (const target of snap.targets) {
+ const distance = Math.abs(target - valueMs);
+ // `<` rather than `<=`: with two targets equally close the first one wins,
+ // which is stable as the pointer moves rather than flipping between them.
+ if (distance < bestDistance) {
+ best = target;
+ bestDistance = distance;
+ }
+ }
+ return best;
+}
+
+/** A whole clip snapped: its head OR its tail may take the magnet, whichever is
+ * closer to something. Returns the start time. Dragging a clip so its END
+ * lands on the next clip's head is how a cut is closed up, and snapping only
+ * the head would never close it. */
+export function snapStart(desiredStartMs: number, durationMs: number, snap: SnapOptions): number {
+ const fromStart = snapTime(desiredStartMs, snap);
+ const fromEnd = snapTime(desiredStartMs + durationMs, snap) - durationMs;
+ /* Whether each END found a magnet at all, which is not the same question as
+ how far it moved: an edge already sitting exactly on a target moves by
+ zero, and reading that as "did not snap" would hand the drag to the other
+ end and pull the clip off the target it was already on. */
+ const headTook = fromStart !== desiredStartMs;
+ const tailTook = fromEnd !== desiredStartMs;
+ if (!headTook) return tailTook ? fromEnd : desiredStartMs;
+ if (!tailTook) return fromStart;
+ // Both ends found something: the smaller correction wins, so the clip moves
+ // to the nearer magnet rather than being yanked across the lane.
+ return Math.abs(fromEnd - desiredStartMs) < Math.abs(fromStart - desiredStartMs) ? fromEnd : fromStart;
+}
+
+/** Where a clip `durationMs` long can actually sit on a lane already holding
+ * `neighbours`, as near `desiredStartMs` as the lane allows.
+ *
+ * A drag that lands on top of another clip is not an overlap and is not a
+ * refusal either: the clip slides flush against whatever is in the way, on
+ * whichever side is nearer to where the pointer actually was. That is what
+ * makes butting two shots together with a drag possible at all. Null is
+ * returned only when the lane genuinely has no room — every gap is too small
+ * and both edges of the crowd are occupied. */
+export function freeStart(neighbours: TimelineClip[], desiredStartMs: number, durationMs: number): number | null {
+ const desired = Math.max(0, Math.round(desiredStartMs));
+ const occupied = neighbours
+ .map((clip) => ({ start: clip.startMs, end: clipEndMs(clip) }))
+ .sort((a, b) => a.start - b.start);
+ const fits = (start: number) => start >= 0 && !occupied.some((slot) => overlaps(start, start + durationMs, slot.start, slot.end));
+ if (fits(desired)) return desired;
+ /* Both sides of every clip in the way, plus the head of the timeline. The
+ nearest one that FITS wins — "nearest" measured from where the pointer
+ asked for, so a clip dropped just past a neighbour's middle butts up after
+ it rather than jumping back in front of it. */
+ const candidates = [0, ...occupied.flatMap((slot) => [slot.start - durationMs, slot.end])]
+ .filter(fits)
+ .sort((a, b) => Math.abs(a - desired) - Math.abs(b - desired));
+ return candidates[0] ?? null;
+}
+
+const withClips = (tracks: TimelineTrack[], trackId: string, clips: TimelineClip[]): TimelineTrack[] =>
+ tracks.map((track) => (track.id === trackId ? { ...track, clips } : track));
+
+const byStart = (clips: TimelineClip[]) => [...clips].sort((a, b) => a.startMs - b.startMs);
+
+export interface ClipLocation {
+ clip: TimelineClip;
+ track: TimelineTrack;
+}
+
+export function findClip(tracks: TimelineTrack[], clipId: string): ClipLocation | null {
+ for (const track of tracks) {
+ const clip = track.clips.find((candidate) => candidate.id === clipId);
+ if (clip) return { clip, track };
+ }
+ return null;
+}
+
+/** Move a clip along its lane or into another one.
+ *
+ * Refused — null, and the caller writes nothing — when either track is locked,
+ * when the two tracks hold different kinds of media (a sound cannot be dragged
+ * onto a picture track any more than it can be dropped there), or when the
+ * target lane has no room for it. */
+export function moveClip(
+ tracks: TimelineTrack[],
+ clipId: string,
+ targetTrackId: string,
+ desiredStartMs: number,
+ snap: SnapOptions = NO_SNAP,
+): TimelineTrack[] | null {
+ const found = findClip(tracks, clipId);
+ const target = tracks.find((track) => track.id === targetTrackId);
+ if (!found || !target) return null;
+ if (found.track.locked || target.locked) return null;
+ if (found.track.kind !== target.kind) return null;
+
+ const startMs = freeStart(
+ target.clips.filter((clip) => clip.id !== clipId),
+ snapStart(desiredStartMs, found.clip.durationMs, snap),
+ found.clip.durationMs,
+ );
+ if (startMs === null) return null;
+ if (target.id === found.track.id && startMs === found.clip.startMs) return null;
+
+ const moved: TimelineClip = { ...found.clip, trackId: target.id, startMs };
+ // Lifted off its old lane first, so a move WITHIN one lane does not leave the
+ // clip behind as its own neighbour.
+ const lifted = tracks.map((track) => (track.id === found.track.id ? { ...track, clips: track.clips.filter((clip) => clip.id !== clipId) } : track));
+ const landing = lifted.find((track) => track.id === target.id)?.clips ?? [];
+ return withClips(lifted, target.id, byStart([...landing, moved]));
+}
+
+/** What the FILE can still give a clip, in milliseconds, at each end.
+ * Null means unbounded: a still image has no source timeline to run out of,
+ * and a file nothing has measured yet has no length to be held to. Passing a
+ * guess here would let a trim claim footage that does not exist. */
+export interface SourceRoom {
+ headMs: number | null;
+ tailMs: number | null;
+}
+
+/** The room a clip has inside its own source file, given the file's length.
+ * `sourceDurationMs` null (a still, or an unmeasured file) means no limit. */
+export function sourceRoom(clip: TimelineClip, sourceDurationMs: number | null): SourceRoom {
+ if (sourceDurationMs === null || !Number.isFinite(sourceDurationMs) || sourceDurationMs <= 0) {
+ return { headMs: null, tailMs: null };
+ }
+ return {
+ headMs: Math.max(0, clip.sourceStartMs),
+ tailMs: Math.max(0, sourceDurationMs - clip.sourceStartMs - clip.durationMs),
+ };
+}
+
+export interface TrimOptions {
+ minClipMs: number;
+ room: SourceRoom;
+ snap?: SnapOptions;
+}
+
+/** Drag one end of a clip to `desiredMs`.
+ *
+ * Trimming the START moves the clip's head on the ruler AND the point it
+ * begins inside its file, together — that is what makes it a trim rather than
+ * a move. Trimming the END only changes how long it lasts.
+ *
+ * Every limit that exists is applied: the neighbour on that side (clips never
+ * overlap), the head of the timeline, the footage the file actually has left,
+ * and a floor of one frame so the result is still a clip. */
+export function trimClip(
+ tracks: TimelineTrack[],
+ clipId: string,
+ edge: "start" | "end",
+ desiredMs: number,
+ options: TrimOptions,
+): TimelineTrack[] | null {
+ const found = findClip(tracks, clipId);
+ if (!found || found.track.locked) return null;
+ const { clip, track } = found;
+ const minClipMs = Math.max(1, Math.round(options.minClipMs));
+ const others = track.clips.filter((candidate) => candidate.id !== clipId);
+ const snapped = Math.round(snapTime(desiredMs, options.snap ?? NO_SNAP));
+
+ if (edge === "start") {
+ const end = clipEndMs(clip);
+ const previousEnd = others
+ .filter((candidate) => clipEndMs(candidate) <= clip.startMs)
+ .reduce((furthest, candidate) => Math.max(furthest, clipEndMs(candidate)), 0);
+ // How far left this end can go: past the neighbour, past zero, and past the
+ // head of the footage are all impossible, and the clip must stay a clip.
+ const floor = Math.max(0, previousEnd, options.room.headMs === null ? 0 : clip.startMs - options.room.headMs);
+ const startMs = Math.min(Math.max(snapped, floor), end - minClipMs);
+ if (startMs === clip.startMs) return null;
+ const shift = startMs - clip.startMs;
+ const next: TimelineClip = {
+ ...clip,
+ startMs,
+ durationMs: end - startMs,
+ // The head moved by `shift` on the ruler, so it moved by `shift` inside
+ // the file too. Clamped at zero for a source with no timeline of its own.
+ sourceStartMs: Math.max(0, clip.sourceStartMs + shift),
+ };
+ return withClips(tracks, track.id, byStart([...others, next]));
+ }
+
+ const nextStart = others
+ .filter((candidate) => candidate.startMs >= clipEndMs(clip))
+ .reduce((nearest, candidate) => Math.min(nearest, candidate.startMs), Number.POSITIVE_INFINITY);
+ const ceiling = Math.min(nextStart, options.room.tailMs === null ? Number.POSITIVE_INFINITY : clipEndMs(clip) + options.room.tailMs);
+ const endMs = Math.max(Math.min(snapped, ceiling), clip.startMs + minClipMs);
+ if (endMs === clipEndMs(clip)) return null;
+ return withClips(tracks, track.id, byStart([...others, { ...clip, durationMs: endMs - clip.startMs }]));
+}
+
+/** Take a clip off the timeline. The media it was cut from stays in the
+ * project: deleting a clip is an edit, not an import being undone. */
+export function removeClip(tracks: TimelineTrack[], clipId: string): TimelineTrack[] | null {
+ const found = findClip(tracks, clipId);
+ if (!found || found.track.locked) return null;
+ return withClips(tracks, found.track.id, found.track.clips.filter((clip) => clip.id !== clipId));
+}
+
+/** Put a new clip on a track at (or as near as possible to) `desiredStartMs`.
+ * The same placement rule as a move, so a file dropped from the media panel
+ * onto an occupied stretch butts up against what is there instead of landing
+ * on top of it. Null when the lane has no room at all. */
+export function insertClip(
+ tracks: TimelineTrack[],
+ trackId: string,
+ clip: TimelineClip,
+ desiredStartMs: number,
+ snap: SnapOptions = NO_SNAP,
+): TimelineTrack[] | null {
+ const track = tracks.find((candidate) => candidate.id === trackId);
+ if (!track || track.locked) return null;
+ const startMs = freeStart(track.clips, snapStart(desiredStartMs, clip.durationMs, snap), clip.durationMs);
+ if (startMs === null) return null;
+ return withClips(tracks, track.id, byStart([...track.clips, { ...clip, trackId, startMs }]));
+}
diff --git a/src/styles/timeline.css b/src/styles/timeline.css
index 7d1c747..e4e403e 100644
--- a/src/styles/timeline.css
+++ b/src/styles/timeline.css
@@ -518,6 +518,53 @@
background-size: 12px 12px;
}
+/* The picture itself. The panel is the frame; the shot is fitted inside it and
+ the rest is the project's background colour, so a 9:16 cut looks 9:16 while
+ it is being cut rather than being stretched to fill a 16:9 panel. */
+.program-picture {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-md);
+}
+
+.program-picture video,
+.program-picture img {
+ display: block;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+}
+
+/* What the monitor has to say when there is no picture to show: a gap under the
+ playhead, a file it could not read, a file still being read. Over the frame
+ rather than instead of it, so the black stays black. */
+.program-note {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ max-width: min(90%, 520px);
+ padding: var(--space-3) var(--space-4);
+ border: 1px solid var(--line-strong);
+ border-radius: var(--radius-md);
+ color: var(--text-secondary);
+ font-size: var(--text-sm);
+ line-height: var(--leading-snug);
+ background: color-mix(in srgb, var(--panel) 86%, transparent);
+}
+
+.program-note--error {
+ border-color: var(--danger);
+ color: var(--text-primary);
+}
+
/* One honest monitor state for both cases: PolStudio cannot decode footage in
the editor yet, so it names the real project instead of drawing a stand-in. */
.program-empty {
@@ -1137,13 +1184,35 @@
/* --- Clips ----------------------------------------------------------------- */
-.timeline-clip {
+/* The clip and the three controls that ride on it — two trim handles and a
+ delete — share one box, positioned on the ruler. They are siblings rather
+ than children of the clip because the clip is itself a control: nesting a
+ button inside a button is not something a browser or a screen reader can
+ make sense of. */
+.clip-slot {
position: absolute;
top: var(--space-2);
height: 56px;
- min-width: 32px;
+ min-width: 22px;
+}
+
+.clip-slot.selected {
+ z-index: 3;
+}
+
+/* The clip being dragged rides over everything, including the clip it is being
+ dropped next to, so the edge being aimed at stays visible. */
+.clip-slot--dragging {
+ z-index: 5;
+ filter: brightness(1.06);
+}
+
+.timeline-clip {
+ position: absolute;
+ inset: 0;
overflow: hidden;
padding: 0;
+ cursor: grab;
border: 1px solid color-mix(in srgb, var(--clip-color, var(--clip-video-default)) 70%, var(--clip-edge) 10%);
border-radius: var(--radius-sm);
text-align: left;
@@ -1175,10 +1244,100 @@
filter: brightness(1.14);
}
+/* Nothing on a locked track moves, so nothing on it offers the hand that says
+ it would. */
+.timeline-clip--locked {
+ cursor: default;
+}
+
.timeline-clip.selected {
border-color: var(--clip-selected-edge);
box-shadow: 0 0 0 2px var(--accent-bright), inset 0 1px var(--clip-sheen-strong);
- z-index: 3;
+}
+
+/* --- Trimming and deleting a clip ------------------------------------------
+
+ The handles are hit targets first: 10px of grab area at each end, wider than
+ the 3px they draw, because a trim that needs a pixel-perfect press is a trim
+ nobody performs. They sit ON the clip's edges rather than outside them, so
+ two clips butted together do not put four overlapping handles in the same
+ few pixels.
+ ========================================================================== */
+
+.clip-handle {
+ position: absolute;
+ z-index: 4;
+ top: 0;
+ bottom: 0;
+ width: 10px;
+ cursor: ew-resize;
+ border-radius: var(--radius-sm);
+ background: transparent;
+ transition: background 120ms ease;
+}
+
+.clip-handle--start { left: 0; }
+.clip-handle--end { right: 0; }
+
+.clip-slot:hover .clip-handle,
+.clip-slot.selected .clip-handle {
+ background: linear-gradient(90deg, var(--clip-sheen-strong), transparent 60%);
+}
+
+.clip-slot:hover .clip-handle--end,
+.clip-slot.selected .clip-handle--end {
+ background: linear-gradient(270deg, var(--clip-sheen-strong), transparent 60%);
+}
+
+.clip-handle:hover {
+ background: var(--accent-bright) !important;
+ opacity: 0.85;
+}
+
+.clip-delete {
+ position: absolute;
+ z-index: 4;
+ top: 3px;
+ right: 3px;
+ display: none;
+ place-items: center;
+ width: 18px;
+ height: 18px;
+ padding: 0;
+ border: 1px solid var(--line-strong);
+ border-radius: var(--radius-sm);
+ color: var(--text-primary);
+ background: color-mix(in srgb, var(--panel) 80%, transparent);
+}
+
+/* Only on the clip the pointer is over, or the one being worked on: eighteen
+ delete buttons across a full timeline is a row of things to hit by mistake.
+ Focus counts too, so it can be reached from the keyboard at all. */
+.clip-slot:hover .clip-delete,
+.clip-slot.selected .clip-delete,
+.clip-delete:focus-visible {
+ display: grid;
+}
+
+.clip-delete:hover {
+ border-color: var(--danger);
+ color: var(--danger);
+}
+
+/* A clip narrower than the controls would be nothing but controls. */
+.clip-slot[style*="width: 0"] .clip-delete {
+ display: none;
+}
+
+/* Nothing is selectable while a clip is being dragged: a drag across the lanes
+ would otherwise paint the whole timeline blue with a text selection. */
+.timeline-view--dragging {
+ user-select: none;
+ cursor: grabbing;
+}
+
+.timeline-view--dragging .timeline-clip {
+ cursor: grabbing;
}
.clip-text {