Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Studio: export picked frames and ranges, a new version history, What's New for every release; macOS full-screen close (#264)

riverisbuilding985dca657cb6
diff --git a/.changeset/export-frames-and-ranges.md b/.changeset/export-frames-and-ranges.md
new file mode 100644
index 0000000..e94b8a7
--- /dev/null
+++ b/.changeset/export-frames-and-ranges.md
@@ -0,0 +1,9 @@
+---
+"openfilm": patch
+---
+
+Export: pick the exact frames and ranges to export, in a larger dialog that grows with the window.
+
+- Images and Slides & PDF are one page, Images, with four ways to deliver the same frames and framing: image files, a ZIP, a PDF or a PowerPoint deck. Any frame can be picked, not only the middle of each shot. The film shows large, as it will be exported, over a filmstrip that zooms and scrolls like the timeline. Click or drag to look, then Add this frame or Return; ← → step a frame. Quick picks add the playhead, the middle of each shot, each marker, or a frame every few seconds. Each image is named after the shot it is in, and the picks are remembered for each project.
+- A partial video, GIF, audio or subtitle export can take up to 100 ranges. Add a range, trim it on the filmstrip or type its start and end (seconds, M:SS, H:MM:SS or a frame timecode), and play it in the preview. Export each range as its own file, or merge them into one file in the order listed, with picture, sound and subtitles kept together. A range that is not valid stops the export with a message; the whole film is never exported in its place.
+- Video file has the social media presets: Default first, then each platform. Changing a setting makes it Custom. Saved social export settings carry over.
diff --git a/.changeset/full-screen-close.md b/.changeset/full-screen-close.md
new file mode 100644
index 0000000..04fdb81
--- /dev/null
+++ b/.changeset/full-screen-close.md
@@ -0,0 +1,5 @@
+---
+"@openfilm/desktop": patch
+---
+
+macOS: closing the window while it is full screen leaves full screen first, then hides the window, so no empty black Space is left behind. Clicking the Dock icon meanwhile keeps the window open.
diff --git a/.changeset/version-history-window.md b/.changeset/version-history-window.md
new file mode 100644
index 0000000..554a362
--- /dev/null
+++ b/.changeset/version-history-window.md
@@ -0,0 +1,15 @@
+---
+"openfilm": patch
+---
+
+Version history is redesigned, in a window the size of Export.
+
+- Versions are listed by day, with search and a filter by type (manual, auto-saved, restore, other) or named versions only. Current edits are at the top, with the files changed since the last saved version, and Save version (an optional name) when something changed.
+- Selecting a version plays its film from the saved copy and lists the files it changed. Looking at a version never touches your current edits.
+- Restore this version brings the project back to it. Unsaved edits are saved as a version first, so nothing is lost. Markers, settings and subtitles follow the restored version in every window. Save as new project starts a separate project from any version.
+- Delete moves one or more versions to Deleted, where they can be recovered. The version in use can't be deleted, and no file or saved copy is removed.
+- Discard all changes returns the film to the last saved version; files added since go to the Trash.
+- A version keeps all of the project's files (pages, code, data, fonts, notes), not only the ones the film names. Unused video, sound and pictures, and files over 50 MB, are still left out. An older history is brought up to date the first time it opens.
+- Settings › Advanced › Versions › Auto versions (off by default) saves a version before and after an agent's turn and when the film rests for two minutes, only when the film changed.
+- Branches and merging are gone from the window; versions saved on earlier branches stay in the list.
+- When the history can't be read, it says so, with Try again.
diff --git a/.changeset/whats-new-earlier-releases.md b/.changeset/whats-new-earlier-releases.md
new file mode 100644
index 0000000..c0357ac
--- /dev/null
+++ b/.changeset/whats-new-earlier-releases.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+What's New is taller, and below this update's notes it scrolls on through every earlier release, in the language Studio shows, so the whole history reads without the English changelog on GitHub (still a click away). A release can now list up to 24 changes there instead of six.
diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs
index a0b5e65..1e655ef 100644
--- a/apps/desktop/src/main.mjs
+++ b/apps/desktop/src/main.mjs
@@ -97,6 +97,7 @@ const tellFfmpeg = (state) => { ffmpegFound = state; broadcast('desktop:ffmpeg',
/** @type {ReturnType<typeof startUpdates> | null} */
let updates = null;
let quitting = false;
+let cancelWindowClose = () => {};
/** @type {ReturnType<typeof registerLocalAgentIpc> | null} */
let localAgents = null;
/** @type {ReturnType<typeof createRoster> | null} */
@@ -107,6 +108,7 @@ const BACKGROUND = { light: '#f2f2f2', dark: '#111111' };
function focusWindow() {
if (!win) return;
+ cancelWindowClose();
if (win.isMinimized()) win.restore();
win.show();
win.focus();
@@ -503,7 +505,7 @@ async function start() {
win.on('moved', saveState);
win.on('enter-full-screen', () => broadcast('desktop:full-screen', true));
win.on('leave-full-screen', () => broadcast('desktop:full-screen', false));
- keepWindowOnClose(win, { mac, isQuitting: () => quitting, save: saveState });
+ cancelWindowClose = keepWindowOnClose(win, { mac, isQuitting: () => quitting, save: saveState });
win.on('closed', () => { win = null; views.clear(); pagePresentation = null; app.quit(); });
ipcMain.on('desktop:theme', (event, next) => { if (fromPage(event)) setTheme(next); });
diff --git a/apps/desktop/src/window-lifecycle.mjs b/apps/desktop/src/window-lifecycle.mjs
index 22a8aaf..2500087 100644
--- a/apps/desktop/src/window-lifecycle.mjs
+++ b/apps/desktop/src/window-lifecycle.mjs
@@ -1,12 +1,28 @@
/** Keep the macOS window available for Dock activation without ending Studio or agent sessions. */
export function keepWindowOnClose(win, { mac, isQuitting, save }) {
+ let leavingFullScreen = false;
+ function cancelClose() {
+ leavingFullScreen = false;
+ win.removeListener('leave-full-screen', hide);
+ }
+ function hide() {
+ cancelClose();
+ if (!win.isDestroyed() && !isQuitting()) win.hide();
+ }
win.on('close', (event) => {
save();
if (mac && !isQuitting()) {
event.preventDefault();
- win.hide();
- }
+ if (leavingFullScreen) return;
+ if (!win.isFullScreen()) { win.hide(); return; }
+ /* Hiding a native full-screen window leaves its Space black. Its exit is asynchronous on macOS. */
+ leavingFullScreen = true;
+ win.once('leave-full-screen', hide);
+ win.setFullScreen(false);
+ } else cancelClose();
});
+ /* Dock activation while full screen is leaving keeps the window open. */
+ return cancelClose;
}
/** An empty projects page closes its window only on macOS. */
diff --git a/apps/desktop/src/window-lifecycle.test.mjs b/apps/desktop/src/window-lifecycle.test.mjs
index 442275e..4973ac6 100644
--- a/apps/desktop/src/window-lifecycle.test.mjs
+++ b/apps/desktop/src/window-lifecycle.test.mjs
@@ -6,8 +6,14 @@ import { closeTabOrWindow, keepWindowOnClose, quitAfterStudio } from './window-l
class Window extends EventEmitter {
visible = true;
destroyed = false;
+ fullScreen = false;
+ fullScreenRequests = [];
hide() { this.visible = false; }
show() { this.visible = true; }
+ isDestroyed() { return this.destroyed; }
+ isFullScreen() { return this.fullScreen; }
+ setFullScreen(value) { this.fullScreenRequests.push(value); }
+ leaveFullScreen() { this.fullScreen = false; this.emit('leave-full-screen'); }
close() {
let prevented = false;
this.emit('close', { preventDefault() { prevented = true; } });
@@ -36,6 +42,48 @@ test('macOS close preserves the window and sessions for activation, but explicit
assert.equal(saved, 3);
});
+test('macOS full-screen close leaves its Space before hiding, even when close is pressed twice', () => {
+ const win = new Window();
+ win.fullScreen = true;
+ keepWindowOnClose(win, { mac: true, isQuitting: () => false, save: () => {} });
+ win.close();
+ win.close();
+ assert.equal(win.visible, true, 'keep drawing the window throughout the native full-screen transition');
+ assert.equal(win.destroyed, false);
+ assert.deepEqual(win.fullScreenRequests, [false]);
+ win.leaveFullScreen();
+ assert.equal(win.visible, false);
+ assert.equal(win.destroyed, false, 'its pages and agent sessions remain available for Dock activation');
+});
+
+test('Dock activation during a full-screen close keeps the window visible after the transition', () => {
+ const win = new Window();
+ win.fullScreen = true;
+ const cancelClose = keepWindowOnClose(win, { mac: true, isQuitting: () => false, save: () => {} });
+ win.close();
+ cancelClose();
+ win.show();
+ win.leaveFullScreen();
+ assert.equal(win.visible, true);
+ assert.equal(win.listenerCount('leave-full-screen'), 0);
+ win.close();
+ assert.equal(win.visible, false, 'a later close still works');
+});
+
+test('explicit Quit during a pending full-screen close proceeds without a late hide', () => {
+ const win = new Window();
+ win.fullScreen = true;
+ let quitting = false;
+ keepWindowOnClose(win, { mac: true, isQuitting: () => quitting, save: () => {} });
+ win.close();
+ quitting = true;
+ win.close();
+ assert.equal(win.destroyed, true);
+ assert.equal(win.listenerCount('leave-full-screen'), 0);
+ win.leaveFullScreen();
+ assert.equal(win.visible, true, 'the deferred close must not act on the destroyed window');
+});
+
test('Windows and Linux window close still follows the existing quit path', () => {
const win = new Window();
let saved = 0;
diff --git a/packages/openfilm/src/render-ranges.mjs b/packages/openfilm/src/render-ranges.mjs
new file mode 100644
index 0000000..be4202d
--- /dev/null
+++ b/packages/openfilm/src/render-ranges.mjs
@@ -0,0 +1,42 @@
+/** Selected stretches in their chosen order, snapped exactly as a single render snaps its endpoints. */
+export function renderSelection(ranges, fps, duration = Infinity) {
+ if (!Array.isArray(ranges) || !ranges.length || ranges.length > 100) throw new Error('ranges: choose 1 to 100 time ranges');
+ let count = 0;
+ const spans = ranges.map((range) => {
+ if (!Array.isArray(range) || range.length !== 2 || !range.every(Number.isFinite) || range[0] < 0 || range[1] <= range[0]) throw new Error('a range is [from, to] in seconds, to after from');
+ const first = Math.round(range[0] * fps);
+ const last = Math.round(Math.min(range[1], duration) * fps);
+ if (last <= first) throw new Error(`nothing to render between ${range[0]} and ${range[1]}`);
+ const span = { from: first / fps, to: last / fps, first, at: count, count: last - first };
+ count += span.count;
+ return span;
+ });
+ return { spans, count, duration: count / fps };
+}
+
+/** The source frame for a frame on the joined timeline. Repeated or overlapping stretches remain repeated. */
+export function selectionFrame(spans, frame) {
+ const span = spans.find((part) => frame < part.at + part.count) ?? spans.at(-1);
+ return span.first + Math.max(0, Math.min(span.count - 1, frame - span.at));
+}
+
+/** Trim the film's mix clips to each stretch and place them consecutively, retaining speed, gain and fade phase.
+ * @template {{ at: number, from: number, to?: number, speed?: number, fade?: { skip: number } }} T
+ * @param {T[]} clips @param {readonly { from: number, to: number }[]} ranges @returns {T[]}
+ */
+export function selectionClips(clips, ranges) {
+ let offset = 0;
+ return ranges.flatMap(({ from, to }) => {
+ const at = offset;
+ offset += to - from;
+ return clips.flatMap((clip) => {
+ const speed = clip.speed ?? 1;
+ const start = Math.max(from, clip.at);
+ const end = Math.min(to, clip.at + ((clip.to ?? Infinity) - clip.from) / speed);
+ if (end <= start) return [];
+ const skip = start - clip.at;
+ return [{ ...clip, at: at + start - from, from: clip.from + skip * speed, to: clip.from + (end - clip.at) * speed,
+ ...(clip.fade ? { fade: { ...clip.fade, skip: clip.fade.skip + skip } } : {}) }];
+ });
+ });
+}
diff --git a/packages/openfilm/src/render-ranges.test.mjs b/packages/openfilm/src/render-ranges.test.mjs
new file mode 100644
index 0000000..70b2178
--- /dev/null
+++ b/packages/openfilm/src/render-ranges.test.mjs
@@ -0,0 +1,31 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { renderSelection, selectionClips, selectionFrame } from './render-ranges.mjs';
+
+test('a joined render keeps chosen order and repeats, with only the selected source frames', () => {
+ const plan = renderSelection([[8.02, 8.34], [1.01, 1.21], [8.02, 8.34]], 30, 10);
+ assert.equal(plan.count, 24);
+ assert.equal(plan.duration, 0.8);
+ assert.deepEqual(Array.from({ length: 24 }, (_, f) => selectionFrame(plan.spans, f)), [
+ ...Array.from({ length: 9 }, (_, f) => 241 + f),
+ ...Array.from({ length: 6 }, (_, f) => 30 + f),
+ ...Array.from({ length: 9 }, (_, f) => 241 + f),
+ ]);
+});
+
+test('the sound is clipped at each cut, moved to the joined clock, and keeps its speed and fade phase', () => {
+ const clips = [{ file: 'voice.wav', at: 1, from: 4, to: 20, speed: 2, volume: 0.7, fade: { in: 2, out: 1, length: 8, skip: 0 } }];
+ const selected = selectionClips(clips, [{ from: 5, to: 7 }, { from: 0, to: 2 }]);
+ assert.deepEqual(selected.map(({ at, from, to, speed, volume, fade }) => ({ at, from, to, speed, volume, fade })), [
+ { at: 0, from: 12, to: 16, speed: 2, volume: 0.7, fade: { in: 2, out: 1, length: 8, skip: 4 } },
+ { at: 3, from: 4, to: 6, speed: 2, volume: 0.7, fade: { in: 2, out: 1, length: 8, skip: 0 } },
+ ]);
+ assert.deepEqual(selectionClips(clips, [{ from: 20, to: 22 }]), []);
+});
+
+test('empty, malformed and sub-frame selections fail before drawing; ends past the film are clamped', () => {
+ for (const ranges of [[], [[1, 1]], [[2, 1]], [[-1, 2]], [[0, Infinity]], [[0, 0.001]], [[5, 6]]]) {
+ assert.throws(() => renderSelection(ranges, 30, 3));
+ }
+ assert.equal(renderSelection([[2, 9]], 30, 3).count, 30);
+});
diff --git a/packages/openfilm/src/render.mjs b/packages/openfilm/src/render.mjs
index ab6a711..cc3d95c 100644
--- a/packages/openfilm/src/render.mjs
+++ b/packages/openfilm/src/render.mjs
@@ -11,6 +11,7 @@ import { exactRate, ffmpegRate } from './rate.mjs';
import { browserCopies, filmVideos } from './seekable.mjs';
import { ffmpeg, filmSound, fmt, kill, locate, mix, open, outDir, parseTarget, shown, UsageError, write } from './shared.mjs';
import { burned } from './burn.mjs';
+import { renderSelection, selectionClips, selectionFrame } from './render-ranges.mjs';
const BT709 = ['-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'bt709', '-color_range', 'tv'];
const TAG_709 = ['-bsf:v', 'h264_metadata=colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1:video_full_range_flag=0'];
@@ -77,6 +78,7 @@ export function outOfMemory(e, workers) {
export async function render(args, opts = {}) {
const started = Date.now();
const { film: target, at, range } = parseTarget(args);
+ if (range && opts.ranges) throw new UsageError('choose a range or ranges, not both');
if (at != null) throw new UsageError(`render takes a range (for example ${at}-${at + 2}), not one time; for one frame use openfilm look ${at}`);
/* --subtitles: the project's film drawn around by a page that burns its subtitles in (the export's own, burn.mjs),
rendered in its place, from the project's folder, named as the film's own render is. Studio burns only the
@@ -127,8 +129,11 @@ export async function render(args, opts = {}) {
const fps = rate.fps;
/* a page without a duration has no end: it is rendered by a range */
const end = meta.duration ?? Infinity;
- if (!range && meta.duration == null) { await probe.close(); await pool?.give(lent); throw new UsageError('this page has no duration, so it has no end: give a range to render, e.g. openfilm render 0-6'); }
- const [from, to] = range ? [range[0], Math.min(range[1], end)] : [0, end];
+ if (!range && !opts.ranges && meta.duration == null) { await probe.close(); await pool?.give(lent); throw new UsageError('this page has no duration, so it has no end: give a range to render, e.g. openfilm render 0-6'); }
+ let selection = null;
+ try { if (opts.ranges) selection = renderSelection(opts.ranges, fps, end); }
+ catch (e) { await probe.close(); await pool?.give(lent); throw e; }
+ const [from, to] = selection ? [0, selection.duration] : range ? [range[0], Math.min(range[1], end)] : [0, end];
const f0 = Math.round(from * fps);
const f1 = Math.round(to * fps);
const total = f1 - f0;
@@ -245,7 +250,8 @@ export async function render(args, opts = {}) {
const stop = new AbortController();
const quit = () => stop.abort();
opts.signal?.addEventListener('abort', quit, { once: true });
- const runs = parts.map((p) => encode(p, { fps, rate, samples, shutter, duration: end, first: f0, format: f, onFrame: progress, still: alpha ? 'png' : 'jpeg', opaque, signal: stop.signal }));
+ const runs = parts.map((p) => encode(p, { fps, rate, samples, shutter, duration: end, first: f0, format: f, onFrame: progress, still: alpha ? 'png' : 'jpeg', opaque, signal: stop.signal,
+ sourceFrame: selection ? (frame) => selectionFrame(selection.spans, frame) : (frame) => frame }));
try {
await unlessCancelled(Promise.all(runs));
} catch (e) {
@@ -288,7 +294,8 @@ export async function render(args, opts = {}) {
if (process.stderr.isTTY && !opts.onProgress) process.stderr.write('\n');
for (const p of pages) problems.push(...p.problems);
- const clips = opts.silent ? [] : await filmSound(probe, from);
+ const allClips = opts.silent ? [] : await filmSound(probe, selection ? 0 : from);
+ const clips = selection ? selectionClips(allClips, selection.spans) : allClips;
if (opts.signal?.aborted) throw new Error('cancelled');
const sound = clips.length ? join(work, `sound${extname(out) === '.mp4' ? '.m4a' : extname(out) === '.webm' ? '.webm' : '.wav'}`) : null;
if (sound) await mix(clips, to - from, sound, format.audio);
@@ -318,6 +325,7 @@ export async function render(args, opts = {}) {
return {
out,
encoder,
+ ...(selection ? { ranges: selection.spans.map((part) => [part.from, part.to]) } : {}),
...(clearFormat ? { clear } : {}),
lines: [
`→ ${shown(out)}`,
@@ -400,7 +408,7 @@ function alphaWatch() {
}
/** Frames [a, b) of one page into one file; sub-frames are averaged by ffmpeg (tmix) and every n-th kept. */
-async function encode({ film, a, b, file }, { fps, rate, samples, shutter, duration, first = a, format, onFrame, still, opaque, signal }) {
+async function encode({ film, a, b, file }, { fps, rate, samples, shutter, duration, first = a, format, onFrame, still, opaque, signal, sourceFrame = (frame) => frame }) {
const blur = samples > 1 ? `tmix=frames=${samples},select='eq(mod(n\\,${samples})\\,${samples - 1})',setpts=N/((${ffmpegRate(rate)})*TB),` : '';
const enc = ffmpeg(['-f', 'image2pipe', '-framerate', ffmpegRate(rate, samples), '-c:v', still === 'png' ? 'png' : 'mjpeg', '-i', '-',
'-vf', blur + format.pix, '-r', ffmpegRate(rate), ...format.video, file], { input: true });
@@ -423,7 +431,7 @@ async function encode({ film, a, b, file }, { fps, rate, samples, shutter, durat
two are taken and thrown away first, of the two frames before this part (of its first frame for the render's
first part), so a frame is the same however many browsers share the render */
for (const f of [a - 2, a - 1].map((n) => Math.max(first, n))) {
- await film.seek(Math.min(Math.max(0, f / fps), duration - 1e-4));
+ await film.seek(Math.min(Math.max(0, sourceFrame(f) / fps), duration - 1e-4));
await film.capture(still === 'png' ? { format: 'png' } : { format: 'jpeg', quality: 95 });
}
for (let f = a; f < b; f++) {
@@ -433,10 +441,10 @@ async function encode({ film, a, b, file }, { fps, rate, samples, shutter, durat
}
if (watch?.clear) {
stop();
- throw showsThrough(`by ${fmt(f / fps)}`);
+ throw showsThrough(`by ${fmt(sourceFrame(f) / fps)}`);
}
for (let k = 0; k < samples; k++) {
- const t = (f + (samples > 1 ? (k / samples - 0.5) * shutter : 0)) / fps;
+ const t = (sourceFrame(f) + (samples > 1 ? (k / samples - 0.5) * shutter : 0)) / fps;
await film.seek(Math.min(Math.max(0, t), duration - 1e-4));
const frame = await film.capture(still === 'png' ? { format: 'png' } : { format: 'jpeg', quality: 95 });
await Promise.race([write(enc.proc.stdin, frame), ended]);
diff --git a/packages/openfilm/studio/server/auto-versions.mjs b/packages/openfilm/studio/server/auto-versions.mjs
new file mode 100644
index 0000000..a5d3aa1
--- /dev/null
+++ b/packages/openfilm/studio/server/auto-versions.mjs
@@ -0,0 +1,86 @@
+// @ts-check
+/**
+ * Versions saved on their own while a project is worked on, when the person turned Auto versions on (prefs.mjs
+ * `autoVersions`). Only for projects open in Studio (the ones someone watches), and only when something changed since
+ * the last version (history.mjs saveVersion gives null otherwise). The moments:
+ *
+ * an app's agent starts a turn what was there before it ('agent'), to come back to if the turn goes wrong
+ * that turn ends what it did ('auto')
+ * the folder rests for IDLE_MS after the person's edits, or an agent's that the app does not run ('auto'); at
+ * most MAX_MS after the first change of a stretch of work that never rests
+ * the project is closed what changed since the last version, if a rest was still awaited ('auto')
+ *
+ * const auto = createAutoVersions({ on: () => readPrefs().autoVersions, working: agentIn, roots: watchers.roots, save });
+ * auto.changed(root) // on each change of the folder
+ * auto.start() … auto.stop()
+ */
+
+export const IDLE_MS = 2 * 60_000;
+export const MAX_MS = 10 * 60_000;
+/** How often whether an app's agent is working is looked at. */
+export const POLL_MS = 3_000;
+
+/**
+ * @param {{ on: () => boolean, working: (root: string) => boolean, roots: () => string[],
+ * save: (root: string, kind: 'auto' | 'agent') => Promise<unknown>, idleMs?: number, maxMs?: number, pollMs?: number }} o
+ */
+export function createAutoVersions({ on, working, roots, save, idleMs = IDLE_MS, maxMs = MAX_MS, pollMs = POLL_MS }) {
+ /** @type {Map<string, { timer: NodeJS.Timeout | null, since: number | null, agent: boolean }>} per project */
+ const projects = new Map();
+ /** @type {NodeJS.Timeout | null} */
+ let polling = null;
+
+ const of = (/** @type {string} */ root) => {
+ let p = projects.get(root);
+ if (!p) { p = { timer: null, since: null, agent: working(root) }; projects.set(root, p); }
+ return p;
+ };
+ const saveNow = (/** @type {string} */ root, /** @type {'auto' | 'agent'} */ kind) => {
+ const p = projects.get(root);
+ if (p) { if (p.timer) clearTimeout(p.timer); p.timer = null; p.since = null; }
+ void save(root, kind).catch(() => {});
+ };
+
+ const poll = () => {
+ const open = new Set(roots());
+ for (const [root, p] of projects) {
+ if (open.has(root)) continue;
+ if (p.timer && on()) saveNow(root, 'auto');
+ else if (p.timer) clearTimeout(p.timer);
+ projects.delete(root);
+ }
+ if (!on()) return;
+ for (const root of open) {
+ const p = of(root);
+ const now = working(root);
+ if (now === p.agent) continue;
+ p.agent = now;
+ saveNow(root, now ? 'agent' : 'auto');
+ }
+ };
+
+ return {
+ /** The folder at `root` changed: a version once it rests, unless an app's agent is mid-turn (saved when it ends). */
+ changed(/** @type {string} */ root) {
+ if (!on()) return;
+ const p = of(root);
+ if (p.agent) return;
+ p.since ??= Date.now();
+ if (p.timer) clearTimeout(p.timer);
+ const wait = Math.max(0, Math.min(idleMs, p.since + maxMs - Date.now()));
+ p.timer = setTimeout(() => saveNow(root, 'auto'), wait);
+ p.timer.unref?.();
+ },
+ poll,
+ start() {
+ polling ??= setInterval(poll, pollMs);
+ polling.unref?.();
+ },
+ stop() {
+ if (polling) clearInterval(polling);
+ polling = null;
+ for (const p of projects.values()) if (p.timer) clearTimeout(p.timer);
+ projects.clear();
+ },
+ };
+}
diff --git a/packages/openfilm/studio/server/auto-versions.test.mjs b/packages/openfilm/studio/server/auto-versions.test.mjs
new file mode 100644
index 0000000..31d5fc9
--- /dev/null
+++ b/packages/openfilm/studio/server/auto-versions.test.mjs
@@ -0,0 +1,71 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createAutoVersions } from './auto-versions.mjs';
+
+const wait = (ms) => new Promise((done) => setTimeout(done, ms));
+
+/** Auto versions over fake projects: what was saved, when, of which kind. */
+function setup({ on = true, idleMs = 40, maxMs = 120 } = {}) {
+ const state = { on, working: new Set(), open: new Set(['/film']) };
+ const saved = [];
+ const auto = createAutoVersions({
+ on: () => state.on,
+ working: (root) => state.working.has(root),
+ roots: () => [...state.open],
+ save: async (root, kind) => { saved.push([root, kind]); },
+ idleMs, maxMs, pollMs: 1000,
+ });
+ return { state, saved, auto };
+}
+
+test('off by default for the person: nothing is saved on its own while it is off', async () => {
+ const { saved, auto } = setup({ on: false });
+ auto.changed('/film');
+ await wait(80);
+ auto.poll();
+ assert.deepEqual(saved, []);
+ auto.stop();
+});
+
+test('on: a version once the folder rests, one for a burst of changes', async () => {
+ const { saved, auto } = setup();
+ auto.changed('/film');
+ await wait(20);
+ auto.changed('/film');
+ await wait(20);
+ assert.deepEqual(saved, [], 'not while it is still changing');
+ await wait(50);
+ assert.deepEqual(saved, [['/film', 'auto']]);
+ auto.stop();
+});
+
+test('a stretch of work that never rests is saved at most MAX_MS after it began', async () => {
+ const { saved, auto } = setup({ idleMs: 50, maxMs: 100 });
+ for (let i = 0; i < 8; i++) { auto.changed('/film'); await wait(20); }
+ assert.ok(saved.length >= 1, 'saved without a rest');
+ auto.stop();
+});
+
+test('an app\'s agent: what was there before its turn, and what it did once the turn ends; its writes wait for that', async () => {
+ const { state, saved, auto } = setup();
+ auto.poll();
+ state.working.add('/film');
+ auto.poll();
+ assert.deepEqual(saved, [['/film', 'agent']]);
+ auto.changed('/film');
+ await wait(60);
+ assert.equal(saved.length, 1, 'no version mid-turn');
+ state.working.delete('/film');
+ auto.poll();
+ assert.deepEqual(saved, [['/film', 'agent'], ['/film', 'auto']]);
+ auto.stop();
+});
+
+test('a project closed with changes still awaiting a rest is saved then', async () => {
+ const { state, saved, auto } = setup({ idleMs: 10_000 });
+ auto.changed('/film');
+ state.open.delete('/film');
+ auto.poll();
+ assert.deepEqual(saved, [['/film', 'auto']]);
+ auto.stop();
+});
diff --git a/packages/openfilm/studio/server/export-ranges.test.mjs b/packages/openfilm/studio/server/export-ranges.test.mjs
new file mode 100644
index 0000000..ddf1de4
--- /dev/null
+++ b/packages/openfilm/studio/server/export-ranges.test.mjs
@@ -0,0 +1,80 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { filmHtml } from '../../src/film-doc.mjs';
+import { createExports, ExportError } from './exports.mjs';
+
+const hasFfmpeg = (() => { try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; } catch { return false; } })();
+const ended = (queue, id) => new Promise((resolve) => {
+ const tick = () => { const job = queue.list('ranges').find((job) => job.id === id); if (['done', 'failed', 'cancelled'].includes(job.status)) resolve(job); else setTimeout(tick, 30); };
+ tick();
+});
+const probe = (file, entries) => execFileSync('ffprobe', ['-v', 'error', '-show_entries', entries, '-of', 'json', file], { encoding: 'utf8' });
+const crossings = (file, start) => {
+ const pcm = execFileSync('ffmpeg', ['-v', 'error', '-ss', String(start), '-i', file, '-t', '0.08', '-map', '0:a:0', '-ac', '1', '-ar', '48000', '-f', 's16le', '-']);
+ let changes = 0;
+ for (let i = 2; i < pcm.length; i += 2) if ((pcm.readInt16LE(i) >= 0) !== (pcm.readInt16LE(i - 2) >= 0)) changes++;
+ return changes;
+};
+
+test('multi-range video joins only selected frames, with matching sound and retimed sidecar captions', { skip: !hasFfmpeg, timeout: 120_000 }, async () => {
+ const root = mkdtempSync(join(tmpdir(), 'openfilm-ranges-'));
+ const queue = createExports({ captions: async () => ({ cues: [{ startMs: 0, durMs: 500, text: 'Early' }, { startMs: 500, durMs: 700, text: 'Late' }], style: {} }) });
+ try {
+ writeFileSync(join(root, 'page.html'), '<!doctype html><body style="margin:0"><script>window.film={width:320,height:180,duration:1.2,frame(t){document.body.style.background=t<.5?"#e02020":"#2040e0"}}</script>');
+ execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'aevalsrc=0.2*sin(2*PI*if(lt(t\\,0.5)\\,440\\,880)*t):s=48000:d=1.2', join(root, 'voice.wav')]);
+ writeFileSync(join(root, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ src: 'page.html', id: 'picture', time: [0, 1.2] }] }, { clips: [{ src: 'voice.wav', id: 'voice' }] }] }));
+ const project = { id: 'ranges', name: 'Ranges', path: root };
+ const job = queue.start(project, { kind: 'video', fps: 10, hardware: false, ranges: [[0.8, 1.1], [0.1, 0.3]], sidecar: 'srt' }, { folder: root });
+ const done = await ended(queue, job.id);
+ assert.equal(done.status, 'done', done.error);
+ const meta = JSON.parse(probe(done.out, 'stream=codec_type,nb_frames:format=duration'));
+ assert.equal(Number(meta.streams.find((stream) => stream.codec_type === 'video').nb_frames), 5);
+ assert.ok(Math.abs(Number(meta.format.duration) - 0.5) < 0.03, meta.format.duration);
+ const pixels = execFileSync('ffmpeg', ['-v', 'error', '-i', done.out, '-vf', 'scale=1:1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);
+ assert.ok(pixels[2] > pixels[0] * 2, 'the first part is the later blue picture');
+ assert.ok(pixels[9] > pixels[11] * 2, 'the next part is the earlier red picture');
+ assert.ok(crossings(done.out, .06) > crossings(done.out, .36) * 1.6, 'the sound follows the same later-to-earlier cuts');
+ const captions = readFileSync(done.outputs.find((file) => file.endsWith('.srt')), 'utf8');
+ assert.match(captions, /00:00:00,000 --> 00:00:00,300\nLate/);
+ assert.match(captions, /00:00:00,300 --> 00:00:00,500\nEarly/);
+
+ const separately = [[0.8, 1.1], [0.1, 0.3]].map((range) => queue.start(project, { kind: 'video', fps: 10, hardware: false, range }, { folder: root }));
+ const separate = await Promise.all(separately.map((job) => ended(queue, job.id)));
+ assert.ok(separate.every((job) => job.status === 'done'), separate.map((job) => job.error).join('\n'));
+ assert.equal(new Set(separate.map((job) => job.out)).size, 2);
+ const frameCounts = separate.map((job) => Number(JSON.parse(probe(job.out, 'stream=codec_type,nb_frames')).streams.find((stream) => stream.codec_type === 'video').nb_frames));
+ assert.deepEqual(frameCounts, [3, 2]);
+
+ const audio = await ended(queue, queue.start(project, { kind: 'audio', format: 'wav', ranges: [[.8, 1.1], [.1, .3]] }, { folder: root }).id);
+ assert.equal(audio.status, 'done', audio.error);
+ assert.ok(Math.abs(Number(JSON.parse(probe(audio.out, 'format=duration')).format.duration) - .5) < .001);
+ assert.ok(crossings(audio.out, .06) > crossings(audio.out, .36) * 1.6);
+ const text = await ended(queue, queue.start(project, { kind: 'subtitles', ranges: [[.8, 1.1], [.1, .3]] }, { folder: root }).id);
+ assert.equal(text.status, 'done', text.error);
+ assert.equal(readFileSync(text.out, 'utf8'), captions);
+ const gif = await ended(queue, queue.start(project, { kind: 'gif', width: 160, fps: 10, ranges: [[.8, 1.1], [.1, .3]] }, { folder: root }).id);
+ assert.equal(gif.status, 'done', gif.error);
+ assert.equal(Number(JSON.parse(probe(gif.out, 'stream=nb_frames')).streams[0].nb_frames), 5);
+ const clamped = await ended(queue, queue.start(project, { kind: 'video', fps: 10, audio: false, hardware: false, ranges: [[1, 5], [0, .1]], sidecar: 'srt' }, { folder: root }).id);
+ assert.equal(clamped.status, 'done', clamped.error);
+ assert.match(readFileSync(clamped.outputs.find((file) => file.endsWith('.srt')), 'utf8'), /00:00:00,200 --> 00:00:00,300\nEarly/);
+ } finally {
+ await queue.stopAll();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('malformed selections and unsupported export destinations are refused before queueing', () => {
+ const queue = createExports();
+ const project = { id: 'ranges', name: 'Ranges', path: tmpdir() };
+ for (const ask of [
+ { kind: 'video', ranges: [] }, { kind: 'video', ranges: [[2, 1]] }, { kind: 'video', ranges: [[0, Infinity]] },
+ { kind: 'video', ranges: Array.from({ length: 101 }, () => [0, 1]) }, { kind: 'video', range: [0, 1], ranges: [[2, 3]] },
+ { kind: 'video', clip: 'a', ranges: [[0, 1]] }, { kind: 'nle', ranges: [[0, 1]] }, { kind: 'stills', ranges: [[0, 1]] },
+ ]) assert.throws(() => queue.start(project, ask), ExportError);
+ assert.deepEqual(queue.list('ranges'), []);
+});
diff --git a/packages/openfilm/studio/server/exports.mjs b/packages/openfilm/studio/server/exports.mjs
index 8d14058..f01b47e 100644
--- a/packages/openfilm/studio/server/exports.mjs
+++ b/packages/openfilm/studio/server/exports.mjs
@@ -24,13 +24,15 @@
* mix: `<name> - mix`; stems: voice, music, sound effects and the footage's own sound, each its own file
* (`<name> - voice`…), a sound grouped by where it is (assets/audio/music/…, assets/audio/sfx/…, anything
* else is voice) and a video's sound as the footage's (nle.mjs soundStem)
- * { kind: 'stills', format?: 'png' | 'jpg', frame?, fill?, shortEdge?, at?: number[] }
- * one frame from the middle of each picture clip (or at the seconds `at`), zipped when there are several
+ * { kind: 'stills', as?: 'files' | 'zip', format?: 'png' | 'jpg', frame?, fill?, shortEdge?, at?: number[] }
+ * one frame from the middle of each picture clip (or at the seconds `at`, each named by the scene it is in), zipped
+ * when there are several unless `as` explicitly asks for separate files or a zip (even for one frame)
* { kind: 'poster', format?, frame?, fill?, shortEdge?, at?: number } one frame (default: the middle)
* { kind: 'subtitles', format?: 'srt' (default) | 'vtt' | 'txt' } the film's subtitle cues as a file (txt: a
* plain transcript); refused when the film has none
* { kind: 'slides', format?: 'pptx' (default) | 'pdf', frame?, fill?, shortEdge? (default 1080), at?: number[] }
- * the scene stills bound as a deck (the scene's name in the speaker notes) or a PDF, one page each
+ * the stills (each scene's middle, or the seconds `at`) bound as a deck (the scene's name in the speaker notes) or a
+ * PDF, one page each
* { kind: 'nle', format?: 'xml' (default) | 'fcpxml' | 'jianying' | 'capcut', fps? (snapped to 23.976, 24, 25, 29.97, 30, 50, 59.94 or 60;
* default 30), audio?: 'clips' (default) | 'stems', media?: 'copy' (default) | 'link', subtitles?: boolean (default true),
* alpha?: 'auto' | 'png' | 'prores' | 'prores4444' }
@@ -54,6 +56,8 @@
* none); those with a picture (not one clip alone) take `burnSubtitles: true`, the subtitles drawn into the picture as
* the editor shows them (captions.mjs: the cues and the person's style). `folder`: an absolute path (or ~/…) to write
* to instead of the exports folder.
+ * Time-based exports also accept `ranges: [[from, to], ...]` (1–100, seconds) to join the selections in their given
+ * order, with the picture, sound and subtitles on the joined clock. Choose either `range` or `ranges`.
*/
import { execFile, fork, spawn } from 'node:child_process';
import { promisify } from 'node:util';
@@ -67,6 +71,7 @@ import { FilmPage, launch } from '../../src/host.mjs';
import { broken, encoders, FRAMES_709, hardwareEncoder, hardwareOptions, onTheChip, prores709, proresOptions } from '../../src/encoders.mjs';
import { COMMAND_ROOM, filmSound, filterScriptOption, kill as killProcess, mix, open } from '../../src/shared.mjs';
import { defaultWorkers, machine } from '../../src/render.mjs';
+import { selectionClips } from '../../src/render-ranges.mjs';
import { filmVideos } from '../../src/seekable.mjs';
import { FILM_FILE, clipFade, filmHtml, fittedFade, kindOf, pictureRect, readFilmFile } from '../../src/film-doc.mjs';
import { layerBlocks, rowBadges, trackKind } from './track-layout.mjs';
@@ -77,7 +82,7 @@ import { slidesPdf, writePptx } from './slides.mjs';
import { subtitlesForExport } from './captions.mjs';
import { burned, even, frameBox, frameRatio, stageOf } from '../../src/burn.mjs';
export { frameBox, frameRatio };
-import { filmSubtitleCuesInRange, filmSubtitleShown, filmSubtitleSrt, filmSubtitleTranscript, filmSubtitleVtt } from './film-subtitle.mjs';
+import { filmSubtitleCuesInRange, filmSubtitleCuesInRanges, filmSubtitleShown, filmSubtitleSrt, filmSubtitleTranscript, filmSubtitleVtt } from './film-subtitle.mjs';
import { zipFiles } from './zip.mjs';
import { inProject } from './files.mjs';
import { filmClosure, folderView } from './closure.mjs';
@@ -97,7 +102,7 @@ export { exportsRoot };
* fps?: number, quality?: Quality, audio?: boolean, clip?: string, preset?: string, sidecar?: 'srt' | 'vtt', hardware?: boolean }} VideoAsk
* @typedef {Framing & { kind: 'gif', width?: number, fps?: number }} GifAsk
* @typedef {{ kind: 'audio', format?: 'wav' | 'm4a' | 'mp3', mix?: boolean, stems?: boolean }} AudioAsk
- * @typedef {Framing & { kind: 'stills', format?: 'png' | 'jpg', shortEdge?: number, at?: number[] }} StillsAsk
+ * @typedef {Framing & { kind: 'stills', as?: 'files' | 'zip', format?: 'png' | 'jpg', shortEdge?: number, at?: number[] }} StillsAsk
* @typedef {Framing & { kind: 'poster', format?: 'png' | 'jpg', shortEdge?: number, at?: number }} PosterAsk
* @typedef {{ kind: 'subtitles', format?: 'srt' | 'vtt' | 'txt' }} SubtitlesAsk
* @typedef {Framing & { kind: 'slides', format?: 'pptx' | 'pdf', shortEdge?: number, at?: number[] }} SlidesAsk
@@ -105,7 +110,7 @@ export { exportsRoot };
* @typedef {{ kind: 'project', parts?: ProjectPart[], as?: 'zip' | 'folder' }} ProjectAsk
* @typedef {typeof PROJECT_PARTS[number]} ProjectPart
* @typedef {VideoAsk | GifAsk | AudioAsk | StillsAsk | PosterAsk | SubtitlesAsk | SlidesAsk | NleAsk | ProjectAsk} ExportSpec
- * @typedef {ExportSpec & { range?: [number, number], label?: string, name?: string }} ExportAsk
+ * @typedef {ExportSpec & { range?: [number, number], ranges?: [number, number][], label?: string, name?: string }} ExportAsk
* @typedef {import('./film-subtitle.mjs').FilmSubtitleCue} Cue
* @typedef {import('./film-subtitle.mjs').FilmSubtitleStyle} SubtitleStyle
* @typedef {'preparing' | 'audio' | 'rendering' | 'encoding' | 'copying' | 'finishing'} ExportPhase
@@ -281,7 +286,7 @@ function baseName(project, ask) {
export apart (a platform, alpha, stills) and loses the ones that only describe the project (a size, a range) */
const named = typeof ask.name === 'string' && ask.name.trim() ? safeName(ask.name) : null;
const base = named ?? safeName(project);
- const range = !named && ask.range ? ` ${ask.range[0]}-${ask.range[1]}s` : '';
+ const range = named ? '' : ask.range ? ` ${ask.range[0]}-${ask.range[1]}s` : ask.ranges ? ` ${ask.ranges.length} parts` : '';
switch (ask.kind) {
case 'video': {
if (ask.preset) return `${base} · ${safeName(ask.preset)}${range}`;
@@ -313,6 +318,10 @@ function checked(/** @type {ExportAsk} */ ask) {
if (ask.range !== undefined && !(Array.isArray(ask.range) && ask.range.length === 2 && isNum(ask.range[0]) && isNum(ask.range[1]) && ask.range[0] >= 0 && ask.range[1] > ask.range[0])) {
throw new ExportError('a range is [from, to] in seconds, to after from');
}
+ if (ask.ranges !== undefined) {
+ if (ask.range !== undefined || !['video', 'gif', 'audio', 'subtitles'].includes(ask.kind) || ('clip' in ask && ask.clip)) throw new ExportError('ranges: choose a whole-film video, GIF, audio or subtitle export without a single range');
+ if (!Array.isArray(ask.ranges) || !ask.ranges.length || ask.ranges.length > 100 || !ask.ranges.every((r) => Array.isArray(r) && r.length === 2 && r.every(isNum) && r[0] >= 0 && r[1] > r[0])) throw new ExportError('ranges: 1 to 100 [from, to] pairs in seconds, to after from');
+ }
if (ask.label !== undefined && (typeof ask.label !== 'string' || ask.label.length > 120)) throw new ExportError('label: text, at most 120 characters');
if (ask.name !== undefined && (typeof ask.name !== 'string' || ask.name.length > 120)) throw new ExportError('name: text, at most 120 characters');
if ('frame' in ask && ask.frame !== undefined && ask.frame !== 'native' && frameRatio(ask.frame) == null) throw new ExportError('frame: native, or a ratio W:H from 1:4 to 4:1 (16:9, 2.39:1)');
@@ -341,6 +350,7 @@ function checked(/** @type {ExportAsk} */ ask) {
case 'stills':
case 'poster':
if (ask.range !== undefined) throw new ExportError('a still is a moment: give `at`, not a range');
+ if (ask.kind === 'stills' && ask.as !== undefined && ask.as !== 'files' && ask.as !== 'zip') throw new ExportError('stills as files or zip');
if (ask.format !== undefined && ask.format !== 'png' && ask.format !== 'jpg') throw new ExportError('format: png or jpg');
if (ask.kind === 'stills' && ask.at !== undefined && !(Array.isArray(ask.at) && ask.at.length <= 500 && ask.at.every((t) => isNum(t) && t >= 0))) {
throw new ExportError('at: a list of seconds');
@@ -817,12 +827,12 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
/** Render the film (or `target`) to `out`, with progress. @param {ExportJob} job @param {string} target @param {string} out @param {Record<string, unknown>} opts @param {AbortSignal} signal */
const renderTo = (job, target, out, opts, signal, share = 0.96) => {
const range = job.ask.range ? [`${num(job.ask.range[0])}-${num(job.ask.range[1])}`] : [];
- return render([target, ...range], { ...opts, out, signal, onProgress: frames(job, share) });
+ return render([target, ...range], { ...opts, ...(job.ask.ranges ? { ranges: job.ask.ranges } : {}), out, signal, onProgress: frames(job, share) });
};
/** @param {ExportJob} job @param {string} root @param {string} dir @param {AbortSignal} signal */
async function exportVideo(job, root, dir, signal) {
- const ask = /** @type {VideoAsk & { range?: [number, number] }} */ (job.ask);
+ const ask = /** @type {VideoAsk & { range?: [number, number], ranges?: [number, number][] }} */ (job.ask);
const codec = ask.codec ?? 'h264';
const alpha = ALPHA_CODECS.has(codec);
const clip = ask.clip ? await clipFilm(root, ask.clip) : null;
@@ -862,6 +872,8 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
const out = freeFile(dir, baseName(job.name, ask), CODEC_EXT[codec]);
if (codec !== 'png') {
const part = partialOf(out, job.id);
+ /** @type {[number, number][] | null} The ranges actually drawn, at the output's rate and within the film. */
+ let selectedRanges = null;
update(job, { out: part, outputs: [part] });
try {
if (codec === 'hevc_alpha') {
@@ -869,11 +881,15 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
parts and adding the sound) drops its alpha layer's parameter sets, and no Apple app opens it then. Drawn
first as a quick PNG with its sound (the same frames, as many browsers as any render), then encoded */
const frames = join(/** @type {string} */ (scratch), 'frames.mov');
- await renderTo(job, target, frames, { ...opts, format: { ...QUICK_PNG, pix: `${place.vf},format=rgba` } }, signal, 0.85);
+ const rendered = await renderTo(job, target, frames, { ...opts, format: { ...QUICK_PNG, pix: `${place.vf},format=rgba` } }, signal, 0.85);
+ selectedRanges = rendered.ranges ?? null;
update(job, { phase: 'encoding', progress: 0.86, rate: 0, etaMs: null });
const { format } = encoding(codec, quality, size, fps ?? 30, have);
await run(['-i', frames, '-map', '0:v:0', '-map', '0:a?', '-vf', /** @type {{ pix: string }} */ (format).pix, ...format.video, '-c:a', 'copy', part], signal);
- } else await renderTo(job, target, part, opts, signal);
+ } else {
+ const rendered = await renderTo(job, target, part, opts, signal);
+ selectedRanges = rendered.ranges ?? null;
+ }
} catch (e) {
/* the graphics chip's encoder gave up partway (a driver, a size it does not take, sessions or memory it ran out
of): the rest of this launch encodes without it, starting with this export again */
@@ -881,7 +897,8 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
broken(hw);
({ encoder, opts } = how(null));
update(job, { encoder, framesDone: 0, progress: 0, etaMs: null });
- await renderTo(job, target, part, opts, signal);
+ const rendered = await renderTo(job, target, part, opts, signal);
+ selectedRanges = rendered.ranges ?? null;
}
await renameSafely(part, out);
update(job, { out, outputs: [out] });
@@ -889,7 +906,8 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
/* the subtitles as a file beside it, timed to the part exported */
if (ask.sidecar) {
const { cues } = await subtitlesOf(root);
- const part = ask.range ? filmSubtitleCuesInRange(cues, ask.range[0] * 1000, ask.range[1] * 1000) : cues;
+ const selected = selectedRanges?.map(([from, to]) => /** @type {[number, number]} */ ([from * 1000, to * 1000]));
+ const part = selected ? filmSubtitleCuesInRanges(cues, selected) : ask.range ? filmSubtitleCuesInRange(cues, ask.range[0] * 1000, ask.range[1] * 1000) : cues;
const text = ask.sidecar === 'vtt' ? filmSubtitleVtt(part) : filmSubtitleSrt(part);
if (text) {
const file = `${out.slice(0, -CODEC_EXT[codec].length)}.${ask.sidecar}`;
@@ -951,7 +969,7 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
/** @param {ExportJob} job @param {string} root @param {string} dir @param {AbortSignal} signal */
async function exportSound(job, root, dir, signal) {
- const ask = /** @type {AudioAsk & { range?: [number, number] }} */ (job.ask);
+ const ask = /** @type {AudioAsk & { range?: [number, number], ranges?: [number, number][] }} */ (job.ask);
const format = ask.format ?? 'wav';
const codec = SOUND_CODECS[format];
if (format === 'mp3' && !(await encoders()).has('libmp3lame')) throw new ExportError('this computer\'s ffmpeg has no MP3 encoder (libmp3lame)');
@@ -961,8 +979,11 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
const meta = probe.film.meta;
/* a page without a duration has no end (and no sound: a page has none) */
const length = meta.duration ?? Infinity;
- const [from, to] = ask.range ? [ask.range[0], Math.min(ask.range[1], length)] : [0, length];
- const clips = await filmSound(probe, from);
+ const selected = ask.ranges?.map(([from, to]) => ({ from, to: Math.min(to, length) }));
+ if (selected?.some((part) => part.to <= part.from)) throw new ExportError('a selected range is outside the film');
+ const [from, to] = selected ? [0, selected.reduce((n, part) => n + part.to - part.from, 0)] : ask.range ? [ask.range[0], Math.min(ask.range[1], length)] : [0, length];
+ const allClips = await filmSound(probe, selected ? 0 : from);
+ const clips = selected ? selectionClips(allClips, selected) : allClips;
if (!clips.length) throw new ExportError('this film has no sound');
/** @type {{ suffix: string, clips: typeof clips }[]} */
const plan = [];
@@ -1017,15 +1038,20 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
if (meta.duration == null && !picked) throw new ExportError('this page has no duration, so it has no middle or end: say which moments to export');
const length = meta.duration ?? Infinity;
const end = Math.max(0, length - 1e-3);
+ /* the film's scenes: a still or a slide is named by the one it is in (a page's speaker notes) */
+ const cuts = ask.kind === 'poster' ? []
+ : [.../** @type {{ id: string, at: number, end: number }[] | null} */ (await probe.film.page.evaluate(() => /** @type {any} */ (window).__filmCuts?.() ?? null)) ?? []]
+ .sort((a, b) => a.at - b.at);
+ /** the scene showing at `t`: of those that do, the one that started last */
+ const sceneAt = (/** @type {number} */ t) => cuts.findLast((c) => c.at <= t && t < c.end)?.id ?? '';
/** @type {{ t: number, label: string }[]} */
let moments;
if (ask.kind === 'poster') moments = [{ t: Math.min(end, ask.at ?? length / 2), label: '' }];
- else if (ask.at?.length) moments = ask.at.map((t) => ({ t: Math.min(end, t), label: '' }));
+ else if (ask.at?.length) moments = ask.at.map((t) => ({ t: Math.min(end, t), label: sceneAt(Math.min(end, t)) }));
else {
- const cuts = /** @type {{ id: string, at: number, end: number }[] | null} */ (await probe.film.page.evaluate(() => /** @type {any} */ (window).__filmCuts?.() ?? null));
moments = [];
let lastAt = -Infinity;
- for (const c of [...(cuts ?? [])].sort((a, b) => a.at - b.at)) {
+ for (const c of cuts) {
if (!(c.end > c.at) || c.at >= length || c.at - lastAt < 0.4) continue;
lastAt = c.at;
moments.push({ t: Math.min(end, (c.at + Math.min(c.end, length)) / 2), label: c.id });
@@ -1068,17 +1094,28 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
const { files } = await stillFrames(job, root, ask, ext, scratch, signal);
update(job, { phase: 'finishing' });
const base = baseName(job.name, ask);
- if (files.length === 1) {
- const out = freeFile(dir, ask.kind === 'stills' ? `${base} ${files[0].name.replace(/\.\w+$/, '')}` : base, ext);
- await writeFile(out, readFileSync(files[0].file));
- update(job, { out, outputs: [out] });
- } else {
+ const archive = ask.kind === 'stills' && (ask.as === 'zip' || (ask.as !== 'files' && files.length > 1));
+ if (archive) {
const out = freeFile(dir, base, '.zip');
const part = partialOf(out, job.id);
update(job, { out: part, outputs: [part] });
await zipFiles(part, files, signal);
await renameSafely(part, out);
update(job, { out, outputs: [out] });
+ } else {
+ /** @type {string[]} */
+ const outputs = [];
+ for (const file of files) {
+ if (signal.aborted) throw new Error('cancelled');
+ const out = freeFile(dir, ask.kind === 'stills' ? `${base} ${file.name.replace(/\.\w+$/, '')}` : base, ext);
+ const part = partialOf(out, job.id);
+ outputs.push(part);
+ update(job, { out: outputs[0], outputs: [...outputs] });
+ await copyFile(file.file, part, fsConstants.COPYFILE_FICLONE);
+ await renameSafely(part, out);
+ outputs[outputs.length - 1] = out;
+ update(job, { out: outputs[0], outputs: [...outputs] });
+ }
}
} finally {
await tidy(scratch);
@@ -1110,9 +1147,9 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
/** The film's subtitles as a file. @param {ExportJob} job @param {string} root @param {string} dir */
async function exportSubtitles(job, root, dir) {
- const ask = /** @type {SubtitlesAsk & { range?: [number, number] }} */ (job.ask);
+ const ask = /** @type {SubtitlesAsk & { range?: [number, number], ranges?: [number, number][] }} */ (job.ask);
const { cues: all } = await subtitlesOf(root);
- const cues = ask.range ? filmSubtitleCuesInRange(all, ask.range[0] * 1000, ask.range[1] * 1000) : all;
+ const cues = ask.ranges ? filmSubtitleCuesInRanges(all, ask.ranges.map(([from, to]) => [from * 1000, to * 1000])) : ask.range ? filmSubtitleCuesInRange(all, ask.range[0] * 1000, ask.range[1] * 1000) : all;
const format = ask.format ?? 'srt';
const text = format === 'vtt' ? filmSubtitleVtt(cues) : format === 'txt' ? filmSubtitleTranscript(cues) : filmSubtitleSrt(cues);
if (!text) throw new ExportError('this film has no subtitles');
@@ -1573,7 +1610,8 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
* @param {{ id: string, name: string, path: string }} project @param {{ jobs?: unknown, folder?: unknown }} body
*/
startAll(project, body) {
- if (!Array.isArray(body?.jobs) || !body.jobs.length || body.jobs.length > 24) throw new ExportError('jobs: a list of 1 to 24 exports');
+ /* Up to 100 selected stretches for each of the destinations a single export could already queue. */
+ if (!Array.isArray(body?.jobs) || !body.jobs.length || body.jobs.length > 2400) throw new ExportError('jobs: a list of 1 to 2400 exports');
const asks = body.jobs.map((ask) => checked(/** @type {ExportAsk} */ (ask)));
const folder = folderOf(body.folder);
/* asks the same but for their name (platforms that take the same frame, size and rate: 抖音, 快手, 视频号) are
@@ -1626,7 +1664,7 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo
* render (src/render.mjs) in a process of its own (render-worker.mjs), as an editor's export runs apart from the editor:
* what breaks in its browsers or encoders ends that export, said in its error, and never Studio. Same arguments and
* result as render; `signal` asks it to stop, and it is ended if it has not after a few seconds.
- * @param {string[]} args @param {Record<string, any>} opts @returns {Promise<{ out: string, encoder: string, lines: string[] }>}
+ * @param {string[]} args @param {Record<string, any>} opts @returns {Promise<{ out: string, encoder: string, lines: string[], ranges?: [number, number][] }>}
*/
function render(args, opts) {
const { signal, onProgress, ...rest } = opts;
diff --git a/packages/openfilm/studio/server/exports.test.mjs b/packages/openfilm/studio/server/exports.test.mjs
index 1eec09b..167018f 100644
--- a/packages/openfilm/studio/server/exports.test.mjs
+++ b/packages/openfilm/studio/server/exports.test.mjs
@@ -26,6 +26,10 @@ function children(parent, pattern) {
if (listed.status !== 0) throw new Error(`the process list did not answer: ${listed.error?.message ?? listed.stderr}`);
return listed.stdout.split(/\r?\n/).filter((line) => new RegExp(pattern).test(line.slice(line.indexOf(' ') + 1))).map((line) => Number(line.split(' ')[0]));
}
+/** End a process as a crash would; one gone already (a browser's helper, ended with the browser) is ended. */
+function end(pid) {
+ try { process.kill(pid, 'SIGKILL'); } catch (e) { if (/** @type {NodeJS.ErrnoException} */ (e).code !== 'ESRCH') throw e; }
+}
/* the tests that end an export's processes find them in the process list, which on Windows (WMI) can stop answering */
const processes = { skip: process.platform === 'win32' && (() => { try { children(process.pid, '.'); return false; } catch { return 'the process list does not answer'; } })() };
let root, scratch;
@@ -246,7 +250,7 @@ test('a video whose browser is ended partway, as a crash would end it, is drawn
if (!browsers.length) await new Promise((r) => setTimeout(r, 25));
}
assert.ok(browsers.length, 'the film draws in a browser of the render process');
- for (const pid of browsers) process.kill(pid, 'SIGKILL');
+ for (const pid of browsers) end(pid);
const done = await ended(exports, job);
assert.equal(done.status, 'done', done.error);
});
@@ -265,7 +269,7 @@ test('a cancelled export stops and leaves no file, and a bad ask is refused befo
assert.ok(!existsSync(running.out), 'the half-written file is gone');
assert.deepEqual(readdirSync(exportsRoot()).filter((n) => n.startsWith('Cancel') || n.includes('.partial-')), [], 'nothing under its name, nothing half made');
for (const bad of [{ kind: 'pdf' }, { kind: 'video', range: [3, 1] }, { kind: 'video', codec: 'av1' }, { kind: 'video', frame: '9:1' }, { kind: 'video', frame: 'wide' },
- { kind: 'audio', mix: false }, { kind: 'stills', range: [0, 1] }, { kind: 'gif', width: 5000 }, { kind: 'subtitles', format: 'ass' },
+ { kind: 'audio', mix: false }, { kind: 'stills', range: [0, 1] }, { kind: 'stills', as: 'pdf' }, { kind: 'gif', width: 5000 }, { kind: 'subtitles', format: 'ass' },
{ kind: 'slides', format: 'key' }, { kind: 'slides', range: [0, 1] }, { kind: 'nle', fps: 500 }, { kind: 'nle', audio: 'mix' }, { kind: 'nle', range: [0, 1] },
{ kind: 'nle', format: 'fcpxml', alpha: 'png' }, { kind: 'nle', alpha: 'auto' }, { kind: 'nle', format: 'jianying', alpha: 'hevc_alpha' }, { kind: 'nle', format: 'jianying', alpha: 'prores4444' }]) {
assert.throws(() => exports.start(project(), bad), ExportError, JSON.stringify(bad));
@@ -467,6 +471,9 @@ test('scene stills: the middle of each picture clip, zipped; a poster: one frame
const stills = await exported({ kind: 'stills', format: 'png', shortEdge: 90 });
assert.equal(stills.out, join(exportsRoot(), 'Tiny stills.zip'));
assert.deepEqual(zipNames(stills.out).names, ['01 title.png', '02 badge.png']);
+ /* the moments picked, each named by the scene it is in: of two showing, the one that started last */
+ const picked = await exported({ kind: 'stills', format: 'png', shortEdge: 90, at: [0.2, 0.7, 0.9] }, 'Picked');
+ assert.deepEqual(zipNames(picked.out).names, ['01 title.png', '02 badge.png', '03 badge.png']);
const poster = await exported({ kind: 'poster', format: 'jpg', at: 0.25, frame: '1:1', shortEdge: 100 });
assert.equal(poster.out, join(exportsRoot(), 'Tiny poster.jpg'));
const jpg = readFileSync(poster.out);
@@ -474,6 +481,20 @@ test('scene stills: the middle of each picture clip, zipped; a poster: one frame
assert.equal(probe(poster.out, 'stream=width,height'), '100,100');
});
+test('picked frames export as separate images or an explicit zip, including a one-frame zip', ffmpeg, async () => {
+ const files = await exported({ kind: 'stills', as: 'files', format: 'png', shortEdge: 90, at: [0.2, 0.7] }, 'Separate');
+ assert.deepEqual(files.outputs.map((f) => basename(f)), ['Separate stills 01 title.png', 'Separate stills 02 badge.png']);
+ assert.equal(files.out, files.outputs[0]);
+ for (const file of files.outputs) assert.equal(probe(file, 'stream=width,height'), '160,90');
+ const original = readFileSync(files.outputs[0]);
+ const again = await exported({ kind: 'stills', as: 'files', format: 'png', shortEdge: 90, at: [0.2] }, 'Separate');
+ assert.notEqual(again.out, files.outputs[0], 'an existing image is never overwritten');
+ assert.deepEqual(readFileSync(files.outputs[0]), original);
+ const zip = await exported({ kind: 'stills', as: 'zip', format: 'jpg', shortEdge: 90, at: [0.2] }, 'One zipped');
+ assert.ok(zip.out.endsWith('.zip'));
+ assert.deepEqual(zipNames(zip.out).names, ['01 title.jpg']);
+});
+
test('several exports at once, into a folder of the person\'s; one wrong ask queues none', ffmpeg, async () => {
const exports = createExports();
const folder = join(scratch, 'Mine', 'Deliveries');
@@ -530,6 +551,10 @@ test('slides: a PowerPoint deck and a PDF, one page per scene, the scene named i
assert.ok(parts.has(resolved), `${name} → ${resolved}`);
}
}
+ /* the moments picked, a page each, each named by its scene */
+ const picked = zipEntries((await exported({ kind: 'slides', format: 'pptx', shortEdge: 180, at: [0.2, 0.3, 0.7] }, 'Picked')).out);
+ assert.ok(picked.has('ppt/slides/slide3.xml') && !picked.has('ppt/slides/slide4.xml'), 'three moments, three slides');
+ assert.deepEqual([1, 2, 3].map((n) => picked.get(`ppt/notesSlides/notesSlide${n}.xml`).toString().match(/<a:t>([^<]*)<\/a:t>/)?.[1]), ['title', 'title', 'badge']);
const pdf = await exported({ kind: 'slides', format: 'pdf', shortEdge: 180, frame: '1:1' }, 'Deck');
assert.equal(pdf.out, join(exportsRoot(), 'Deck.pdf'));
const bytes = readFileSync(pdf.out).toString('latin1');
@@ -1094,7 +1119,7 @@ test('剪映: the pages\' browsers, ended partway as a crash would end them, are
assert.ok(worker, 'the pages draw in a process of their own');
const browsers = children(worker, 'chrom');
assert.ok(browsers.length, 'with browsers of its own');
- for (const pid of browsers) process.kill(pid, 'SIGKILL');
+ for (const pid of browsers) end(pid);
const done = await ended(exports, job);
assert.equal(done.status, 'done', done.error);
for (const id of ['a', 'b', 'c']) assert.equal(frameCount(join(dirname(done.out), 'media', `${id}.mov`)), 120, `${id}: every frame`);
diff --git a/packages/openfilm/studio/server/film-subtitle.mjs b/packages/openfilm/studio/server/film-subtitle.mjs
index a677cee..428bfcb 100644
--- a/packages/openfilm/studio/server/film-subtitle.mjs
+++ b/packages/openfilm/studio/server/film-subtitle.mjs
@@ -783,3 +783,16 @@ export function filmSubtitleCuesInRange(cues, fromMs, toMs) {
}
return out;
}
+
+/** Cues for selected stretches joined in list order, each moved to its position in the result.
+ * @template {FilmSubtitleCue} T
+ * @param {readonly T[]} cues @param {readonly (readonly [number, number])[]} ranges @returns {T[]}
+ */
+export function filmSubtitleCuesInRanges(cues, ranges) {
+ let offset = 0;
+ return ranges.flatMap(([from, to]) => {
+ const part = filmSubtitleCuesInRange(cues, from, to).map((cue) => ({ ...cue, startMs: cue.startMs + offset }));
+ offset += to - from;
+ return part;
+ });
+}
diff --git a/packages/openfilm/studio/server/history-delete.test.mjs b/packages/openfilm/studio/server/history-delete.test.mjs
new file mode 100644
index 0000000..25d5821
--- /dev/null
+++ b/packages/openfilm/studio/server/history-delete.test.mjs
@@ -0,0 +1,90 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { checkoutVersion, copyVersion, deleteVersions, log, recoverVersions, saveVersion, status, versionFilesChanged } from './history.mjs';
+import { createHistoryPreviews } from './history-previews.mjs';
+
+const fixture = async () => {
+ const root = mkdtempSync(join(tmpdir(), 'of-history-delete-'));
+ writeFileSync(join(root, 'film.html'), '<meta name="viewport" content="width=800, height=450"><section><iframe src="title.html" time="0 2"></iframe></section>');
+ const commits = [];
+ for (const name of ['First', 'Second', 'Third', 'Fourth']) {
+ writeFileSync(join(root, 'title.html'), name);
+ commits.push(await saveVersion(root, { message: name }));
+ }
+ return { root, commits, close: () => rmSync(root, { recursive: true, force: true }) };
+};
+const refused = (promise, code) => assert.rejects(promise, (error) => error.code === code);
+
+test('selected versions leave the active list, preserve pagination and parent links, and can be recovered', async () => {
+ const { root, commits: [first, second, third, fourth], close } = await fixture();
+ try {
+ writeFileSync(join(root, 'title.html'), 'Unsaved work');
+ const before = await status(root), mtime = statSync(join(root, 'title.html')).mtimeMs;
+ assert.deepEqual((await deleteVersions(root, [second.slice(0, 10), third])).commits.sort(), [second, third].sort());
+ assert.deepEqual(await status(root), before, 'deleting records never changes HEAD or current edits');
+ assert.equal(statSync(join(root, 'title.html')).mtimeMs, mtime);
+ const active = await log(root, { includeDeletedCount: true });
+ assert.deepEqual(active.versions.map((version) => version.commit), [fourth, first]);
+ assert.deepEqual(active.versions[0].parents, [first], 'deleted ancestors do not leave broken graph links');
+ assert.equal(active.deletedCount, 2);
+ assert.equal((await log(root, { limit: 1 })).more, true);
+ assert.equal((await log(root, { limit: 2 })).more, false);
+ assert.deepEqual((await log(root, { deleted: true })).versions.map((version) => version.commit).sort(), [second, third].sort());
+ assert.equal((await log(root, { deleted: true, limit: 1 })).more, true);
+ await refused(checkoutVersion(root, second), 'deleted');
+ await refused(versionFilesChanged(root, third), 'deleted');
+ assert.ok((await versionFilesChanged(root, fourth)).length > 0, 'surviving version details remain readable');
+ await recoverVersions(root, [second, third]);
+ assert.equal((await log(root, { includeDeletedCount: true })).deletedCount, 0);
+ assert.deepEqual((await log(root)).versions.map((version) => version.commit), [fourth, third, second, first]);
+ assert.deepEqual(await status(root), before);
+ const copy = mkdtempSync(join(tmpdir(), 'of-recovered-version-'));
+ try { await copyVersion(root, second, copy); assert.equal(readFileSync(join(copy, 'title.html'), 'utf8'), 'Second'); }
+ finally { rmSync(copy, { recursive: true, force: true }); }
+ } finally { close(); }
+});
+
+test('current versions and malformed batches are refused atomically, including after checking out an older version', async () => {
+ const { root, commits: [first, second, , fourth], close } = await fixture();
+ try {
+ for (const selection of [[], ['--all'], ['../film.html'], [null], [first, '0'.repeat(40)], Array.from({ length: 1001 }, () => first)]) {
+ await assert.rejects(deleteVersions(root, selection));
+ assert.equal(existsSync(join(root, '.film/history/deleted-versions.json')), false);
+ }
+ await refused(deleteVersions(root, [first, fourth]), 'current');
+ assert.equal((await log(root)).versions.length, 4);
+ await checkoutVersion(root, first);
+ await refused(deleteVersions(root, [first, second]), 'current');
+ await deleteVersions(root, [second]);
+ writeFileSync(join(root, 'title.html'), 'New branch');
+ const newer = await saveVersion(root, { message: 'New work' });
+ const history = await log(root);
+ assert.equal(history.versions[0].commit, newer);
+ assert.equal(history.versions.some((version) => version.commit === second), false, 'new saves do not bring deleted records back');
+ await recoverVersions(root, [second]);
+ assert.ok((await log(root)).versions.some((version) => version.commit === second));
+ } finally { close(); }
+});
+
+test('deleting invalidates prepared previews; recovery rebuilds them without touching a separate Git repository', async () => {
+ const { root, commits: [first], close } = await fixture();
+ const previews = createHistoryPreviews();
+ try {
+ execFileSync('git', ['init', '--quiet', '--template='], { cwd: root });
+ const personalHead = readFileSync(join(root, '.git/HEAD'), 'utf8');
+ const prepared = await previews.get(root, first);
+ await deleteVersions(root, [first]);
+ await previews.invalidate(root, [first]);
+ assert.equal(existsSync(prepared.path), false);
+ await refused(previews.get(root, first), 'deleted');
+ await recoverVersions(root, [first]);
+ const recovered = await previews.get(root, first);
+ assert.equal(readFileSync(join(recovered.path, 'title.html'), 'utf8'), 'First');
+ assert.equal(readFileSync(join(root, '.git/HEAD'), 'utf8'), personalHead);
+ assert.deepEqual(execFileSync('git', ['for-each-ref'], { cwd: root, encoding: 'utf8' }), '');
+ } finally { await previews.close(); close(); }
+});
diff --git a/packages/openfilm/studio/server/history-deleted.mjs b/packages/openfilm/studio/server/history-deleted.mjs
new file mode 100644
index 0000000..441c60c
--- /dev/null
+++ b/packages/openfilm/studio/server/history-deleted.mjs
@@ -0,0 +1,33 @@
+// @ts-check
+/** Deleted version records stay recoverable without rewriting the project's Git commits or touching its files. */
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { writeAtomic } from './atomic.mjs';
+import { HistoryError } from './history-store.mjs';
+
+/** @typedef {{ at: number, parents: string[] }} DeletedVersion */
+const fullId = (/** @type {unknown} */ id) => typeof id === 'string' && /^[0-9a-f]{40,64}$/.test(id);
+
+/** @param {string} gitDir @returns {Promise<Map<string, DeletedVersion>>} */
+export async function readDeletedVersions(gitDir) {
+ let text;
+ try { text = await readFile(join(gitDir, 'deleted-versions.json'), 'utf8'); }
+ catch (error) { if (/** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT') return new Map(); throw error; }
+ try {
+ const data = JSON.parse(text);
+ if (data.format !== 1 || !data.commits || typeof data.commits !== 'object' || Array.isArray(data.commits)) throw new Error('format');
+ /** @type {Map<string, DeletedVersion>} */
+ const records = new Map();
+ for (const [id, raw] of Object.entries(data.commits)) {
+ const entry = /** @type {DeletedVersion} */ (raw);
+ if (!fullId(id) || !entry || !Number.isFinite(entry.at) || !Array.isArray(entry.parents) || !entry.parents.every(fullId)) throw new Error('record');
+ records.set(id, { at: entry.at, parents: [...entry.parents] });
+ }
+ return records;
+ } catch { throw new HistoryError('the deleted-version list could not be read', 500); }
+}
+
+/** @param {string} gitDir @param {Map<string, DeletedVersion>} records */
+export function writeDeletedVersions(gitDir, records) {
+ return writeAtomic(join(gitDir, 'deleted-versions.json'), JSON.stringify({ format: 1, commits: Object.fromEntries(records) }) + '\n');
+}
diff --git a/packages/openfilm/studio/server/history-migrate.mjs b/packages/openfilm/studio/server/history-migrate.mjs
index 35ba18f..241e40c 100644
--- a/packages/openfilm/studio/server/history-migrate.mjs
+++ b/packages/openfilm/studio/server/history-migrate.mjs
@@ -4,8 +4,10 @@
* the folder but video and files over 20 MB, each commit with `git add --all`: renders, frames, logs and other takes
* went in, and footage did not. Each of its versions is made again holding the film's files only (closure.mjs), with
* the same message, author and time; media in it moves to the store (history-store.mjs); the changes left on a branch
- * (stashes) become parked versions. On the branch checked out, a "History cleanup" commit then adds what the film uses
- * that history never had (its videos), as they are in the folder now.
+ * (stashes) become parked versions. On the branch checked out, an "upgrade" version then adds what a version holds now
+ * (history.mjs versionFiles) that the converted ones do not (the film's videos, the folder's other code and notes), as
+ * they are in the folder now. A history of format 2 kept the film's files only: the same is added to it
+ * (upgradeHistory).
*
* It is made beside the old one (`.film/history-next`), borrowing its objects, then packed on its own and checked
* before it takes its place. The old history goes to the Trash, so nothing is lost if something went wrong; the
@@ -14,7 +16,7 @@
*/
import { spawn } from 'node:child_process';
import { createHash } from 'node:crypto';
-import { createWriteStream, existsSync } from 'node:fs';
+import { createWriteStream, existsSync, readFileSync } from 'node:fs';
import { chmod, copyFile, mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { tempPath, replaceFile } from './atomic.mjs';
@@ -25,19 +27,52 @@ import {
import { TOOL_DIR } from './projects.mjs';
import { moveToTrash } from './trash.mjs';
-/** The format of a history Studio made: 2 keeps the film's files only, media outside git. */
-export const FORMAT = 2;
+/** The format of a history Studio made: 2 kept the film's files only, media outside git; 3 keeps the project's files. */
+export const FORMAT = 3;
const MARKER = 'openfilm.json';
-export const CLEANUP_MESSAGE = 'History cleanup: the film\'s files only, its media kept from now on';
+/** The message of the version that adds what an earlier history did not keep (history.mjs Kind 'upgrade'). */
+export const UPGRADE_MESSAGE = 'Kept all the project\'s files\n\nOpenfilm-Version: upgrade\n';
/** The format of the history in `gitDir`: 1 for one an earlier Studio made (no marker), else what its marker says. */
export function formatOf(/** @type {string} */ gitDir) {
if (!existsSync(join(gitDir, MARKER))) return 1;
- return FORMAT;
+ try { return Number(JSON.parse(readFileSync(join(gitDir, MARKER), 'utf8')).format) || 2; } catch { return 2; }
}
export const markFormat = (/** @type {string} */ gitDir) => writeFile(join(gitDir, MARKER), `${JSON.stringify({ format: FORMAT })}\n`);
+/**
+ * Add the folder's `paths` to the version `head` (`base`, as read), as an "upgrade" version on `headRef`.
+ * @param {import('./history-store.mjs').Repo} repo @param {string} headRef @param {string} head
+ * @param {import('./history-store.mjs').Version} base @param {string[]} paths
+ */
+async function addToVersion(repo, headRef, head, base, paths) {
+ const added = await keepFiles(repo, paths, null);
+ if (!added.size) return;
+ const tree = await writeTree(repo, new Map([...base, ...added]));
+ const made = (await repo.git(['commit-tree', tree, '-p', head, '-F', '-'], { input: UPGRADE_MESSAGE })).trim();
+ await repo.git(['update-ref', headRef, made]);
+}
+
+/**
+ * A history of format 2 (the film's files only) brought to this one: on the branch checked out, what a version holds
+ * now beyond the film's files (`files`: history.mjs versionFiles) is added as an "upgrade" version, so nothing looks
+ * changed that was not. The person's files are not written.
+ * @param {string} root @param {string} gitDir @param {(root: string) => Promise<Map<string, number>>} files
+ */
+export async function upgradeHistory(root, gitDir, files) {
+ const repo = openRepo(root, gitDir);
+ const head = (await repo.git(['rev-parse', '--verify', '--quiet', 'HEAD']).catch(() => '')).trim();
+ const headRef = (await repo.git(['symbolic-ref', '--quiet', 'HEAD']).catch(() => '')).trim();
+ if (head && headRef) {
+ const base = await readVersion(repo, head);
+ const closure = await filmClosure(folderView(root));
+ const missing = [...(await files(root)).keys()].filter((path) => !base.has(path) && !closure.has(path));
+ if (missing.length) await addToVersion(repo, headRef, head, base, missing);
+ }
+ await markFormat(gitDir);
+}
+
/** A blob of the old history written to the store (streamed: it may be large), named by its sha256. */
function extract(/** @type {import('./history-store.mjs').Repo} */ old, /** @type {string} */ storeDir, /** @type {string} */ oid) {
return new Promise((done, fail) => {
@@ -80,10 +115,12 @@ function rewriteCommit(/** @type {string} */ raw, /** @type {string} */ tree, /*
}
/**
- * Bring the history in `gitDir` (an earlier Studio's) up to date; see the header. `progress` hears how far it is.
- * @param {string} root @param {string} gitDir @param {import('./history-store.mjs').Progress} [progress]
+ * Bring the history in `gitDir` (an earlier Studio's) up to date; see the header. `files` reads what a version of the
+ * folder holds now (history.mjs versionFiles); `progress` hears how far it is.
+ * @param {string} root @param {string} gitDir @param {(root: string) => Promise<Map<string, number>>} files
+ * @param {import('./history-store.mjs').Progress} [progress]
*/
-export async function migrateHistory(root, gitDir, progress) {
+export async function migrateHistory(root, gitDir, files, progress) {
const old = openRepo(root, gitDir);
const refLines = (await old.git(['for-each-ref', '--format=%(objectname)%1f%(*objectname)%1f%(refname)', 'refs/heads', 'refs/tags'])).split('\n').filter(Boolean);
const stashList = await old.git(['stash', 'list', '--format=%H%x1f%gs']).catch(() => '');
@@ -196,19 +233,14 @@ export async function migrateHistory(root, gitDir, progress) {
progress?.({ phase: 'migrate', done: ++done, total });
}
- /* the branch checked out: what its film uses that history never had (video, mostly), from the folder as it is */
+ /* the branch checked out: what a version holds now that the converted one does not (its video, mostly, and the
+ folder's other code and notes), from the folder as it is */
const tip = (await old.git(['rev-parse', '--verify', '--quiet', 'HEAD']).catch(() => '')).trim();
if (tip && headRef && mapped.has(tip)) {
- const version = await readVersion(old, tip);
- const closure = await filmClosure(versionView(old, version, folderView(root)));
- const missing = [...closure.keys()].filter((path) => !version.has(path));
- if (missing.length) {
- const base = await readVersion(neu, /** @type {string} */ (mapped.get(tip)));
- const added = await keepFiles(neu, missing, null);
- const tree = await writeTree(neu, new Map([...base, ...added]));
- const made = (await git(['commit-tree', tree, '-p', /** @type {string} */ (mapped.get(tip)), '-m', CLEANUP_MESSAGE])).trim();
- await git(['update-ref', headRef, made]);
- }
+ const closure = await filmClosure(versionView(old, await readVersion(old, tip), folderView(root)));
+ const base = await readVersion(neu, /** @type {string} */ (mapped.get(tip)));
+ const missing = [...new Set([...closure.keys(), ...(await files(root)).keys()])].filter((path) => !base.has(path));
+ if (missing.length) await addToVersion(neu, headRef, /** @type {string} */ (mapped.get(tip)), base, missing);
}
progress?.({ phase: 'migrate', done: ++done, total });
diff --git a/packages/openfilm/studio/server/history-previews.mjs b/packages/openfilm/studio/server/history-previews.mjs
new file mode 100644
index 0000000..674b438
--- /dev/null
+++ b/packages/openfilm/studio/server/history-previews.mjs
@@ -0,0 +1,73 @@
+// @ts-check
+/**
+ * Read-only copies of saved versions on the film origin. Previews never check out the working project or borrow its
+ * current media. Repeated requests share a preparation; failed copies can be retried. Copies live outside the
+ * project, so its watcher never sees them; the last KEPT are kept, and they are removed when Studio closes.
+ */
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { copyVersion, HistoryError } from './history.mjs';
+
+/** How many versions' copies are kept: each is the whole project, footage included (a full copy on Windows and Linux). */
+const KEPT = 3;
+
+export function createHistoryPreviews() {
+ /** @type {Map<string, Promise<{ path: string, missing: string[] }>>} the copies, the one used last at the end */
+ const copies = new Map();
+ let closed = false;
+ /* the copies used longest ago go, past KEPT: one looked at again is copied again */
+ const trim = () => {
+ for (const [key, copy] of [...copies].slice(0, Math.max(0, copies.size - KEPT))) {
+ copies.delete(key);
+ void copy.then((prepared) => rm(prepared.path, { recursive: true, force: true }), () => {});
+ }
+ };
+ return {
+ /** @param {string} root @param {string} commit */
+ get(root, commit) {
+ if (closed) throw new HistoryError('version previews are closed', 503);
+ if (!/^[0-9a-f]{7,64}$/.test(commit)) throw new HistoryError('which version?', 400, 'none');
+ const key = `${root}\0${commit}`;
+ let copy = copies.get(key);
+ /* used again: the last used */
+ if (copy) { copies.delete(key); copies.set(key, copy); }
+ if (!copy) {
+ copy = (async () => {
+ const path = await mkdtemp(join(tmpdir(), 'openfilm-history-preview-'));
+ try {
+ const { missing } = await copyVersion(root, commit, path);
+ return { path, missing };
+ } catch (e) {
+ await rm(path, { recursive: true, force: true });
+ copies.delete(key);
+ throw e;
+ }
+ })();
+ copies.set(key, copy);
+ trim();
+ }
+ return copy;
+ },
+ /** Forget deleted versions, including their prepared read-only files.
+ * @param {string} root @param {string[]} commits
+ */
+ async invalidate(root, commits) {
+ const pending = [...copies.entries()].filter(([key]) => {
+ const [folder, id] = key.split('\0');
+ return folder === root && commits.some((commit) => commit.startsWith(id));
+ });
+ for (const [key] of pending) copies.delete(key);
+ await Promise.all(pending.map(async ([, copy]) => {
+ const prepared = await copy.catch(() => null);
+ if (prepared) await rm(prepared.path, { recursive: true, force: true });
+ }));
+ },
+ async close() {
+ closed = true;
+ const prepared = await Promise.allSettled(copies.values());
+ await Promise.all(prepared.map((r) => r.status === 'fulfilled' ? rm(r.value.path, { recursive: true, force: true }) : undefined));
+ copies.clear();
+ },
+ };
+}
diff --git a/packages/openfilm/studio/server/history-previews.test.mjs b/packages/openfilm/studio/server/history-previews.test.mjs
new file mode 100644
index 0000000..b029247
--- /dev/null
+++ b/packages/openfilm/studio/server/history-previews.test.mjs
@@ -0,0 +1,61 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createHistoryPreviews } from './history-previews.mjs';
+import { saveVersion } from './history.mjs';
+
+test('version preview copies are shared, failures can be retried, and shutdown removes completed copies', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'of-history-preview-test-'));
+ const previews = createHistoryPreviews();
+ try {
+ writeFileSync(join(root, 'film.html'), '<meta name="viewport" content="width=800, height=450"><section><iframe src="title.html" at="0" time="0 2"></iframe></section>');
+ writeFileSync(join(root, 'title.html'), 'saved');
+ const commit = await saveVersion(root);
+ writeFileSync(join(root, 'title.html'), 'current');
+ const first = previews.get(root, commit);
+ assert.equal(first, previews.get(root, commit), 'in-flight preparations are deduplicated');
+ const copy = await first;
+ assert.equal(readFileSync(join(copy.path, 'title.html'), 'utf8'), 'saved');
+ assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'current');
+ const missing = '0'.repeat(40);
+ const failed = previews.get(root, missing);
+ await assert.rejects(failed, (e) => e.status === 404);
+ const retry = previews.get(root, missing);
+ assert.notEqual(retry, failed, 'a failed preparation is not cached');
+ await assert.rejects(retry, (e) => e.status === 404);
+ await previews.close();
+ assert.equal(existsSync(copy.path), false);
+ assert.throws(() => previews.get(root, commit), (e) => e.status === 503);
+ } finally {
+ await previews.close();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('only the last three versions previewed keep their copies: one looked at again is the newest, the oldest goes', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'of-history-preview-kept-'));
+ const previews = createHistoryPreviews();
+ try {
+ writeFileSync(join(root, 'film.html'), '<meta name="viewport" content="width=800, height=450"><section><iframe src="title.html" at="0" time="0 2"></iframe></section>');
+ const commits = [];
+ for (const n of [1, 2, 3, 4]) {
+ writeFileSync(join(root, 'title.html'), `version ${n}`);
+ commits.push(await saveVersion(root));
+ }
+ const [one, two, three, four] = commits;
+ const first = await previews.get(root, one);
+ const second = await previews.get(root, two);
+ await previews.get(root, three);
+ /* the first looked at again: the second is now the one used longest ago */
+ assert.equal(await previews.get(root, one), first);
+ await previews.get(root, four);
+ await new Promise((r) => setTimeout(r, 200));
+ assert.equal(existsSync(second.path), false, 'the copy used longest ago is removed');
+ assert.equal(existsSync(first.path), true);
+ } finally {
+ await previews.close();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/packages/openfilm/studio/server/history.mjs b/packages/openfilm/studio/server/history.mjs
index ddb920d..aee3737 100644
--- a/packages/openfilm/studio/server/history.mjs
+++ b/packages/openfilm/studio/server/history.mjs
@@ -3,42 +3,43 @@
* A project's version history: a git repository of its own in `.film/history`. It never touches a `.git` the folder
* may have (the person's or the agent's own repository): every call names this one explicitly.
*
- * What a version holds is the film: film.html and every file it uses, as closure.mjs reads them from it (each clip's
- * file, what its pages load, subtitles beside its media, Studio's settings and markers of it). Restoring a version
- * brings all of that back exactly, footage included. Files the film does not use (renders, frames, logs, other takes)
- * are not in history, and history never writes, moves or deletes them. Media is kept by its content outside git, as
- * clones where the disk can (history-store.mjs), so keeping a version of a large project takes moments and no space.
+ * A version holds the project: film.html and every file it uses (closure.mjs), and every other file of the folder
+ * that is not a video, a sound or a picture the film does not use, nor larger than UNUSED_MAX (versionFiles). So the
+ * pages, their code, data and fonts, Studio's settings and markers of the film, and the agent's notes and scripts are
+ * all kept, however a page names them; renders, frames and other takes are not, and history never writes, moves or
+ * deletes them. Media is kept by its content outside git, as clones where the disk can (history-store.mjs), so keeping
+ * a version of a large project takes moments and no space.
*
- * It is git, as a person knows it from GitHub: commits on branches, uncommitted changes, switching, merging. Every
- * commit is the person's — made when they commit, with their message — and nothing here commits on its own: going back
- * to a version puts its files in the folder as uncommitted changes, switching branches leaves the changes on the
- * branch they were made on (a parked version, put back on coming back) or brings them along. What a commit changed is
- * told in the film's terms (scenes and sounds added, removed, edited: `summary`), not as files; smaller steps are the
- * editor's undo, not commits.
+ * It is git as VS Code's Source Control shows it: the folder's changes against the version checked out, committed
+ * as a version (with the person's message, or on its own while they work when they asked for that:
+ * auto-versions.mjs), and every version drawn as a graph. Checking one out makes the folder hold its files, as git
+ * does, and makes no version of its own; with changes it is refused unless they are discarded. A commit on a version
+ * checked out on its own goes on main from there; main's later versions stay, on a line of their own. What a version
+ * changed is also told in the film's terms (scenes and sounds added, removed, edited: `summary`), which decides
+ * whether one is saved on its own.
+ *
+ * Each version is a commit. Its message is the person's (or what kind of version it is) and a trailer saying its
+ * kind: `Openfilm-Version: named` and so on (Kind). Histories of earlier editions had branches, names as tags and
+ * changes parked on branches: their versions are listed too, and any of them can be checked out.
*
* Every action takes an optional `onProgress` (history-store.mjs Progress) to say how far it is; a history an earlier
* Studio made is brought up to date on first use (history-migrate.mjs).
*/
-import { execFile } from 'node:child_process';
-import { randomBytes } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
-import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
+import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
-import { promisify } from 'node:util';
import { FILM_FILE, kindOf, readFilmFile } from '../../src/film-doc.mjs';
-import { clipFile, filmClosure, folderView, projectFiles } from './closure.mjs';
-import { FORMAT, formatOf, markFormat, migrateHistory } from './history-migrate.mjs';
+import { STUDIO_STATE, clipFile, filmClosure, folderView, isMediaFile, projectFiles } from './closure.mjs';
+import { FORMAT, formatOf, markFormat, migrateHistory, upgradeHistory } from './history-migrate.mjs';
import {
- HistoryError, gitRun, keepFiles, openRepo, readBlobs, readVersion, sameAs, writeFiles, writeTree,
+ HistoryError, gitRun, keepFiles, openRepo, readVersion, sameAs, writeFiles, writeTree,
} from './history-store.mjs';
import { TOOL_DIR } from './projects.mjs';
import { moveToTrash } from './trash.mjs';
+import { readDeletedVersions, writeDeletedVersions } from './history-deleted.mjs';
export { HistoryError };
-const run = promisify(execFile);
-
/** @typedef {import('./history-store.mjs').Progress} Progress */
/** @typedef {{ onProgress?: Progress }} Options */
@@ -49,11 +50,12 @@ const historyDir = (/** @type {string} */ root) => join(root, TOOL_DIR, 'history
* taken from the history's settings (its `core.worktree` is where the folder was when the history was made, and a
* project moved or renamed since would have every call fail). Its hooks are never run (history-store.mjs gitRun).
*/
-async function git(/** @type {string} */ root, /** @type {string[]} */ args) {
+async function git(/** @type {string} */ root, /** @type {string[]} */ args, /** @type {{ input?: string }} */ o = {}) {
const gitDir = historyDir(root);
if (!ownHistory(gitDir)) throw new HistoryError('this project\'s version history was not made by Studio, so Studio does not use it', 409);
- await followMove(root, gitDir);
- return gitRun(root, gitDir, args);
+ /* a history being made has no settings of its own to put right yet */
+ if (existsSync(join(gitDir, 'HEAD'))) await followMove(root, gitDir);
+ return gitRun(root, gitDir, args, o);
}
/**
@@ -105,6 +107,11 @@ async function ready(root, progress) {
if (!existsSync(root)) throw new HistoryError('the project\'s folder is not there', 404, 'none');
const gitDir = historyDir(root);
if (existsSync(gitDir) && !ownHistory(gitDir)) await rename(gitDir, `${gitDir}-from-elsewhere-${Date.now()}`);
+ /* git takes a folder for a history only with these in it, empty as they are until the first version: a copy or a
+ sync that leaves out empty folders would have every call fail ("not in a git directory") */
+ if (existsSync(join(gitDir, 'HEAD'))) {
+ for (const dir of ['objects', join('refs', 'heads'), join('refs', 'tags')]) await mkdir(join(gitDir, dir), { recursive: true });
+ }
if (!existsSync(join(gitDir, 'HEAD'))) {
await mkdir(join(gitDir, 'info'), { recursive: true });
await git(root, ['init', '--quiet', '--template=', '--initial-branch=main', '--object-format=sha1']);
@@ -115,7 +122,9 @@ async function ready(root, progress) {
await markFormat(gitDir);
} else {
await followMove(root, gitDir);
- if (formatOf(gitDir) < FORMAT) await migrateHistory(root, gitDir, progress);
+ const format = formatOf(gitDir);
+ if (format < 2) await migrateHistory(root, gitDir, versionFiles, progress);
+ else if (format < FORMAT) await upgradeHistory(root, gitDir, versionFiles);
}
return openRepo(root, gitDir);
}
@@ -163,6 +172,26 @@ const headOf = async (/** @type {string} */ root) => (await git(root, ['rev-pars
/** The branch checked out (a new history's first branch has no commit yet). */
const currentBranch = async (/** @type {string} */ root) => (await git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => '')).trim();
+/** Larger than this, a file the film does not use is not kept (a disk image, an archive, a project of another app). */
+export const UNUSED_MAX = 50 << 20;
+
+/* what is never the project's own, wherever it is: a tool's dot folder or file, what builds and packages make */
+const NOT_KEPT = /(^|\/)(\.[^/]*|node_modules|dist|build)(\/|$)/;
+
+/**
+ * The files a version of the folder at `root` holds: path → size. The film's (filmClosure), and the folder's others
+ * but videos, sounds and pictures, files over UNUSED_MAX, and what NOT_KEPT says. None without a film.html.
+ * @param {string} root @returns {Promise<Map<string, number>>}
+ */
+export async function versionFiles(root) {
+ const held = await filmClosure(folderView(root));
+ if (!held.size) return held;
+ for (const [path, size] of await projectFiles(root)) {
+ if (!held.has(path) && !isMediaFile(path) && size <= UNUSED_MAX && !NOT_KEPT.test(path)) held.set(path, size);
+ }
+ return held;
+}
+
/** @typedef {{ path: string, change: 'added' | 'modified' | 'deleted' }} Change */
/**
@@ -172,7 +201,7 @@ const currentBranch = async (/** @type {string} */ root) => (await git(root, ['s
* @returns {Promise<{ changes: Change[], closure: Map<string, number> }>}
*/
async function changesNow(repo, head, progress) {
- const closure = await filmClosure(folderView(repo.root));
+ const closure = await versionFiles(repo.root);
const was = head ? await readVersion(repo, head) : new Map();
/** @type {Change[]} */
const changes = [];
@@ -214,9 +243,13 @@ function clipsOf(/** @type {string} */ text) {
* @typedef {{ scenes: Counts, sounds: Counts, stage: boolean, other: boolean }} Summary
* what changed, as the film tells it: its scenes (the clips with a picture) and its sounds, each added, removed or
* edited (moved, trimmed, restyled, or its file changed); `stage`: the picture's size; `other`: files no clip names
- * changed (a page's shared code, a font): the picture may look different though no clip did
+ * changed that a page may draw with (its shared code, a font, a picture): the picture may look different though no
+ * clip did. Notes, scripts and Studio's markers change nothing of the picture.
*/
+/* what a page may draw with */
+const PICTURE = /\.(html?|css|[cm]?js|json|svg|woff2?|ttf|otf|png|jpe?g|gif|webp|avif|mp4|mov|m4v|webm|mp3|m4a|wav|aac|ogg|opus|flac)$/i;
+
/**
* What changed from `from` (a commit; null: nothing, the start) to `to` (a commit; null: the folder now), `paths` being
* the files that changed between them.
@@ -240,443 +273,346 @@ async function summarize(root, from, to, paths) {
for (const [id, clip] of before.clips) {
if (!after.clips.has(id)) (clip.sound ? summary.sounds : summary.scenes).removed += 1;
}
- summary.other = paths.some((path) => path !== FILM_FILE && !files.has(path));
+ summary.other = paths.some((path) => path !== FILM_FILE && !files.has(path) && PICTURE.test(path) && !path.startsWith(`${TOOL_DIR}/`));
return summary;
}
-/** @type {Map<string, Summary>} what each commit changed (a commit never changes, nor does what it changed) */
-const summaries = new Map();
-
-/** What `commit` changed from its first parent. */
-async function commitSummary(/** @type {string} */ root, /** @type {string} */ commit, /** @type {string | undefined} */ parent) {
- const key = `${root}\0${commit}`;
- const known = summaries.get(key);
- if (known) return known;
- const paths = (await git(root, ['diff-tree', '--root', '--no-commit-id', '--name-only', '-r', '-z', commit])).split('\0').filter(Boolean);
- const summary = await summarize(root, parent ?? null, commit, paths);
- summaries.set(key, summary);
- if (summaries.size > 5000) summaries.delete(summaries.keys().next().value ?? '');
- return summary;
-}
-
-/* a branch's uncommitted changes, left on it when another was switched to: a version of its own under this ref */
-const parkedRef = (/** @type {string} */ branch) => `refs/openfilm/parked/${branch}`;
-
-/** The branches whose changes are parked. */
-async function parkedBranches(/** @type {string} */ root) {
- const list = await git(root, ['for-each-ref', '--format=%(refname)', 'refs/openfilm/parked']).catch(() => '');
- return new Set(list.split('\n').map((s) => s.slice('refs/openfilm/parked/'.length)).filter(Boolean));
-}
+/** Whether `summary` changes the film: a scene or a sound, the picture's size, or a file its pages draw with. */
+const filmChanged = (/** @type {Summary} */ summary) => summary.stage || summary.other
+ || [summary.scenes, summary.sounds].some((c) => c.added || c.removed || c.edited);
/**
- * @typedef {{ name: string, commit: string, at: number, message: string, current: boolean, parked: boolean }} Branch
- * @typedef {{ held: number, heldBytes: number, ignored: number }} Files
- * the film's files now (in history once committed), and how many other files the folder has (never in history)
- * @typedef {{ branch: string, head: string | null, branches: Branch[], changes: { count: number, summary: Summary } | null, files: Files }} Status
+ * @typedef {{ head: string | null, branch: string | null, changes: { count: number, summary: Summary, files: Change[] } | null }} Status
+ * `branch`: the branch checked out (null: a version checked out on its own, as git's detached HEAD)
*/
+/** How many changed files a status lists (the count says how many there are). */
+const LISTED = 500;
+
/**
- * Where the history is: the branch checked out, every branch (the most recently committed first), the uncommitted
- * changes (null: none), and what the film holds against what the folder has. A project never committed has no branch
- * to list yet, and all it holds is uncommitted.
+ * Where the history is: the version checked out (null: none yet), and what the folder holds that it does not: the
+ * files added, modified and deleted, and what that does to the film (null: nothing). A project never saved holds all
+ * it has as changes.
* @param {string} root @param {Options} [o] @returns {Promise<Status>}
*/
export function status(root, { onProgress } = {}) {
return queued(root, async () => {
const repo = await ready(root, throttled(onProgress));
- const branch = await currentBranch(root) || 'main';
const head = await headOf(root);
- const parked = await parkedBranches(root);
- const refs = await git(root, ['for-each-ref', '--sort=-committerdate', '--format=%(refname:short)%1f%(objectname)%1f%(committerdate:unix)%1f%(contents:subject)', 'refs/heads']);
- const branches = refs.split('\n').filter(Boolean).map((line) => {
- const [name, commit, at, message] = line.split('\x1f');
- return { name, commit, at: Number(at) * 1000, message: shownMessage(message), current: name === branch, parked: parked.has(name) };
- });
- const { changes: paths, closure } = await changesNow(repo, head);
- const changes = paths.length ? { count: paths.length, summary: await summarize(root, head, null, paths.map((p) => p.path)) } : null;
- const all = await projectFiles(root, { sizes: false });
- const files = {
- held: closure.size,
- heldBytes: [...closure.values()].reduce((n, s) => n + s, 0),
- ignored: [...all.keys()].filter((p) => !closure.has(p)).length,
- };
- return { branch, head, branches, changes, files };
+ const { changes: files } = await changesNow(repo, head);
+ const changes = files.length
+ ? { count: files.length, summary: await summarize(root, head, null, files.map((p) => p.path)), files: files.slice(0, LISTED) }
+ : null;
+ return { head, branch: head ? (await currentBranch(root)) || null : 'main', changes };
});
}
/**
- * The film's files now, and the folder's other files (which history leaves alone), each with its size, by path.
- * @param {string} root @returns {Promise<{ held: { path: string, size: number }[], ignored: { path: string, size: number }[] }>}
+ * What a version is, as its trailer says: `named` (saved by the person with a message), `saved` (by the person,
+ * without one), `auto` (on its own while they worked), `agent` (on its own before an agent's turn), `upgrade` (what an
+ * earlier history did not keep, added when it was brought up to date), `parked` (changes an earlier edition left on a
+ * branch); `before-restore` and `restore` from an edition that saved a version to restore one. A commit with no trailer
+ * is the person's, named by its message.
+ * @typedef {'named' | 'saved' | 'auto' | 'agent' | 'before-restore' | 'restore' | 'upgrade' | 'parked'} Kind
*/
-export function historyFiles(root) {
- return queued(root, async () => {
- if (!existsSync(root)) throw new HistoryError('the project\'s folder is not there', 404, 'none');
- const closure = await filmClosure(folderView(root));
- const all = await projectFiles(root);
- const list = (/** @type {Iterable<[string, number]>} */ m) => [...m].map(([path, size]) => ({ path, size })).sort((a, b) => a.path.localeCompare(b.path));
- return { held: list(closure), ignored: list([...all].filter(([p]) => !closure.has(p))) };
- });
-}
+const KINDS = new Set(['named', 'saved', 'auto', 'agent', 'before-restore', 'restore', 'upgrade', 'parked']);
-/**
- * A commit's message as it is shown: a commit Studio's earlier editions made says what it was in their words
- * (`studio: named "Final"`), shown as the name the person gave it.
- */
-function shownMessage(/** @type {string} */ subject) {
- const named = /^studio: named "(.*)"$/.exec(subject);
- return named ? named[1] : subject;
-}
+/** The subject a version of `kind` gets when the person gave it no message (what plain git shows of it). */
+const SUBJECT = { saved: 'Saved version', auto: 'Auto-saved', agent: 'Before agent\'s turn', upgrade: 'Kept all the project\'s files' };
+
+/** A version's message: its subject, then the trailer saying its kind. */
+const messageOf = (/** @type {Kind} */ kind, /** @type {string} */ text) =>
+ `${text || SUBJECT[/** @type {keyof typeof SUBJECT} */ (kind)] || kind}\n\nOpenfilm-Version: ${kind}\n`;
-/* a tag's name is anything a person typed in an earlier edition (a named version); stored encoded */
-const decodeName = (/** @type {string} */ tag) => (tag.startsWith('v-') ? Buffer.from(tag.slice(2), 'base64url').toString('utf8') : tag);
+/* a name an earlier edition gave a version: a tag on it, `v-<the name, base64url>[.<the version's first hex>]` */
+const decodeName = (/** @type {string} */ tag) => (tag.startsWith('v-') ? Buffer.from(tag.slice(2).split('.')[0], 'base64url').toString('utf8') : tag);
/**
- * @typedef {{ commit: string, parents: string[], at: number, message: string, body: string, tags: string[], summary: Summary }} Commit
+ * @typedef {{ commit: string, parents: string[], at: number, kind: Kind, name: string, restored: string | null }} Version
+ * `name`: the person's message ('' when there is none: it is told by its kind); `restored`: the version a
+ * `restore` of an earlier edition brought back
*/
+/* where the versions are: every branch, what HEAD is on, the line a commit on a checked-out version moved aside
+ (`kept`), and what an earlier edition parked */
+const ALL_VERSIONS = ['HEAD', '--branches', '--glob=refs/openfilm/kept/*', '--glob=refs/openfilm/parked/*'];
+
/**
- * The commits of `ref` (a branch; the one checked out by default), newest first, each with what it changed.
- * @param {string} root @param {{ ref?: string, limit?: number } & Options} [options] @returns {Promise<Commit[]>}
+ * The versions of the project, newest first, `limit` of them (more: there are older ones), each with its parents, so
+ * they draw as a graph.
+ * @param {string} root @param {{ limit?: number, deleted?: boolean, includeDeletedCount?: boolean } & Options} [options] @returns {Promise<{ versions: Version[], more: boolean, deletedCount?: number }>}
*/
-export function log(root, { ref = 'HEAD', limit = 100, onProgress } = {}) {
+export function log(root, { limit = 50, deleted = false, includeDeletedCount = false, onProgress } = {}) {
return queued(root, async () => {
const gitDir = historyDir(root);
- if (!existsSync(join(gitDir, 'HEAD')) || !ownHistory(gitDir)) return [];
+ if (!existsSync(join(gitDir, 'HEAD')) || !ownHistory(gitDir)) return { versions: [], more: false, ...(includeDeletedCount ? { deletedCount: 0 } : {}) };
await ready(root, throttled(onProgress));
- if (!(await headOf(root))) return [];
- /** @type {Map<string, string[]>} */
- const tags = new Map();
- const refs = await git(root, ['for-each-ref', '--format=%(objectname)%1f%(*objectname)%1f%(refname:strip=2)', 'refs/tags']);
+ const head = await headOf(root);
+ if (!head) return { versions: [], more: false, ...(includeDeletedCount ? { deletedCount: 0 } : {}) };
+ const removed = await readDeletedVersions(gitDir);
+ removed.delete(head);
+ const extra = includeDeletedCount ? { deletedCount: removed.size } : {};
+ if (deleted && !removed.size) return { versions: [], more: false, ...extra };
+ /** @type {Map<string, string>} */
+ const names = new Map();
+ const refs = await git(root, ['for-each-ref', '--sort=creatordate', '--format=%(objectname)%1f%(*objectname)%1f%(refname:strip=2)', 'refs/tags']);
for (const line of refs.split('\n')) {
const [tag, peeled, name] = line.split('\x1f');
const sha = peeled || tag;
- if (sha && name) tags.set(sha, [...(tags.get(sha) ?? []), decodeName(name)]);
+ if (sha && name) names.set(sha, decodeName(name));
}
- const out = await git(root, ['log', `--max-count=${limit}`, '--format=%H%x1f%P%x1f%ct%x1f%s%x1f%b%x1e', ref, '--']);
- const commits = [];
+ const format = '--format=%H%x1f%P%x1f%ct%x1f%s%x1f%b%x1e';
+ const out = deleted
+ ? await git(root, ['log', '--no-walk=sorted', format, '--stdin', '--'], { input: [...removed.keys()].join('\n') + '\n' })
+ : await git(root, ['log', '--date-order', `--max-count=${limit + removed.size + 1}`, format, ...ALL_VERSIONS, '--']);
+ /** @type {Version[]} */
+ const versions = [];
for (const record of out.split('\x1e')) {
- const [commit, parents, at, subject, body] = record.replace(/^\n/, '').split('\x1f');
+ const [commit, parents = '', at, subject = '', body = ''] = record.replace(/^\n/, '').split('\x1f');
if (!commit) continue;
- const parentList = parents ? parents.split(' ').filter(Boolean) : [];
- commits.push({
- commit, parents: parentList, at: Number(at) * 1000, message: shownMessage(subject ?? ''), body: (body ?? '').trim(),
- tags: tags.get(commit) ?? [], summary: await commitSummary(root, commit, parentList[0]),
+ if (!deleted && removed.has(commit)) continue;
+ if (deleted && !removed.has(commit)) continue;
+ const said = /^Openfilm-Version: (\S+)$/m.exec(body)?.[1] ?? '';
+ const parked = /^parked: (.*)$/.exec(subject);
+ const kind = /** @type {Kind} */ (KINDS.has(said) ? said : parked ? 'parked' : 'named');
+ const own = kind === 'named' ? shownMessage(subject) : kind === 'parked' ? (parked?.[1] ?? '') : '';
+ versions.push({
+ commit, parents: parents.split(' ').filter(Boolean), at: Number(at) * 1000, kind, name: names.get(commit) ?? own,
+ restored: /^Openfilm-Restored: ([0-9a-f]+)$/m.exec(body)?.[1] ?? null,
});
}
- return commits;
+ /** @param {string} id @returns {string[]} */
+ const nearest = (id) => {
+ const pending = [id], seen = new Set();
+ /** @type {string[]} */
+ const found = [];
+ while (pending.length) {
+ const next = pending.pop();
+ if (!next || seen.has(next)) continue;
+ seen.add(next);
+ const entry = removed.get(next);
+ if (entry) pending.push(...[...entry.parents].reverse()); else found.push(next);
+ }
+ return found;
+ };
+ const visible = deleted ? versions : versions.map((version) => ({ ...version, parents: [...new Set(version.parents.flatMap((parent) => nearest(parent)))] }));
+ return { versions: visible.slice(0, limit), more: visible.length > limit, ...extra };
});
}
-/* ── changing it: only ever when the person asks ─────────────────────────── */
+/**
+ * A commit's message as it is shown: a commit Studio's earlier editions made says what it was in their words
+ * (`studio: named "Final"`), shown as the name the person gave it.
+ */
+function shownMessage(/** @type {string} */ subject) {
+ const named = /^studio: named "(.*)"$/.exec(subject);
+ return named ? named[1] : subject;
+}
-/** A commit or branch the person named, as git knows it: its full id, or a 404. */
-async function resolveCommit(/** @type {string} */ root, /** @type {string} */ rev) {
- if (!/^[0-9a-f]{7,64}$/.test(String(rev))) throw new HistoryError('which commit?', 400, 'none');
- const full = (await git(root, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`]).catch(() => '')).trim();
- if (!full) throw new HistoryError('no such commit', 404, 'none');
- return full;
+/**
+ * The files a version changed from the one before it (its first parent; none: all it holds is added), as git's
+ * status letters say them.
+ * @param {string} root @param {string} commit @returns {Promise<Change[]>}
+ */
+export function versionFilesChanged(root, commit) {
+ return queued(root, async () => {
+ await ready(root);
+ const full = await resolveCommit(root, commit);
+ const out = await git(root, ['diff-tree', '--root', '--no-commit-id', '--name-status', '-r', '-z', '--no-renames', full]);
+ const parts = out.split('\0').filter(Boolean);
+ /** @type {Change[]} */
+ const files = [];
+ const CHANGE = /** @type {Record<string, Change['change']>} */ ({ A: 'added', M: 'modified', D: 'deleted', T: 'modified' });
+ for (let i = 0; i + 1 < parts.length; i += 2) files.push({ path: parts[i + 1], change: CHANGE[parts[i][0]] ?? 'modified' });
+ return files;
+ });
}
-const needClean = async (/** @type {import('./history-store.mjs').Repo} */ repo, /** @type {string | null} */ head) => {
- if ((await changesNow(repo, head)).changes.length) throw new HistoryError('there are uncommitted changes: commit or discard them first', 409, 'dirty');
-};
+/* ── changing it ─────────────────────────────────────────────────────────── */
-/** The film's files in the folder now, kept as a tree (`head`: the version they are compared with). */
-async function keepFolder(/** @type {import('./history-store.mjs').Repo} */ repo, /** @type {string | null} */ head, /** @type {Progress | undefined} */ progress) {
- const closure = await filmClosure(folderView(repo.root));
- const version = await keepFiles(repo, closure.keys(), head ? await readVersion(repo, head) : null, progress);
- return writeTree(repo, version);
+/** A version the person named, as git knows it: its full id, or a 404. */
+async function resolveCommit(/** @type {string} */ root, /** @type {string} */ rev) {
+ if (!/^[0-9a-f]{7,64}$/.test(String(rev))) throw new HistoryError('which version?', 400, 'none');
+ const full = (await git(root, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`]).catch(() => '')).trim();
+ if (!full) throw new HistoryError('no such version', 404, 'none');
+ if ((await readDeletedVersions(historyDir(root))).has(full) && full !== await headOf(root)) throw new HistoryError('this version was deleted; recover it first', 409, 'deleted');
+ return full;
}
-/**
- * Commit the uncommitted changes with the person's message (its first line is the summary). The first commit of a
- * project takes all the film holds. Returns the commit.
- * @param {string} root @param {string} message @param {Options} [o]
+/** Resolve a bounded selection in one Git call, before changing any records.
+ * @param {string} root @param {unknown} commits @returns {Promise<Map<string, string[]>>}
*/
-export function commitChanges(root, message, { onProgress } = {}) {
- return queued(root, async () => {
- const text = String(message ?? '').trim().slice(0, 5000);
- if (!text) throw new HistoryError('a commit needs a message', 400, 'message');
- const progress = throttled(onProgress);
- const repo = await ready(root, progress);
- const head = await headOf(root);
- const branchRef = (await git(root, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => '')).trim() || 'refs/heads/main';
- const tree = await keepFolder(repo, head, progress);
- if (head && tree === (await git(root, ['rev-parse', `${head}^{tree}`])).trim()) throw new HistoryError('nothing to commit', 409, 'nothing');
- const commit = (await git(root, ['commit-tree', tree, ...(head ? ['-p', head] : []), '-m', text])).trim();
- await git(root, ['update-ref', '-m', `commit: ${text.split('\n')[0]}`, branchRef, commit, head ?? '']);
- maintain(root);
- return commit;
- });
+async function selectedCommits(root, commits) {
+ if (!Array.isArray(commits) || !commits.length || commits.length > 1000 || !commits.every((id) => typeof id === 'string' && /^[0-9a-f]{7,64}$/.test(id))) throw new HistoryError('select 1 to 1000 versions', 400, 'selection');
+ const ids = [...new Set(/** @type {string[]} */ (commits))];
+ const out = await git(root, ['log', '--no-walk=unsorted', '--format=%H%x1f%P', '--stdin', '--'], { input: ids.join('\n') + '\n' }).catch(() => { throw new HistoryError('no such version', 404, 'none'); });
+ const found = new Map(out.trim().split('\n').filter(Boolean).map((line) => { const [id, parents = ''] = line.split('\x1f'); return [id, parents.split(' ').filter(Boolean)]; }));
+ if (ids.some((id) => ![...found.keys()].some((full) => full.startsWith(id)))) throw new HistoryError('no such version', 404, 'none');
+ return found;
}
-/**
- * Put the film back as the last commit holds it: its files written where they differ. A file the film takes that the
- * commit does not have (made since, beside a page) goes to the trash, as a delete in Studio does, so a discard can be
- * taken back from there; files the film does not use are left as they are.
- * @param {string} root @param {Options} [o]
+/** Move selected records out of the active history. Snapshots stay recoverable; no working file or Git ref moves.
+ * @param {string} root @param {unknown} commits
*/
-export function discardChanges(root, { onProgress } = {}) {
+export function deleteVersions(root, commits) {
return queued(root, async () => {
- const progress = throttled(onProgress);
- const repo = await ready(root, progress);
- const head = await headOf(root);
- if (!head) throw new HistoryError('nothing is committed yet, so there is nothing to go back to', 409, 'nothing');
- await writeFiles(repo, await readVersion(repo, head), { progress });
- for (const { path, change } of (await changesNow(repo, head)).changes) {
- if (change === 'added' && existsSync(join(root, path))) await moveToTrash(join(root, path));
- }
+ await ready(root);
+ const found = await selectedCommits(root, commits);
+ if (found.has(await headOf(root) ?? '')) throw new HistoryError('the version currently in use cannot be deleted', 409, 'current');
+ const removed = await readDeletedVersions(historyDir(root));
+ for (const [id, parents] of found) if (!removed.has(id)) removed.set(id, { at: Date.now(), parents });
+ await writeDeletedVersions(historyDir(root), removed);
+ return { commits: [...found.keys()] };
});
}
-/**
- * Put the film as `commit` holds it, as uncommitted changes on the branch checked out: nothing is committed, the
- * person commits them (or discards them, which comes back to where it was). Asked with uncommitted changes, it says so
- * ('dirty'): they would be lost. Returns the commit, and the media it holds that could not be found (none, unless
- * the history's store lost some).
- * @param {string} root @param {string} commit @param {Options} [o]
+/** Recover deleted records, without checking them out or changing any files.
+ * @param {string} root @param {unknown} commits
*/
-export function restoreCommit(root, commit, { onProgress } = {}) {
+export function recoverVersions(root, commits) {
return queued(root, async () => {
- const progress = throttled(onProgress);
- const repo = await ready(root, progress);
- const full = await resolveCommit(root, commit);
- await needClean(repo, await headOf(root));
- const { missing } = await writeFiles(repo, await readVersion(repo, full), { progress });
- return { commit: full, missing };
+ await ready(root);
+ const found = await selectedCommits(root, commits);
+ const removed = await readDeletedVersions(historyDir(root));
+ for (const id of found.keys()) removed.delete(id);
+ await writeDeletedVersions(historyDir(root), removed);
+ return { commits: [...found.keys()] };
});
}
-/** A branch name a person typed, as git takes it (spaces become dashes), or a 400. */
-async function branchName(/** @type {string} */ root, /** @type {string} */ name) {
- const clean = String(name ?? '').trim().replace(/\s+/g, '-');
- if (!clean || clean.length > 100) throw new HistoryError('a branch needs a name', 400, 'name');
- const ok = await git(root, ['check-ref-format', '--branch', clean]).then(() => true, () => false);
- if (!ok || clean.startsWith('-')) throw new HistoryError(`"${clean}" cannot be a branch name`, 400, 'name');
- return clean;
+/** The files a version holds, as they are in the folder now, kept as a tree (`head`: the version they are compared with). */
+async function keepFolder(/** @type {import('./history-store.mjs').Repo} */ repo, /** @type {string | null} */ head, /** @type {Progress | undefined} */ progress) {
+ const files = await versionFiles(repo.root);
+ const version = await keepFiles(repo, files.keys(), head ? await readVersion(repo, head) : null, progress);
+ return writeTree(repo, version);
}
-const branchExists = async (/** @type {string} */ root, /** @type {string} */ name) => Boolean(await git(root, ['rev-parse', '--verify', '--quiet', `refs/heads/${name}`]).catch(() => ''));
-
-/** The paths whose files differ between two versions. */
-function differing(/** @type {import('./history-store.mjs').Version} */ a, /** @type {import('./history-store.mjs').Version} */ b) {
- const out = new Set();
- for (const [path, e] of a) if (b.get(path)?.oid !== e.oid) out.add(path);
- for (const path of b.keys()) if (!a.has(path)) out.add(path);
- return out;
-}
+const treeOf = async (/** @type {string} */ root, /** @type {string} */ commit) => (await git(root, ['rev-parse', `${commit}^{tree}`])).trim();
+const isAncestor = (/** @type {string} */ root, /** @type {string} */ a, /** @type {string} */ b) => git(root, ['merge-base', '--is-ancestor', a, b]).then(() => true, () => false);
/**
- * Leave the film's uncommitted changes on `branch`: the folder's film kept as a version of its own (`parkedRef`),
- * put back when the branch is checked out again. An older one left there and not put back stays in its history.
+ * Commit the folder as a version. On a branch, it goes on it. On a version checked out on its own (detached), it goes
+ * on main from there, as the newest; main's versions after that one stay in the history, on a line of their own
+ * (`refs/openfilm/kept/<its tip>`), and main is checked out again. Null when the folder holds the version checked out.
+ * Not queued: the caller is.
+ * @param {import('./history-store.mjs').Repo} repo @param {Kind} kind @param {string} text @param {Progress} [progress]
*/
-async function park(/** @type {import('./history-store.mjs').Repo} */ repo, /** @type {string} */ branch, /** @type {string} */ head, /** @type {Progress | undefined} */ progress) {
+async function commitFolder(repo, kind, text, progress) {
+ const root = repo.root;
+ const head = await headOf(root);
const tree = await keepFolder(repo, head, progress);
- const older = (await git(repo.root, ['rev-parse', '--verify', '--quiet', parkedRef(branch)]).catch(() => '')).trim();
- const commit = (await git(repo.root, ['commit-tree', tree, '-p', head, ...(older ? ['-p', older] : []), '-m', `parked: ${branch}`])).trim();
- await git(repo.root, ['update-ref', parkedRef(branch), commit]);
-}
-
-/**
- * Put back the changes left on `branch`, if any, over the version `tip` now in the folder. False when they collide
- * (the branch changed the same files since, or `carried` changes did): they stay parked.
- * @param {import('./history-store.mjs').Repo} repo @param {string} branch @param {string} tip @param {Set<string>} carried @param {Progress} [progress]
- */
-async function unpark(repo, branch, tip, carried, progress) {
- const parked = (await git(repo.root, ['rev-parse', '--verify', '--quiet', parkedRef(branch)]).catch(() => '')).trim();
- if (!parked) return true;
- const base = (await git(repo.root, ['rev-parse', `${parked}^1`])).trim();
- const left = await readVersion(repo, parked);
- const changed = differing(await readVersion(repo, base), left);
- const moved = base === tip ? new Set() : differing(await readVersion(repo, base), await readVersion(repo, tip));
- if ([...changed].some((p) => moved.has(p) || carried.has(p))) return false;
- await writeFiles(repo, left, { paths: changed, progress });
- await git(repo.root, ['update-ref', '-d', parkedRef(branch)]);
- return true;
+ if (head && tree === await treeOf(root, head)) return null;
+ const commit = (await git(root, ['commit-tree', tree, ...(head ? ['-p', head] : []), '-F', '-'], { input: messageOf(kind, text) })).trim();
+ const branch = (await git(root, ['symbolic-ref', '--quiet', 'HEAD']).catch(() => '')).trim();
+ if (branch || !head) {
+ await git(root, ['update-ref', '-m', `${kind}: ${text || kind}`, branch || 'refs/heads/main', commit, head ?? '']);
+ } else {
+ const main = (await git(root, ['rev-parse', '--verify', '--quiet', 'refs/heads/main']).catch(() => '')).trim();
+ if (main && !(await isAncestor(root, main, commit))) await git(root, ['update-ref', `refs/openfilm/kept/${main}`, main]);
+ await git(root, ['update-ref', '-m', `${kind}: ${text || kind}`, 'refs/heads/main', commit]);
+ await git(root, ['symbolic-ref', 'HEAD', 'refs/heads/main']);
+ }
+ maintain(root);
+ return commit;
}
/**
- * Check out `target` (a branch, or `create` one first, from `from`: a commit; the one checked out by default). The
- * uncommitted changes are left on the branch they were made on (`carry` 'leave', put back when it is checked out again)
- * or brought along ('bring': refused with 'conflict' when they collide with what the other branch holds). Changes left
- * on `target` before come back. Returns whether they did (false: they collide and stay parked).
- * @param {string} root @param {{ target: string, create?: boolean, from?: string, carry?: 'leave' | 'bring' } & Options} o
+ * Commit the folder as a version. By the person: `message` is theirs (none: 'saved'); with nothing changed it is
+ * refused ('nothing'). On its own (`kind` 'auto' or 'agent'): null unless the film changed (filmChanged). Returns the
+ * version.
+ * @param {string} root @param {{ message?: string, kind?: 'auto' | 'agent' } & Options} [o] @returns {Promise<string | null>}
*/
-export function checkout(root, { target, create = false, from, carry = 'leave', onProgress }) {
+export function saveVersion(root, { message = '', kind, onProgress } = {}) {
return queued(root, async () => {
- const progress = throttled(onProgress);
- const repo = await ready(root, progress);
- const head = await headOf(root);
- if (!head) throw new HistoryError('commit once before making branches', 409, 'nothing');
- const name = await branchName(root, target);
- const here = await currentBranch(root);
- if (create && await branchExists(root, name)) throw new HistoryError(`a branch "${name}" exists already`, 409, 'exists');
- if (!create && !(await branchExists(root, name))) throw new HistoryError(`no branch "${name}"`, 404, 'none');
- if (!create && name === here) return true;
- const to = create ? (from ? await resolveCommit(root, from) : head) : (await git(root, ['rev-parse', `refs/heads/${name}`])).trim();
- const checkOut = async () => {
- if (create) await git(root, ['update-ref', '-m', `branch: from ${to}`, `refs/heads/${name}`, to, '']);
- await git(root, ['symbolic-ref', '-m', `checkout: to ${name}`, 'HEAD', `refs/heads/${name}`]);
- };
- /* a new branch where the folder is: the changes simply go with it, nothing to leave or bring */
- if (create && to === head) { await checkOut(); return true; }
- const { changes } = await changesNow(repo, head, progress);
- const dirty = new Set(changes.map((c) => c.path));
- const goal = await readVersion(repo, to);
- if (carry === 'bring' && dirty.size) {
- /* what the other branch holds differently from here, where the person changed it too: refused, nothing moved */
- const differ = differing(await readVersion(repo, head), goal);
- for (const path of dirty) {
- if (differ.has(path) && !(await sameAs(repo, path, goal.get(path)))) throw new HistoryError('the uncommitted changes collide with what that branch holds', 409, 'conflict');
- }
- await writeFiles(repo, goal, { paths: [...differ].filter((p) => !dirty.has(p)), progress });
- await checkOut();
- return unpark(repo, name, to, dirty, progress);
+ const text = String(message ?? '').trim().replace(/\s+/g, ' ').slice(0, 200);
+ const repo = await ready(root, throttled(onProgress));
+ /* on its own, only when the film changed: notes, logs and scripts an agent writes, or markers, are kept with the
+ next version, not one of their own */
+ if (kind) {
+ const head = await headOf(root);
+ const { changes } = await changesNow(repo, head);
+ if (!changes.length || !filmChanged(await summarize(root, head, null, changes.map((c) => c.path)))) return null;
}
- if (dirty.size && here) await park(repo, here, head, progress);
- await writeFiles(repo, goal, { progress });
- await checkOut();
- return unpark(repo, name, to, new Set(), progress);
+ const saved = await commitFolder(repo, kind ?? (text ? 'named' : 'saved'), kind ? '' : text, throttled(onProgress));
+ if (!saved && !kind) throw new HistoryError('nothing changed since the version checked out', 409, 'nothing');
+ return saved;
});
}
-/** Rename a branch (its parked changes go with it). */
-export function renameBranch(/** @type {string} */ root, /** @type {string} */ from, /** @type {string} */ to) {
- return queued(root, async () => {
- await ready(root);
- const old = await branchName(root, from);
- const name = await branchName(root, to);
- if (!(await branchExists(root, old))) throw new HistoryError(`no branch "${old}"`, 404, 'none');
- if (old === name) return name;
- if (await branchExists(root, name)) throw new HistoryError(`a branch "${name}" exists already`, 409, 'exists');
- await git(root, ['branch', '-m', old, name]);
- const parked = (await git(root, ['rev-parse', '--verify', '--quiet', parkedRef(old)]).catch(() => '')).trim();
- if (parked) {
- await git(root, ['update-ref', parkedRef(name), parked]);
- await git(root, ['update-ref', '-d', parkedRef(old)]);
- }
- return name;
- });
+/**
+ * Put the folder back as `head` holds it, `changes` (changesNow) being what differs: its files written where they
+ * differ, and a file the version does not have (made since) to the trash, as a delete in Studio does. Files the
+ * versions leave out are not touched.
+ * @param {import('./history-store.mjs').Repo} repo @param {import('./history-store.mjs').Version} version
+ * @param {Change[]} changes @param {Progress} [progress]
+ */
+async function putBack(repo, version, changes, progress) {
+ const { missing } = await writeFiles(repo, version, { progress });
+ for (const { path, change } of changes) {
+ if (change === 'added' && !version.has(path) && existsSync(join(repo.root, path))) await moveToTrash(join(repo.root, path));
+ }
+ /* Studio's state of the film (markers, settings, subtitle style) the version did not have: it had none */
+ for (const path of STUDIO_STATE) if (!version.has(path) && existsSync(join(repo.root, path))) await moveToTrash(join(repo.root, path));
+ return missing;
}
/**
- * Delete a branch (not the one checked out). One with commits on no other branch is refused ('unmerged', with how
- * many) unless `force`: those commits would be gone. Its parked changes go too.
- * @param {string} root @param {string} name @param {{ force?: boolean }} [o]
+ * Discard the changes: the folder as the version checked out holds it. Returns the media it holds that could not be
+ * found.
+ * @param {string} root @param {Options} [o]
*/
-export function deleteBranch(root, name, { force = false } = {}) {
+export function discardChanges(root, { onProgress } = {}) {
return queued(root, async () => {
- await ready(root);
- const branch = await branchName(root, name);
- if (!(await branchExists(root, branch))) throw new HistoryError(`no branch "${branch}"`, 404, 'none');
- if (branch === await currentBranch(root)) throw new HistoryError('the branch checked out cannot be deleted', 409, 'current');
- if (!force) {
- /* its commits no other branch has (`--exclude` takes a name as `--branches` sees it, without refs/heads/) */
- const only = Number((await git(root, ['rev-list', '--count', branch, '--not', `--exclude=${branch}`, '--branches'])).trim());
- if (only > 0) throw Object.assign(new HistoryError(`"${branch}" has ${only} commit(s) on no other branch`, 409, 'unmerged'), { commits: only });
- }
- await git(root, ['branch', '-D', branch]);
- await git(root, ['update-ref', '-d', parkedRef(branch)]).catch(() => {});
+ const progress = throttled(onProgress);
+ const repo = await ready(root, progress);
+ const head = await headOf(root);
+ if (!head) throw new HistoryError('nothing is committed yet, so there is nothing to go back to', 409, 'nothing');
+ const { changes } = await changesNow(repo, head);
+ return { missing: await putBack(repo, await readVersion(repo, head), changes, progress) };
});
}
/**
- * Merge the trees of `ours` and `theirs` from `base`, as `git merge` would, in a scratch index: what one side changed
- * is taken; where both changed one file, its text is merged line by line. What both changed in the same place (or a
- * media file both changed, or one changed and the other deleted) is a conflict, unless `prefer` says whose side wins.
- * Returns the tree.
- * @param {import('./history-store.mjs').Repo} repo @param {string} base @param {string} ours @param {string} theirs @param {'ours' | 'theirs'} [prefer]
+ * Check out `commit`, as git does: the folder holds its files (those of the version checked out that it does not
+ * have go to the trash) and it is where the next commit goes. No version is made. The branch whose tip it is is
+ * checked out; any other version, on its own (detached). With changes, refused ('dirty') unless `discard`: they would
+ * be lost. Returns the version, and the media it holds that could not be found.
+ * @param {string} root @param {string} commit @param {{ discard?: boolean } & Options} [o]
*/
-async function mergeTrees(repo, base, ours, theirs, prefer) {
- const index = join(repo.gitDir, `openfilm-index-${process.pid}-${randomBytes(4).toString('hex')}`);
- const env = { GIT_INDEX_FILE: index };
- const scratch = join(tmpdir(), `openfilm-merge-${randomBytes(6).toString('hex')}`);
- const conflict = () => new HistoryError('the two branches changed the same thing', 409, 'conflict');
- try {
- await repo.git(['read-tree', '-m', '-i', '--aggressive', base, ours, theirs], { env });
- const unmerged = await repo.git(['ls-files', '-u', '-z'], { env });
- /** @type {Map<string, Record<string, { mode: string, oid: string }>>} */
- const stages = new Map();
- for (const line of unmerged.split('\0')) {
- const tab = line.indexOf('\t');
- if (tab < 0) continue;
- const [mode, oid, stage] = line.slice(0, tab).split(' ');
- const path = line.slice(tab + 1);
- stages.set(path, { ...(stages.get(path) ?? {}), [stage]: { mode, oid } });
- }
- if (!stages.size) return (await repo.git(['write-tree'], { env })).trim();
- const [oursV, theirsV] = [await readVersion(repo, ours), await readVersion(repo, theirs)];
- const zero = '0'.repeat(repo.algo === 'sha256' ? 64 : 40);
- const lines = [];
- await mkdir(scratch, { recursive: true });
- for (const [path, s] of stages) {
- const [b, o, t] = [s['1'], s['2'], s['3']];
- const pick = prefer === 'ours' ? o : prefer === 'theirs' ? t : undefined;
- let result = /** @type {{ mode: string, oid: string } | null | undefined} */ (undefined);
- if (!o || !t || oursV.get(path)?.media || theirsV.get(path)?.media) {
- if (!prefer) throw conflict();
- result = pick ?? null;
- } else {
- const blobs = await readBlobs(repo, [o.oid, t.oid, ...(b ? [b.oid] : [])]);
- const files = ['ours', 'base', 'theirs'].map((n) => join(scratch, n));
- await writeFile(files[0], blobs.get(o.oid) ?? '');
- await writeFile(files[1], b ? blobs.get(b.oid) ?? '' : '');
- await writeFile(files[2], blobs.get(t.oid) ?? '');
- const merged = await run('git', ['merge-file', '-p', ...(prefer ? [`--${prefer}`] : []), ...files], { maxBuffer: 64 << 20, windowsHide: true })
- .then((r) => r.stdout, () => null);
- if (merged == null) {
- /* conflicts left (without `prefer`), or files it cannot merge (binary) */
- if (!prefer) throw conflict();
- result = pick ?? null;
- } else {
- const oid = (await repo.git(['hash-object', '-w', '--stdin'], { input: merged })).trim();
- result = { mode: o.mode, oid };
- }
+export function checkoutVersion(root, commit, { discard = false, onProgress } = {}) {
+ return queued(root, async () => {
+ const progress = throttled(onProgress);
+ const repo = await ready(root, progress);
+ const full = await resolveCommit(root, commit);
+ const head = await headOf(root);
+ const { changes } = await changesNow(repo, head);
+ if (changes.length && !discard) throw new HistoryError('there are changes: commit or discard them first', 409, 'dirty');
+ const version = await readVersion(repo, full);
+ const missing = await putBack(repo, version, changes, progress);
+ if (head) {
+ for (const path of (await readVersion(repo, head)).keys()) {
+ if (!version.has(path) && existsSync(join(root, path))) await moveToTrash(join(root, path));
}
- lines.push(`0 ${zero}\t${path}`);
- if (result) lines.push(`${result.mode} ${result.oid}\t${path}`);
}
- await repo.git(['update-index', '--index-info'], { input: `${lines.join('\n')}\n`, env });
- return (await repo.git(['write-tree'], { env })).trim();
- } finally {
- await rm(index, { force: true });
- await rm(scratch, { recursive: true, force: true });
- }
+ const tips = (await git(root, ['for-each-ref', `--points-at=${full}`, '--format=%(refname)', 'refs/heads'])).split('\n').filter(Boolean);
+ const branch = tips.includes('refs/heads/main') ? 'refs/heads/main' : tips[0];
+ if (branch) await git(root, ['symbolic-ref', 'HEAD', branch]);
+ else await git(root, ['update-ref', '--no-deref', 'HEAD', full]);
+ return { commit: full, missing };
+ });
}
/**
- * Merge `branch` into the one checked out, with the person's message (a merge that only moves forward makes no commit
- * of its own). Where both changed the same thing it stops ('conflict'), unless `prefer` says whose wins there: 'ours'
- * (the branch checked out) or 'theirs'. Needs no uncommitted changes ('dirty'). Returns false when there was nothing to
- * merge.
- * @param {string} root @param {{ branch: string, message: string, prefer?: 'ours' | 'theirs' } & Options} o
+ * Put `commit`'s files in the folder `into` (a new project's): a copy of that version, to try another way from it.
+ * Media comes from the store as clones where the disk can. Returns the media that could not be found.
+ * @param {string} root @param {string} commit @param {string} into @param {Options} [o]
*/
-export function mergeBranch(root, { branch, message, prefer, onProgress }) {
+export function copyVersion(root, commit, into, { onProgress } = {}) {
return queued(root, async () => {
const progress = throttled(onProgress);
const repo = await ready(root, progress);
- const name = await branchName(root, branch);
- if (!(await branchExists(root, name))) throw new HistoryError(`no branch "${name}"`, 404, 'none');
- if (name === await currentBranch(root)) throw new HistoryError('a branch is not merged into itself', 409, 'current');
- const head = /** @type {string} */ (await headOf(root));
- await needClean(repo, head);
- const branchRef = (await git(root, ['symbolic-ref', '--quiet', 'HEAD'])).trim();
- const theirs = (await git(root, ['rev-parse', `refs/heads/${name}`])).trim();
- const isAncestor = (/** @type {string} */ a, /** @type {string} */ b) => git(root, ['merge-base', '--is-ancestor', a, b]).then(() => true, () => false);
- if (await isAncestor(theirs, head)) return false;
- const text = String(message ?? '').trim() || `Merge ${name}`;
- let commit = theirs;
- if (!(await isAncestor(head, theirs))) {
- const base = (await git(root, ['merge-base', head, theirs]).catch(() => '')).trim();
- if (!base) throw new HistoryError(`"${name}" and this branch share no version`, 409, 'conflict');
- const tree = await mergeTrees(repo, base, head, theirs, prefer).catch((e) => {
- throw e instanceof HistoryError && e.code === 'conflict' ? new HistoryError(`"${name}" and this branch changed the same thing`, 409, 'conflict') : e;
- });
- commit = (await git(root, ['commit-tree', tree, '-p', head, '-p', theirs, '-m', text])).trim();
- }
- await git(root, ['update-ref', '-m', `merge ${name}`, branchRef, commit, head]);
- await writeFiles(repo, await readVersion(repo, commit), { progress });
- maintain(root);
- return true;
+ const version = await readVersion(repo, await resolveCommit(root, commit));
+ const { missing } = await writeFiles(openRepo(into, repo.gitDir), version, { progress });
+ return { missing };
});
}
diff --git a/packages/openfilm/studio/server/history.test.mjs b/packages/openfilm/studio/server/history.test.mjs
index 303f0c0..cf3ef72 100644
--- a/packages/openfilm/studio/server/history.test.mjs
+++ b/packages/openfilm/studio/server/history.test.mjs
@@ -2,12 +2,10 @@ import { test, before } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { randomBytes } from 'node:crypto';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, utimesSync, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import {
- checkout, commitChanges, deleteBranch, discardChanges, historyFiles, log, mergeBranch, renameBranch, restoreCommit, status,
-} from './history.mjs';
+import { checkoutVersion, copyVersion, discardChanges, log, saveVersion, status, versionFilesChanged } from './history.mjs';
import { replaceFile } from './atomic.mjs';
let trash;
@@ -28,50 +26,80 @@ const project = () => {
writeFileSync(join(root, 'title.html'), 'title');
return root;
};
-const gitEnv = (root) => ({ ...process.env, GIT_DIR: join(root, '.film', 'history'), GIT_WORK_TREE: root, GIT_CONFIG_NOSYSTEM: '1' });
-const gitOut = (root, args) => execFileSync('git', args, { cwd: root, env: gitEnv(root) }).toString();
-/** What the last commit holds. */
+/* who writes the versions an earlier edition made, as Studio does (history-store.mjs): a CI runner has no git identity */
+const gitEnv = (root) => ({ ...process.env, GIT_DIR: join(root, '.film', 'history'), GIT_WORK_TREE: root, GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'OpenFilm Studio', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'OpenFilm Studio', GIT_COMMITTER_EMAIL: '[email protected]' });
+const gitOut = (root, args, input) => execFileSync('git', args, { cwd: root, env: gitEnv(root), ...(input ? { input } : {}) }).toString();
+/** What a version holds. */
const tracked = (root, rev = 'HEAD') => gitOut(root, ['ls-tree', '-r', '--name-only', rev]).trim().split('\n').filter(Boolean).sort();
const rejects = (promise, code) => assert.rejects(promise, (e) => e.code === code);
/** A file's bytes and when it was last written, to see that nothing touched it. */
const mark = (path) => ({ bytes: readFileSync(path), mtime: statSync(path).mtimeMs });
const old = (path) => { const t = new Date(Date.now() - 3600_000); utimesSync(path, t, t); };
+const versions = async (root, o) => (await log(root, o)).versions;
-test('nothing is committed unless the person commits, with their message; only the film\'s files are kept', async () => {
+test('nothing is committed unless the person commits; a version holds the project, but media the film does not use', async () => {
const root = project();
mkdirSync(join(root, 'assets'));
+ mkdirSync(join(root, 'node_modules', 'x'), { recursive: true });
+ mkdirSync(join(root, '.venv'));
writeFileSync(join(root, 'assets', 'a.mp4'), 'video no clip uses');
+ writeFileSync(join(root, 'assets', 'still.png'), 'a picture no clip uses');
+ writeFileSync(join(root, 'notes.md'), 'the agent\'s notes');
+ writeFileSync(join(root, 'make.py'), 'print("the script that made it")');
+ writeFileSync(join(root, 'node_modules', 'x', 'index.js'), 'a package');
+ writeFileSync(join(root, '.venv', 'lib.py'), 'a tool\'s');
writeFileSync(join(root, '.film', 'id'), 'x');
writeFileSync(join(root, '.film', 'settings.json'), '{"fps":24}');
const fresh = await status(root);
- assert.equal(fresh.head, null, 'no commit yet');
- assert.deepEqual(fresh.branches, []);
- assert.equal(fresh.changes.summary.scenes.added, 1, 'all it holds is uncommitted');
- assert.equal(fresh.files.held, 3);
- assert.equal(fresh.files.ignored, 1, 'the video no clip uses');
- assert.deepEqual(await log(root), []);
- await rejects(commitChanges(root, ' '), 'message');
- const first = await commitChanges(root, 'First cut');
- assert.deepEqual(tracked(root), ['.film/settings.json', 'film.html', 'title.html']);
- await rejects(commitChanges(root, 'Again'), 'nothing');
- const [only] = await log(root);
+ assert.equal(fresh.head, null, 'no version yet');
+ assert.equal(fresh.changes.summary.scenes.added, 1, 'all it holds is new');
+ assert.deepEqual(fresh.changes.files.map((f) => [f.path, f.change]),
+ [['.film/settings.json', 'added'], ['film.html', 'added'], ['make.py', 'added'], ['notes.md', 'added'], ['title.html', 'added']],
+ 'the changes, as files: not the media no clip uses, a package or a tool\'s folder');
+ assert.deepEqual(await log(root), { versions: [], more: false });
+ const first = await saveVersion(root);
+ assert.deepEqual(tracked(root), ['.film/settings.json', 'film.html', 'make.py', 'notes.md', 'title.html']);
+ await rejects(saveVersion(root, { message: 'Again' }), 'nothing');
+ const [only] = await versions(root);
assert.equal(only.commit, first);
- assert.equal(only.message, 'First cut');
- assert.deepEqual(only.summary.scenes, { added: 1, removed: 0, edited: 0 });
- const after = await status(root);
- assert.equal(after.changes, null);
- assert.deepEqual(after.branches.map((b) => [b.name, b.current, b.message]), [['main', true, 'First cut']]);
- const files = await historyFiles(root);
- assert.deepEqual(files.ignored.map((f) => f.path), ['assets/a.mp4']);
- assert.deepEqual(files.held.map((f) => f.path), ['.film/settings.json', 'film.html', 'title.html']);
+ assert.deepEqual([only.kind, only.name, only.parents], ['saved', '', []]);
+ assert.equal((await status(root)).changes, null);
+ assert.equal((await status(root)).branch, 'main');
+ writeFileSync(join(root, 'title.html'), 'title, again');
+ assert.deepEqual((await status(root)).changes.files, [{ path: 'title.html', change: 'modified' }]);
+ const second = await saveVersion(root, { message: ' Second cut ' });
+ assert.deepEqual((await versions(root)).map((v) => [v.kind, v.name, v.parents]), [['named', 'Second cut', [first]], ['saved', '', []]]);
+ assert.match(gitOut(root, ['log', '-1', '--format=%B']), /^Second cut\n\nOpenfilm-Version: named\n/, 'readable in git too');
+ assert.deepEqual(await versionFilesChanged(root, second), [{ path: 'title.html', change: 'modified' }], 'what a version changed');
+ assert.equal((await versionFilesChanged(root, first)).length, 5, 'the first: all it holds');
+ writeFileSync(join(root, 'notes.md'), 'more notes');
+ writeFileSync(join(root, '.film', 'markers.json'), '{"markers":[]}');
+ assert.deepEqual((await status(root)).changes.summary, { scenes: { added: 0, removed: 0, edited: 0 }, sounds: { added: 0, removed: 0, edited: 0 }, stage: false, other: false },
+ 'notes and markers change nothing of the picture');
+});
+
+test('a file a page names by a path it builds in code is kept, wherever it is', async () => {
+ const root = project();
+ mkdirSync(join(root, 'assets', 'fonts'), { recursive: true });
+ mkdirSync(join(root, 'src'));
+ writeFileSync(join(root, 'assets', 'fonts', 'Archivo-VF.ttf'), randomBytes(3000));
+ writeFileSync(join(root, 'src', 'type.js'), "const DIR = '../assets/fonts/'; export const fonts = [{ file: 'Archivo-VF.ttf' }].map((f) => DIR + f.file);");
+ writeFileSync(join(root, 'title.html'), '<script type="module" src="src/type.js"></script>');
+ await saveVersion(root, { message: 'With its font' });
+ assert.ok(tracked(root).includes('assets/fonts/Archivo-VF.ttf'));
+ const font = readFileSync(join(root, 'assets', 'fonts', 'Archivo-VF.ttf'));
+ writeFileSync(join(root, 'assets', 'fonts', 'Archivo-VF.ttf'), randomBytes(3000));
+ await discardChanges(root);
+ assert.deepEqual(readFileSync(join(root, 'assets', 'fonts', 'Archivo-VF.ttf')), font, 'it comes back');
});
-test('what a commit changed is told as the film: scenes and sounds added, removed and edited', async () => {
+test('what changed is told as the film too: scenes and sounds added, removed and edited', async () => {
const root = project();
mkdirSync(join(root, 'end'));
writeFileSync(join(root, 'end', 'end.html'), 'end');
writeFileSync(join(root, 'film.html'), film(page('title.html'), page('end/end.html', 5)));
- await commitChanges(root, 'Two scenes');
+ await saveVersion(root, { message: 'Two scenes' });
/* one scene's page rewritten, one gone, a sound added, and a stylesheet beside the pages changed */
writeFileSync(join(root, 'title.html'), 'title, bigger');
writeFileSync(join(root, 'look.css'), 'body {}');
@@ -81,10 +109,8 @@ test('what a commit changed is told as the film: scenes and sounds added, remove
assert.deepEqual(changes.summary.scenes, { added: 0, removed: 1, edited: 1 });
assert.deepEqual(changes.summary.sounds, { added: 1, removed: 0, edited: 0 });
assert.equal(changes.summary.other, true, 'a file no clip names');
- await commitChanges(root, 'Shorter, with music');
- assert.deepEqual((await log(root))[0].summary, changes.summary, 'the commit tells the same');
- assert.ok(!tracked(root).includes('end/end.html'), 'a page the film no longer uses leaves the version');
- assert.ok(existsSync(join(root, 'end', 'end.html')), 'and stays in the folder');
+ await saveVersion(root, { message: 'Shorter, with music' });
+ assert.ok(tracked(root).includes('end/end.html'), 'a page the film no longer uses is still the project\'s');
});
test('media is kept by its content outside git, and comes back byte for byte', async () => {
@@ -96,7 +122,7 @@ test('media is kept by its content outside git, and comes back byte for byte', a
writeFileSync(join(root, 'assets', 'shot.vtt'), 'WEBVTT\n');
writeFileSync(join(root, 'assets', 'copy.mp4'), take1);
writeFileSync(join(root, 'film.html'), film(video('assets/shot.mp4#t=1,2'), video('assets/copy.mp4', 3)));
- const first = await commitChanges(root, 'Take 1');
+ const first = await saveVersion(root, { message: 'Take 1' });
/* the tree holds a pointer; the store holds the bytes once */
const pointer = gitOut(root, ['show', 'HEAD:assets/shot.mp4']);
assert.match(pointer, /^openfilm-media 1\nsha256 [0-9a-f]{64}\nsize 3145728\n$/);
@@ -106,18 +132,63 @@ test('media is kept by its content outside git, and comes back byte for byte', a
assert.ok(tracked(root).includes('assets/shot.vtt'), 'its subtitles beside it');
writeFileSync(join(root, 'assets', 'shot.mp4'), take2);
writeFileSync(join(root, 'assets', 'shot.vtt'), 'WEBVTT\n\n00:00.000 --> 00:01.000\nhi\n');
- await commitChanges(root, 'Take 2');
- await restoreCommit(root, first);
+ const second = await saveVersion(root, { message: 'Take 2' });
+ await checkoutVersion(root, first);
assert.deepEqual(readFileSync(join(root, 'assets', 'shot.mp4')), take1, 'take 1, exactly');
assert.equal(readFileSync(join(root, 'assets', 'shot.vtt'), 'utf8'), 'WEBVTT\n');
- assert.equal((await status(root)).changes.count, 2, 'as uncommitted changes');
- await discardChanges(root);
+ assert.equal((await status(root)).changes, null);
+ await checkoutVersion(root, second);
assert.deepEqual(readFileSync(join(root, 'assets', 'shot.mp4')), take2);
});
-test('discard puts back the last commit; files the film takes since go to the trash, others stay', async () => {
+test('checking out a version, as git: the folder holds its files, no version is made, and changes are not lost', async () => {
const root = project();
- await commitChanges(root, 'One');
+ const first = await saveVersion(root, { message: 'One' });
+ writeFileSync(join(root, 'title.html'), 'two');
+ writeFileSync(join(root, '.film', 'markers.json'), '{"markers":[{"id":"m1","t":1}]}');
+ mkdirSync(join(root, 'more'));
+ writeFileSync(join(root, 'more', 'extra.html'), 'extra');
+ writeFileSync(join(root, 'film.html'), film(page('title.html'), page('more/extra.html', 4)));
+ const second = await saveVersion(root, { message: 'Two' });
+ writeFileSync(join(root, 'title.html'), 'not committed');
+ await rejects(checkoutVersion(root, first), 'dirty');
+ assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'not committed', 'refused: nothing touched');
+ const done = await checkoutVersion(root, first, { discard: true });
+ assert.equal(done.commit, first);
+ assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'title');
+ assert.ok(!existsSync(join(root, 'more', 'extra.html')), 'a file the version checked out had and this one does not goes');
+ assert.ok(readdirSync(trash).includes('extra.html'), 'to the trash');
+ assert.ok(!existsSync(join(root, '.film', 'markers.json')), 'the version had no markers');
+ const now = await status(root);
+ assert.deepEqual([now.head, now.branch, now.changes], [first, null, null], 'checked out on its own, as git\'s detached HEAD');
+ assert.deepEqual((await versions(root)).map((v) => v.name), ['Two', 'One'], 'no version of its own');
+ /* back to the newest: main again */
+ await checkoutVersion(root, second);
+ assert.deepEqual([(await status(root)).branch, readFileSync(join(root, 'title.html'), 'utf8')], ['main', 'two']);
+ assert.ok(existsSync(join(root, '.film', 'markers.json')), 'and its markers');
+ await rejects(checkoutVersion(root, 'nothex'), 'none');
+ await rejects(checkoutVersion(root, second.replace(/./g, 'f')), 'none');
+});
+
+test('a commit on a version checked out goes on main from there; main\'s later versions stay on a line of their own', async () => {
+ const root = project();
+ const first = await saveVersion(root, { message: 'One' });
+ writeFileSync(join(root, 'title.html'), 'two');
+ const second = await saveVersion(root, { message: 'Two' });
+ await checkoutVersion(root, first);
+ writeFileSync(join(root, 'title.html'), 'another way');
+ const third = await saveVersion(root, { message: 'Another way' });
+ const now = await status(root);
+ assert.deepEqual([now.head, now.branch], [third, 'main']);
+ const list = await versions(root);
+ assert.deepEqual(list.map((v) => [v.name, v.parents]), [['Another way', [first]], ['Two', [first]], ['One', []]], 'every version, as a graph');
+ await checkoutVersion(root, second);
+ assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'two', 'the later one can still be checked out');
+});
+
+test('discarding the changes puts back the version checked out; files made since go to the trash, others stay', async () => {
+ const root = project();
+ await saveVersion(root, { message: 'One' });
writeFileSync(join(root, 'title.html'), 'changed');
writeFileSync(join(root, 'new.html'), 'new, beside the page');
writeFileSync(join(root, 'big.wav'), Buffer.alloc(2 << 20));
@@ -125,179 +196,103 @@ test('discard puts back the last commit; files the film takes since go to the tr
assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'title');
assert.ok(!existsSync(join(root, 'new.html')));
assert.ok(readdirSync(trash).includes('new.html'), 'to the trash, not away');
- assert.ok(existsSync(join(root, 'big.wav')), 'the film does not use it');
+ assert.ok(existsSync(join(root, 'big.wav')), 'the film does not use it: not the history\'s');
assert.equal((await status(root)).changes, null);
- assert.equal((await log(root)).length, 1, 'nothing committed');
-});
-
-test('going back to a commit puts its files in the folder as uncommitted changes; nothing is committed', async () => {
- const root = project();
- const first = await commitChanges(root, 'One');
- writeFileSync(join(root, 'title.html'), 'two');
- mkdirSync(join(root, 'more'));
- writeFileSync(join(root, 'more', 'extra.html'), 'extra');
- writeFileSync(join(root, 'film.html'), film(page('title.html'), page('more/extra.html', 4)));
- await commitChanges(root, 'Two');
- writeFileSync(join(root, 'title.html'), 'unsaved');
- await rejects(restoreCommit(root, first), 'dirty');
- await discardChanges(root);
- await restoreCommit(root, first);
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'title');
- assert.ok(existsSync(join(root, 'more', 'extra.html')), 'a file the film no longer uses stays in the folder');
- const { changes } = await status(root);
- assert.ok(changes, 'shown as uncommitted');
- assert.deepEqual(changes.summary.scenes, { added: 0, removed: 1, edited: 1 });
- assert.equal((await log(root)).length, 2, 'no commit of its own');
- /* discarding comes back to where it was */
- await discardChanges(root);
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'two');
- await rejects(restoreCommit(root, 'nothex'), 'none');
+ assert.equal((await versions(root)).length, 1, 'nothing committed');
});
-test('restore, switch and merge write only the film\'s files that differ, and nothing else', async () => {
+test('checking out writes only the files that differ, and nothing else', async () => {
const root = project();
mkdirSync(join(root, 'renders'));
writeFileSync(join(root, 'renders', 'frame-0001.exr'), randomBytes(1000));
writeFileSync(join(root, 'render.log'), 'log');
writeFileSync(join(root, 'same.html'), 'same in every version');
writeFileSync(join(root, 'film.html'), film(page('title.html'), page('same.html', 3)));
- const first = await commitChanges(root, 'One');
+ const first = await saveVersion(root, { message: 'One' });
writeFileSync(join(root, 'title.html'), 'two');
- await commitChanges(root, 'Two');
+ await saveVersion(root, { message: 'Two' });
for (const f of ['renders/frame-0001.exr', 'render.log', 'same.html']) old(join(root, f));
const before = Object.fromEntries(['renders/frame-0001.exr', 'render.log', 'same.html'].map((f) => [f, mark(join(root, f))]));
- const untouched = () => { for (const [f, m] of Object.entries(before)) assert.deepEqual(mark(join(root, f)), m, `${f} untouched`); };
- await restoreCommit(root, first);
- untouched();
- await discardChanges(root);
- await checkout(root, { target: 'alt', create: true, from: first });
+ await checkoutVersion(root, first);
assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'title');
- writeFileSync(join(root, 'title.html'), 'alt');
- await commitChanges(root, 'Alt');
- await checkout(root, { target: 'main' });
- untouched();
- await mergeBranch(root, { branch: 'alt', message: 'Merge alt', prefer: 'theirs' });
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'alt');
- untouched();
- assert.ok(!tracked(root).some((p) => p.startsWith('renders/') || p === 'render.log'));
+ for (const [f, m] of Object.entries(before)) assert.deepEqual(mark(join(root, f)), m, `${f} untouched`);
});
-test('branches: a new one takes the changes along; switching leaves them on their branch and brings them back', async () => {
+test('a copy of a version is put in another folder, media and all', async () => {
const root = project();
- await rejects(checkout(root, { target: 'idea', create: true }), 'nothing');
- await commitChanges(root, 'One');
- writeFileSync(join(root, 'title.html'), 'on idea');
- await checkout(root, { target: 'Snow idea', create: true });
- let state = await status(root);
- assert.equal(state.branch, 'Snow-idea', 'spaces become dashes');
- assert.ok(state.changes, 'the changes came along');
- await commitChanges(root, 'Snow');
- /* back to main with something uncommitted: left on Snow-idea, and there again on coming back */
- writeFileSync(join(root, 'title.html'), 'half done');
- await checkout(root, { target: 'main' });
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'title');
- state = await status(root);
- assert.equal(state.changes, null);
- assert.equal(state.branches.find((b) => b.name === 'Snow-idea').parked, true);
- await checkout(root, { target: 'Snow-idea' });
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'half done');
- assert.equal((await status(root)).branches.find((b) => b.name === 'Snow-idea').parked, false);
- /* brought along: refused when it collides with what the other branch holds */
- await rejects(checkout(root, { target: 'main', carry: 'bring' }), 'conflict');
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'half done', 'nothing moved');
- /* brought along where it does not collide: it comes, and what the other branch holds comes too */
- writeFileSync(join(root, 'title.html'), 'on idea');
- writeFileSync(join(root, 'side.css'), 'body { color: red }');
- await checkout(root, { target: 'main', carry: 'bring' });
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'title');
- assert.equal(readFileSync(join(root, 'side.css'), 'utf8'), 'body { color: red }');
- assert.deepEqual((await status(root)).changes?.count, 1, 'the new stylesheet came along, uncommitted');
- await rejects(checkout(root, { target: 'main', create: true }), 'exists');
- await rejects(checkout(root, { target: 'bad..name', create: true }), 'name');
+ const shot = randomBytes(2 << 20);
+ writeFileSync(join(root, 'shot.mp4'), shot);
+ writeFileSync(join(root, 'film.html'), film(page('title.html'), video('shot.mp4', 2)));
+ const first = await saveVersion(root, { message: 'One' });
+ writeFileSync(join(root, 'title.html'), 'two');
+ await saveVersion(root, { message: 'Two' });
+ const into = mkdtempSync(join(tmpdir(), 'of-history-copy-'));
+ const { missing } = await copyVersion(root, first, into);
+ assert.deepEqual(missing, []);
+ assert.equal(readFileSync(join(into, 'title.html'), 'utf8'), 'title');
+ assert.deepEqual(readFileSync(join(into, 'shot.mp4')), shot);
+ assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'two', 'the project stays as it is');
});
-test('a branch from an earlier commit; rename takes its parked changes; delete guards commits on no other branch', async () => {
+test('the versions of every branch an earlier edition made, and the changes it parked, are listed and can be checked out', async () => {
const root = project();
- const first = await commitChanges(root, 'One');
+ await saveVersion(root, { message: 'One' });
writeFileSync(join(root, 'title.html'), 'two');
- await commitChanges(root, 'Two');
- await checkout(root, { target: 'from-one', create: true, from: first });
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'title');
- writeFileSync(join(root, 'title.html'), 'alt');
- await commitChanges(root, 'Alt');
- writeFileSync(join(root, 'title.html'), 'parked');
- await checkout(root, { target: 'main' });
- await renameBranch(root, 'from-one', 'alt-take');
- const branches = (await status(root)).branches;
- assert.deepEqual(branches.map((b) => b.name).sort(), ['alt-take', 'main']);
- assert.equal(branches.find((b) => b.name === 'alt-take').parked, true, 'its parked changes came with the name');
- await checkout(root, { target: 'alt-take' });
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'parked');
- await discardChanges(root);
- await checkout(root, { target: 'main' });
- await rejects(deleteBranch(root, 'main'), 'current');
- await assert.rejects(deleteBranch(root, 'alt-take'), (e) => e.code === 'unmerged' && e.commits === 1);
- await deleteBranch(root, 'alt-take', { force: true });
- assert.deepEqual((await status(root)).branches.map((b) => b.name), ['main']);
+ const second = await saveVersion(root, { message: 'Two' });
+ /* an earlier edition's branch, and changes it left on it */
+ writeFileSync(join(root, 'title.html'), 'idea');
+ const idea = await saveVersion(root, { message: 'Idea' });
+ gitOut(root, ['update-ref', 'refs/heads/idea', idea]);
+ gitOut(root, ['update-ref', 'refs/heads/main', second]);
+ const parked = gitOut(root, ['commit-tree', `${idea}^{tree}`, '-p', idea, '-m', 'parked: idea']).trim();
+ gitOut(root, ['update-ref', 'refs/openfilm/parked/idea', parked]);
+ writeFileSync(join(root, 'title.html'), 'two');
+ const list = await versions(root);
+ assert.deepEqual(list.map((v) => [v.kind, v.name]).sort(), [['named', 'Idea'], ['named', 'One'], ['named', 'Two'], ['parked', 'idea']]);
+ await checkoutVersion(root, idea);
+ assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'idea');
+ assert.equal((await status(root)).branch, 'idea', 'the branch whose tip it is');
+ const page2 = await log(root, { limit: 2 });
+ assert.equal(page2.versions.length, 2);
+ assert.equal(page2.more, true);
});
-test('merge: a clean one, a collision that stops, and one where the person says whose side wins', async () => {
+test('on its own, a version is saved only when the film changed, never for notes, logs or markers', async () => {
const root = project();
- writeFileSync(join(root, 'end.html'), 'end');
- writeFileSync(join(root, 'film.html'), film(page('title.html'), page('end.html', 5)));
- await commitChanges(root, 'One');
- await checkout(root, { target: 'ending', create: true });
- writeFileSync(join(root, 'end.html'), 'new end');
- await commitChanges(root, 'New ending');
- await checkout(root, { target: 'main' });
- assert.equal(await mergeBranch(root, { branch: 'ending', message: 'Merge ending' }), true);
- assert.equal(readFileSync(join(root, 'end.html'), 'utf8'), 'new end');
- assert.equal(await mergeBranch(root, { branch: 'ending', message: 'Again' }), false, 'nothing left to merge');
- /* both change the title */
- await checkout(root, { target: 'ending' });
- writeFileSync(join(root, 'title.html'), 'theirs');
- await commitChanges(root, 'Their title');
- await checkout(root, { target: 'main' });
- writeFileSync(join(root, 'title.html'), 'ours');
- await rejects(mergeBranch(root, { branch: 'ending', message: 'x' }), 'dirty');
- await commitChanges(root, 'Our title');
- const before = (await log(root)).length;
- await rejects(mergeBranch(root, { branch: 'ending', message: 'Merge' }), 'conflict');
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'ours', 'stopped: nothing changed');
- assert.equal((await status(root)).changes, null);
- assert.equal((await log(root)).length, before);
- await mergeBranch(root, { branch: 'ending', message: 'Merge, their title', prefer: 'theirs' });
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'theirs');
- const [merge] = await log(root);
- assert.equal(merge.message, 'Merge, their title');
- assert.equal(merge.parents.length, 2);
+ assert.ok(await saveVersion(root, { kind: 'auto' }), 'the first: all the film is new');
+ assert.equal(await saveVersion(root, { kind: 'auto' }), null, 'nothing changed');
+ writeFileSync(join(root, 'notes.md'), 'the agent\'s notes');
+ writeFileSync(join(root, 'render.log'), 'a log');
+ writeFileSync(join(root, '.film', 'markers.json'), '{"markers":[{"id":"m1","t":1}]}');
+ assert.equal(await saveVersion(root, { kind: 'agent' }), null, 'notes, a log and markers are not the film');
+ writeFileSync(join(root, 'title.html'), 'a new title');
+ const saved = await saveVersion(root, { kind: 'auto' });
+ assert.ok(saved, 'a scene changed');
+ assert.ok(tracked(root).includes('notes.md'), 'and the notes go with it');
+ assert.deepEqual((await versions(root)).map((v) => v.kind), ['auto', 'auto']);
+ writeFileSync(join(root, 'notes.md'), 'more notes');
+ assert.ok(await saveVersion(root), 'the person may save a version of anything that changed');
});
-test('merge: film.html edits on both sides in different places come together line by line', async () => {
+test('a history that lost its empty folders (a copy or a sync left them out) still works', async () => {
const root = project();
- writeFileSync(join(root, 'a.html'), 'a');
- writeFileSync(join(root, 'b.html'), 'b');
- const base = ['title.html', 'a.html', 'b.html'];
- const lines = (srcs) => film(...srcs.map((s, i) => page(s, i * 10)));
- writeFileSync(join(root, 'film.html'), lines(base));
- await commitChanges(root, 'Base');
- await checkout(root, { target: 'other', create: true });
- writeFileSync(join(root, 'film.html'), lines(base).replace('src="b.html" at="20"', 'src="b.html" at="25"'));
- await commitChanges(root, 'Later b');
- await checkout(root, { target: 'main' });
- writeFileSync(join(root, 'film.html'), lines(base).replace('src="title.html" at="0"', 'src="title.html" at="1"'));
- await commitChanges(root, 'Later title');
- assert.equal(await mergeBranch(root, { branch: 'other', message: 'Both' }), true);
- const merged = readFileSync(join(root, 'film.html'), 'utf8');
- assert.match(merged, /src="title.html" at="1"/);
- assert.match(merged, /src="b.html" at="25"/);
- assert.equal((await status(root)).changes, null);
+ /* never saved yet, as a copy without empty folders leaves it: refs/ and objects/ gone */
+ await status(root);
+ rmSync(join(root, '.film', 'history', 'refs'), { recursive: true, force: true });
+ rmSync(join(root, '.film', 'history', 'objects'), { recursive: true, force: true });
+ assert.ok((await status(root)).changes, 'read');
+ assert.ok(await saveVersion(root, { message: 'One' }), 'and saved');
+ /* moved since, too: its settings name the folder where it was */
+ const config = join(root, '.film', 'history', 'config');
+ writeFileSync(config, readFileSync(config, 'utf8').replace(/worktree = .*/, 'worktree = /somewhere/else'));
+ rmSync(join(root, '.film', 'history', 'refs', 'tags'), { recursive: true, force: true });
+ assert.deepEqual((await versions(root)).map((v) => v.name), ['One']);
});
test('the folder\'s own .git is never touched', async () => {
const root = project();
execFileSync('git', ['init', '--quiet'], { cwd: root });
- await commitChanges(root, 'saved');
+ await saveVersion(root);
assert.match(execFileSync('git', ['status', '--porcelain'], { cwd: root }).toString(), /film\.html/, 'film.html is still untracked in the person\'s repository');
assert.throws(() => execFileSync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: root, stdio: 'ignore' }), 'and it has no commit');
});
@@ -311,25 +306,25 @@ test('a history the folder brought with it never runs its commands: it is put as
execFileSync('git', ['--git-dir', gitDir, 'config', 'core.fsmonitor', `echo fsmonitor >> '${ran}'; false`]);
writeFileSync(join(gitDir, 'hooks', 'post-commit'), `#!/bin/sh\necho hook >> '${ran}'\n`);
chmodSync(join(gitDir, 'hooks', 'post-commit'), 0o755);
- assert.deepEqual(await log(root), [], 'not read either');
- assert.ok(await commitChanges(root, 'saved'));
+ assert.deepEqual(await log(root), { versions: [], more: false }, 'not read either');
+ assert.ok(await saveVersion(root));
assert.equal(existsSync(ran), false, 'nothing it named ran');
assert.equal(readdirSync(join(root, '.film')).filter((n) => n.startsWith('history-from-elsewhere-')).length, 1, 'it is put aside, not deleted');
assert.doesNotMatch(readFileSync(join(gitDir, 'config'), 'utf8'), /fsmonitor/);
- assert.equal((await log(root)).length, 1);
+ assert.equal((await versions(root)).length, 1);
/* a hook put into Studio's own history does not run either */
mkdirSync(join(gitDir, 'hooks'), { recursive: true });
writeFileSync(join(gitDir, 'hooks', 'post-commit'), `#!/bin/sh\necho hook >> '${ran}'\n`);
chmodSync(join(gitDir, 'hooks', 'post-commit'), 0o755);
writeFileSync(join(root, 'film.html'), film(page('title.html'), page('title.html', 3)));
- assert.ok(await commitChanges(root, 'saved again'));
+ assert.ok(await saveVersion(root));
assert.equal(existsSync(ran), false);
});
test('a project moved or renamed keeps its history: every call names the folder where it is now', async () => {
const before = project();
- await commitChanges(before, 'First cut');
+ await saveVersion(before, { message: 'First cut' });
const gitDir = (root) => join(root, '.film', 'history');
const worktree = (root) => execFileSync('git', ['--git-dir', gitDir(root), 'config', 'core.worktree'], { env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1' } }).toString().trim();
/* as git init wrote it, and as an earlier Studio left it: where the folder was */
@@ -338,22 +333,24 @@ test('a project moved or renamed keeps its history: every call names the folder
/* the commit's tidy-up (git gc --auto) may still be running in the folder: Windows refuses the move for a moment */
await replaceFile(before, root);
assert.equal(worktree(root), before, 'the history still says the old folder');
- assert.deepEqual((await log(root)).map((c) => c.message), ['First cut']);
+ assert.deepEqual((await versions(root)).map((v) => v.name), ['First cut']);
assert.equal(worktree(root), root, 'and says the new one once used');
assert.equal((await status(root)).changes, null, 'nothing looks changed');
writeFileSync(join(root, 'end.html'), 'end');
writeFileSync(join(root, 'film.html'), film(page('title.html'), page('end.html', 3)));
- await commitChanges(root, 'Moved');
- await checkout(root, { target: 'alt', create: true });
- assert.deepEqual((await status(root)).branches.map((b) => [b.name, b.current]), [['alt', true], ['main', false]]);
- assert.deepEqual((await log(root)).map((c) => c.message), ['Moved', 'First cut']);
+ await saveVersion(root, { message: 'Moved' });
+ assert.deepEqual((await versions(root)).map((v) => v.name), ['Moved', 'First cut']);
assert.deepEqual(tracked(root), ['end.html', 'film.html', 'title.html']);
});
-test('a commit an earlier edition made shows the name the person gave it', async () => {
+test('a version an earlier edition made shows the name the person gave it', async () => {
const root = project();
- await commitChanges(root, 'studio: named "Final"');
- assert.equal((await log(root))[0].message, 'Final');
+ await saveVersion(root);
+ gitOut(root, ['update-ref', 'refs/heads/main', gitOut(root, ['commit-tree', 'HEAD^{tree}', '-m', 'studio: named "Final"']).trim()]);
+ gitOut(root, ['update-ref', 'refs/tags/v-' + Buffer.from('Older').toString('base64url'), 'HEAD']);
+ assert.deepEqual((await versions(root)).map((v) => [v.kind, v.name]), [['named', 'Older']]);
+ gitOut(root, ['update-ref', '-d', 'refs/tags/v-' + Buffer.from('Older').toString('base64url')]);
+ assert.deepEqual((await versions(root)).map((v) => [v.kind, v.name]), [['named', 'Final']]);
});
test('progress is told while an action runs', async () => {
@@ -361,7 +358,7 @@ test('progress is told while an action runs', async () => {
writeFileSync(join(root, 'clip.mp4'), randomBytes(1 << 20));
writeFileSync(join(root, 'film.html'), film(page('title.html'), video('clip.mp4', 2)));
const seen = [];
- await commitChanges(root, 'One', { onProgress: (p) => seen.push(p.phase) });
+ await saveVersion(root, { message: 'One', onProgress: (p) => seen.push(p.phase) });
assert.ok(seen.includes('scan') && seen.includes('store'));
});
@@ -369,7 +366,7 @@ test('progress is told while an action runs', async () => {
/** A history as an earlier Studio kept it: everything but .film/ and video, committed with `git add --all`. */
function oldHistory(root) {
- const git = (...args) => execFileSync('git', args, { cwd: root, env: { ...gitEnv(root), GIT_AUTHOR_NAME: 'OpenFilm Studio', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'OpenFilm Studio', GIT_COMMITTER_EMAIL: '[email protected]' } }).toString();
+ const git = (...args) => execFileSync('git', args, { cwd: root, env: gitEnv(root) }).toString();
mkdirSync(join(root, '.film', 'history', 'info'), { recursive: true });
git('init', '--quiet', '--template=', '--initial-branch=main');
git('config', 'core.autocrlf', 'false');
@@ -415,21 +412,35 @@ test('an earlier Studio\'s history is brought up to date on first use: its versi
assert.deepEqual(mark(join(root, 'render.log')), logNow);
assert.ok(existsSync(join(root, '.film', 'history', 'openfilm.json')));
assert.equal(readdirSync(trash).filter((n) => n.startsWith('history-before-cleanup-')).length >= 1, true, 'the old history went to the trash');
- const commits = await log(root);
- assert.deepEqual(commits.map((c) => c.message), ['History cleanup: the film\'s files only, its media kept from now on', 'v2', 'v1']);
- assert.deepEqual(tracked(root), ['assets/shot.mp4', 'assets/vo.mp3', 'film.html', 'title.html'], 'the film\'s files only, its video added');
+ const commits = await versions(root);
+ assert.deepEqual(commits.filter((c) => c.kind !== 'parked').map((c) => [c.kind, c.name]), [['upgrade', ''], ['named', 'v2'], ['named', 'v1']]);
+ assert.deepEqual(tracked(root), ['assets/shot.mp4', 'assets/vo.mp3', 'film.html', 'render.log', 'title.html'], 'the project\'s files, its video added, not the renders');
assert.deepEqual(tracked(root, 'HEAD~1'), ['assets/vo.mp3', 'film.html', 'title.html'], 'a version as it was, without what the film never used');
- const newV1 = commits[2].commit;
+ const newV1 = commits.find((c) => c.name === 'v1').commit;
assert.ok(existsSync(join(posters, `${newV1}.jpg`)), 'its picture under its new name');
/* an old version comes back: its page and its sound, byte for byte */
- await restoreCommit(root, newV1);
+ await checkoutVersion(root, newV1);
assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'title');
assert.deepEqual(readFileSync(join(root, 'assets', 'vo.mp3')), vo1);
- await discardChanges(root);
- assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'title two');
/* the changes left on a branch are still there */
- assert.equal((await status(root)).branches.find((b) => b.name === 'idea').parked, true);
- await checkout(root, { target: 'idea' });
+ const parked = commits.find((c) => c.kind === 'parked');
+ assert.equal(parked.name, 'idea');
+ await checkoutVersion(root, parked.commit);
assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), 'idea, half done');
- assert.ok(existsSync(join(root, 'renders', 'f2.exr')) && existsSync(join(root, 'render.log')), 'and nothing else was touched');
+ assert.ok(existsSync(join(root, 'renders', 'f2.exr')), 'what no version holds is never touched');
+ await checkoutVersion(root, commits[0].commit);
+ assert.equal(readFileSync(join(root, 'render.log'), 'utf8'), 'a long log', 'the newest, as it was');
+});
+
+test('a history that kept the film\'s files only is brought up to date: the project\'s others are added, nothing looks changed', async () => {
+ const root = project();
+ await saveVersion(root, { message: 'One' });
+ writeFileSync(join(root, '.film', 'history', 'openfilm.json'), '{"format":2}\n');
+ writeFileSync(join(root, 'notes.md'), 'notes a version did not keep before');
+ const before = mark(join(root, 'notes.md'));
+ assert.equal((await status(root)).changes, null);
+ assert.deepEqual((await versions(root)).map((v) => [v.kind, v.name]), [['upgrade', ''], ['named', 'One']]);
+ assert.ok(tracked(root).includes('notes.md'));
+ assert.deepEqual(mark(join(root, 'notes.md')), before, 'the person\'s files are not written');
+ assert.match(readFileSync(join(root, '.film', 'history', 'openfilm.json'), 'utf8'), /"format":3/);
});
diff --git a/packages/openfilm/studio/server/prefs.mjs b/packages/openfilm/studio/server/prefs.mjs
index 121f79c..6e5add0 100644
--- a/packages/openfilm/studio/server/prefs.mjs
+++ b/packages/openfilm/studio/server/prefs.mjs
@@ -10,6 +10,8 @@
* (OPENFILM_SHARED_HOME, else this one), so every OpenFilm on the computer shares it.
* keys the keyboard shortcuts: the scheme in use and the custom ones (null: OpenFilm's). Kept as Studio's
* page gives them, in shape only (keysOf); the page checks every action and key (ui/src/lib/keymap.ts).
+ * autoVersions whether a project open in Studio saves versions of itself while it is worked on (auto-versions.mjs)
+ * showAutoVersions legacy visibility hint for older clients; the current history dialog uses its type filter
*/
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { isAbsolute, join, resolve } from 'node:path';
@@ -17,10 +19,10 @@ import { studioHome } from './projects.mjs';
import { chooseFolder, chosenFolder } from '../../src/locations.mjs';
/** @typedef {{ scheme: string, custom: Record<string, { base: string, keys: Record<string, string[]> }> }} Keys */
-/** @typedef {{ proxies: { on: boolean, height: 540 | 720 | 1080 }, seenVersion: string | null, projectsFolder: string | null, keys: Keys | null }} Prefs */
+/** @typedef {{ proxies: { on: boolean, height: 540 | 720 | 1080 }, seenVersion: string | null, projectsFolder: string | null, keys: Keys | null, autoVersions: boolean, showAutoVersions: boolean }} Prefs */
-/** Proxies on by default, at 720p. */
-export const DEFAULT_PREFS = /** @type {Prefs} */ ({ proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: null, keys: null });
+/** Proxies on by default, at 720p; versions saved by the person only, and only theirs listed. */
+export const DEFAULT_PREFS = /** @type {Prefs} */ ({ proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: null, keys: null, autoVersions: false, showAutoVersions: false });
const VERSION = /^\d+\.\d+\.\d+(?:-[\w.]+)?$/;
const HEIGHTS = [540, 720, 1080];
@@ -55,7 +57,7 @@ export function keysOf(raw) {
/** What is kept, each field checked; anything missing or wrong is its default. @param {unknown} raw @returns {Prefs} */
export function prefsOf(raw) {
- const p = /** @type {{ proxies?: { on?: unknown, height?: unknown }, seenVersion?: unknown, projectsFolder?: unknown, keys?: unknown } | null} */ (raw && typeof raw === 'object' ? raw : null);
+ const p = /** @type {{ proxies?: { on?: unknown, height?: unknown }, seenVersion?: unknown, projectsFolder?: unknown, keys?: unknown, autoVersions?: unknown, showAutoVersions?: unknown } | null} */ (raw && typeof raw === 'object' ? raw : null);
const folder = (/** @type {unknown} */ v) => (typeof v === 'string' && isAbsolute(v) ? resolve(v) : null);
const height = Number(p?.proxies?.height);
return {
@@ -66,6 +68,8 @@ export function prefsOf(raw) {
seenVersion: typeof p?.seenVersion === 'string' && VERSION.test(p.seenVersion) ? p.seenVersion : null,
projectsFolder: folder(p?.projectsFolder),
keys: keysOf(p?.keys),
+ autoVersions: p?.autoVersions === true,
+ showAutoVersions: p?.showAutoVersions === true,
};
}
@@ -85,7 +89,7 @@ export function readPrefs() {
*/
export function writePrefs(patch) {
const now = readPrefs();
- const asked = /** @type {{ proxies?: object, seenVersion?: unknown, projectsFolder?: unknown, keys?: unknown }} */ (patch && typeof patch === 'object' ? patch : {});
+ const asked = /** @type {{ proxies?: object, seenVersion?: unknown, projectsFolder?: unknown, keys?: unknown, autoVersions?: unknown, showAutoVersions?: unknown }} */ (patch && typeof patch === 'object' ? patch : {});
const next = prefsOf({ ...now, ...asked, proxies: { ...now.proxies, ...(asked.proxies ?? {}) } });
const at = file();
let kept = {};
diff --git a/packages/openfilm/studio/server/prefs.test.mjs b/packages/openfilm/studio/server/prefs.test.mjs
index c783a60..b202581 100644
--- a/packages/openfilm/studio/server/prefs.test.mjs
+++ b/packages/openfilm/studio/server/prefs.test.mjs
@@ -56,3 +56,11 @@ test('the keyboard shortcuts written are read back, and the rest of prefs.json s
if (was === undefined) delete process.env.OPENFILM_HOME; else process.env.OPENFILM_HOME = was;
}
});
+
+test('auto versions are off, and not listed, unless the person turned them on', () => {
+ assert.equal(prefsOf(null).autoVersions, false);
+ assert.equal(prefsOf(null).showAutoVersions, false);
+ assert.equal(prefsOf({ showAutoVersions: true }).showAutoVersions, true);
+ assert.equal(prefsOf({ autoVersions: 'yes' }).autoVersions, false);
+ assert.equal(prefsOf({ autoVersions: true }).autoVersions, true);
+});
diff --git a/packages/openfilm/studio/server/server.mjs b/packages/openfilm/studio/server/server.mjs
index db95e29..3941dbc 100644
--- a/packages/openfilm/studio/server/server.mjs
+++ b/packages/openfilm/studio/server/server.mjs
@@ -25,7 +25,9 @@ import { EditError, editProjectFilm, pageClipLook, readProjectFilm } from './fil
import { FileError, bringIn, collect, extractAudio, freezeFrame, importFile, inside, listFiles, makeFolder, moveCheck, moveFile, readable, relink, trashFile } from './files.mjs';
import { ExportError, createExports, draftApps, exportCapabilities, exportsRoot, projectSizes } from './exports.mjs';
import { MediaError, frame, loudness, poster, probe, waveform } from './derived.mjs';
-import { HistoryError, checkout, commitChanges, deleteBranch, discardChanges, historyFiles, log, mergeBranch, renameBranch, restoreCommit, status as historyStatus } from './history.mjs';
+import { HistoryError, checkoutVersion, copyVersion, deleteVersions, discardChanges, log, recoverVersions, saveVersion, status as historyStatus, versionFilesChanged } from './history.mjs';
+import { createAutoVersions } from './auto-versions.mjs';
+import { createHistoryPreviews } from './history-previews.mjs';
import { ownHost, startPages } from './pages.mjs';
import { HttpError, cookie, json, readJson } from './http.mjs';
import { acceptWebSocket } from './websocket.mjs';
@@ -41,7 +43,6 @@ import { readPrefs, writePrefs } from './prefs.mjs';
import { ensureProxies } from './proxies.mjs';
import { ensurePreviews, knownLate } from './preview-cache.mjs';
import { npmOpenfilm, olderThanThis } from '../client.mjs';
-import { writeAtomic } from './atomic.mjs';
import { createWatchers } from './watch.mjs';
import { projectMissing } from './project-presence.mjs';
import { installedFonts } from './fonts.mjs';
@@ -108,7 +109,8 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
/** The key from either session cookie. */
const cookieKey = (/** @type {Req} */ req) => (sameKey(cookie(req, COOKIE)) ? cookie(req, COOKIE) : cookie(req, FRAMED));
key ??= advertise ? studioKey() : randomBytes(24).toString('hex');
- const watchers = createWatchers();
+ /* every change of an open project's folder: a version once it rests, when the person asked for that */
+ const watchers = createWatchers({ onChange: (root, e) => { if (e.type === 'film' || e.type === 'files') autoVersions.changed(root); } });
/** questions about spending for the person, in the pages showing a project (see get.mjs) */
const asks = createAsks({ emit: (root, event) => watchers.emit(root, event), roots: watchers.roots });
/** the editor pages open right now, and whether each is in sight: `/open` switches them to a project */
@@ -122,6 +124,16 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
let updating = /** @type {{ status: 'updating' | 'failed', version: string, error?: string } | null} */ (null);
/** whether an app's agent is working in the project at `path` now */
const agentIn = (/** @type {string} */ path) => working().some((folder) => resolve(folder) === resolve(path));
+ /** The project at `root`'s history changed: its pages hear of it. `moved`: the folder's files changed with it. */
+ const historyChanged = (/** @type {string} */ root, { moved = false } = {}) => watchers.emit(root, { type: 'history', ...(moved ? { moved: true } : {}) });
+ /* versions saved on their own (auto-versions.mjs), while the person has Auto versions on */
+ const autoVersions = createAutoVersions({
+ on: () => readPrefs().autoVersions,
+ working: agentIn,
+ roots: () => watchers.roots(),
+ save: async (root, kind) => { if (await saveVersion(root, { kind })) historyChanged(root); },
+ });
+ autoVersions.start();
/** how many editor pages have connected since Studio started: whether one opened an address `/open` gave out */
let pagesConnected = 0;
/** @type {(event: unknown) => void} */
@@ -616,89 +628,66 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
const page = url.searchParams.get('page');
return json(res, 200, await projectFonts(project.path, page ? resolveIn('', page) : null));
}
- /* ── version history: git, every change of it the person's (history.mjs) ──
- GET history → { status, commits }: the branch checked out, the branches, the
- uncommitted changes, the film's files against the folder's, and
- the commits of the branch, newest first
- GET history/files → { held, ignored }: the film's files, and the others (never kept)
- GET history/poster/:commit the film's picture when it was committed (404: none was taken)
- POST history/commit { message } commit the uncommitted changes
- POST history/discard put the film back as the last commit holds it
- POST history/restore { commit } the film as a commit holds it, as uncommitted changes
- POST history/checkout { branch, create?, from?, carry? } check out a branch (or make one)
- PATCH history/branches/:name { name } rename a branch
- DELETE history/branches/:name[?force=1] delete one
- POST history/merge { branch, message, prefer? } merge a branch into the one checked out
- Every change tells the project's pages ({ type: 'history' }); one that changed the folder, the film too. While
- one runs, they hear how far it is ({ type: 'history-progress', op, phase, done, total }). */
+ /* ── version history (history.mjs) ──
+ GET history[?limit=n] → { status, versions, more }: the version checked out and the changes
+ against it, and the versions, newest first, with their parents
+ GET history/versions/:commit → { files }: what that version changed
+ GET history/versions/:commit/preview → { folder, doc, missing }: a read-only copy on the film origin
+ POST history/save { message? } commit the changes as a version
+ POST history/discard the folder as the version checked out holds it
+ POST history/checkout { commit, discard? } check out a version (no version is made)
+ POST history/copy { commit, name } a new project holding that version → { project, missing }
+ Every change tells the project's pages ({ type: 'history' }; `moved`: the folder's files changed, so Studio's
+ state of the film is read again). While one runs, they hear how far it is ({ type: 'history-progress', op,
+ phase, done, total }). */
if (parts[2] === 'history') {
const history = parts.slice(3);
- const changed = () => watchers.emit(project.path, { type: 'history' });
/** @param {string} op */
const onProgress = (op) => (/** @type {{ phase: string, done: number, total: number }} */ p) => watchers.emit(project.path, { type: 'history-progress', op, ...p });
if (!history.length && req.method === 'GET') {
- const [state, commits] = await Promise.all([historyStatus(project.path, { onProgress: onProgress('load') }), log(project.path)]);
- return json(res, 200, { status: state, commits });
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 50, 1), 1000);
+ const [state, { versions, more, deletedCount }] = await Promise.all([historyStatus(project.path, { onProgress: onProgress('load') }), log(project.path, { limit, deleted: url.searchParams.get('deleted') === '1', includeDeletedCount: true })]);
+ return json(res, 200, { status: state, versions, more, deletedCount });
}
- if (history[0] === 'files' && history.length === 1 && req.method === 'GET') return json(res, 200, await historyFiles(project.path));
- if (history[0] === 'poster' && history.length === 2 && req.method === 'GET') {
- if (!/^[0-9a-f]{40}$/.test(history[1])) throw new HttpError(400, 'which commit?');
- const jpeg = await readFile(join(project.path, TOOL_DIR, 'cache', 'commits', `${history[1]}.jpg`)).catch(() => null);
- if (!jpeg) throw new HttpError(404, 'no picture of that commit');
- res.writeHead(200, { 'content-type': 'image/jpeg', 'cache-control': 'private, max-age=31536000, immutable', 'content-length': jpeg.length });
- return res.end(jpeg);
+ if (history[0] === 'versions' && history.length === 2 && req.method === 'GET') return json(res, 200, { files: await versionFilesChanged(project.path, history[1]) });
+ if (history[0] === 'versions' && history.length === 3 && history[2] === 'preview' && req.method === 'GET') {
+ const snapshot = await historyPreviews.get(project.path, history[1]);
+ const film = await readProjectFilm(snapshot.path);
+ return json(res, 200, {
+ folder: pages.folderUrl({ id: `${project.id}/history/${history[1]}`, path: snapshot.path }),
+ doc: film.doc, missing: snapshot.missing,
+ });
}
- if (history[0] === 'commit' && req.method === 'POST') {
+ if (history[0] === 'save' && req.method === 'POST') {
const { message } = /** @type {{ message?: string }} */ (await readJson(req));
- const sha = await commitChanges(project.path, String(message ?? ''), { onProgress: onProgress('commit') });
- changed();
- /* the film's picture as it was committed, for the commit's card: drawn after the answer (it takes a moment) */
- void pageFrame(project.path, pages.folderUrl(project), FILM_PAGE, -1, 480)
- .then(async (jpeg) => {
- const dir = join(project.path, TOOL_DIR, 'cache', 'commits');
- await mkdir(dir, { recursive: true });
- await writeAtomic(join(dir, `${sha}.jpg`), jpeg);
- })
- .then(changed, () => {});
+ const sha = await saveVersion(project.path, { message: String(message ?? ''), onProgress: onProgress('save') });
+ historyChanged(project.path);
return json(res, 200, { commit: sha });
}
- if (history[0] === 'discard' && req.method === 'POST') {
- await discardChanges(project.path, { onProgress: onProgress('discard') });
- changed();
- return json(res, 200, await readProjectFilm(project.path));
+ if ((history[0] === 'delete' || history[0] === 'recover') && history.length === 1 && req.method === 'POST') {
+ const { commits } = /** @type {{ commits?: unknown }} */ (await readJson(req));
+ const done = history[0] === 'delete' ? await deleteVersions(project.path, commits) : await recoverVersions(project.path, commits);
+ if (history[0] === 'delete') await historyPreviews.invalidate(project.path, done.commits);
+ historyChanged(project.path);
+ return json(res, 200, done);
}
- if (history[0] === 'restore' && req.method === 'POST') {
- const { commit: target } = /** @type {{ commit?: string }} */ (await readJson(req));
- const { missing } = await restoreCommit(project.path, String(target ?? ''), { onProgress: onProgress('restore') });
- changed();
- /* `missing`: media of that version history no longer has (left as it is in the folder) */
- return json(res, 200, { missing, ...(await readProjectFilm(project.path)) });
+ if (history[0] === 'discard' && req.method === 'POST') {
+ const done = await discardChanges(project.path, { onProgress: onProgress('discard') });
+ historyChanged(project.path, { moved: true });
+ return json(res, 200, { ...done, ...(await readProjectFilm(project.path)) });
}
if (history[0] === 'checkout' && req.method === 'POST') {
- const { branch, create, from, carry } = /** @type {{ branch?: string, create?: boolean, from?: string, carry?: 'leave' | 'bring' }} */ (await readJson(req));
- const back = await checkout(project.path, { target: String(branch ?? ''), create: create === true, ...(from ? { from: String(from) } : {}), carry: carry === 'bring' ? 'bring' : 'leave', onProgress: onProgress('checkout') });
- changed();
- /* `parkedBack` false: the changes left on that branch collide with it now and stay put away */
- return json(res, 200, { parkedBack: back, ...(await readProjectFilm(project.path)) });
- }
- if (history[0] === 'branches' && history.length === 2) {
- if (req.method === 'PATCH') {
- const { name } = /** @type {{ name?: string }} */ (await readJson(req));
- const renamed = await renameBranch(project.path, history[1], String(name ?? ''));
- changed();
- return json(res, 200, { name: renamed });
- }
- if (req.method === 'DELETE') {
- await deleteBranch(project.path, history[1], { force: url.searchParams.get('force') === '1' });
- changed();
- return json(res, 200, {});
- }
+ const { commit: target, discard } = /** @type {{ commit?: string, discard?: boolean }} */ (await readJson(req));
+ const done = await checkoutVersion(project.path, String(target ?? ''), { discard: discard === true, onProgress: onProgress('checkout') });
+ historyChanged(project.path, { moved: true });
+ /* `missing`: media of that version history no longer has (left as it is in the folder) */
+ return json(res, 200, { ...done, ...(await readProjectFilm(project.path)) });
}
- if (history[0] === 'merge' && req.method === 'POST') {
- const { branch, message, prefer } = /** @type {{ branch?: string, message?: string, prefer?: string }} */ (await readJson(req));
- const merged = await mergeBranch(project.path, { branch: String(branch ?? ''), message: String(message ?? ''), ...(prefer === 'ours' || prefer === 'theirs' ? { prefer } : {}), onProgress: onProgress('merge') });
- changed();
- return json(res, 200, { merged, ...(await readProjectFilm(project.path)) });
+ if (history[0] === 'copy' && req.method === 'POST') {
+ const { commit: target, name } = /** @type {{ commit?: string, name?: string }} */ (await readJson(req));
+ const copy = await createProject(String(name ?? '').trim() || `${project.name} copy`);
+ const { missing } = await copyVersion(project.path, String(target ?? ''), copy.path, { onProgress: onProgress('copy') });
+ return json(res, 200, { project: copy, missing });
}
throw new HttpError(404, 'no such history action');
}
@@ -969,7 +958,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
if (res.headersSent) return res.end();
json(res, status, { error: e instanceof Error ? e.message : String(e), ...(e instanceof HttpError ? e.extra : {}),
...((e instanceof ProjectError || e instanceof FetchError || e instanceof BrowseError) && e.code ? { code: e.code } : {}),
- ...(e instanceof HistoryError && e.code ? { code: e.code, ...('commits' in e ? { commits: e.commits } : {}) } : {}) });
+ ...(e instanceof HistoryError && e.code ? { code: e.code } : {}) });
});
});
/* the streams: the key, as for the API, and only from the editor's own origin (another site's page could otherwise
@@ -1019,6 +1008,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
COOKIE = cookieName(address.port);
FRAMED = framedCookieName(address.port);
/* the film's port is the next one: when it is not free, the editor's is let go again, so a caller can try others */
+ const historyPreviews = createHistoryPreviews();
const pages = await startPages({ port: port ? address.port + 1 : 0, editorOrigin: () => origin, secret: key, projects: listProjects }).catch(async (e) => {
watchers.closeAll();
await new Promise((done) => editor.close(() => done(undefined)));
@@ -1047,6 +1037,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
/* a running export stops, and cleans up after itself while the rest closes: its half-made files go before Studio */
const exporting = exports.stopAll();
fetches.stopAll();
+ autoVersions.stop();
await closePageFrames();
watchers.closeAll();
await pages.close();
@@ -1054,6 +1045,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
for (const socket of streamSockets) socket.destroy();
await new Promise((done) => editor.close(() => done(undefined)));
await exporting;
+ await historyPreviews.close();
}
return studio;
}
diff --git a/packages/openfilm/studio/server/server.test.mjs b/packages/openfilm/studio/server/server.test.mjs
index 14a3607..f5a0c5c 100644
--- a/packages/openfilm/studio/server/server.test.mjs
+++ b/packages/openfilm/studio/server/server.test.mjs
@@ -328,10 +328,10 @@ test('an open project keeps film, file, history and export events after rename w
writeFileSync(join(renamed.path, 'scene.html'), '<p>after rename</p>');
await waitFor((e) => e.type === 'film' && e.rev, 'the existing socket sees the new film revision');
await waitFor((e) => e.type === 'files' && e.paths?.includes('scene.html'), 'the existing socket sees new files');
- const committed = await api(`/api/projects/${project.id}/history/commit`, { method: 'POST', body: { message: 'After rename' } });
- assert.equal(committed.status, 200);
+ const saved = await api(`/api/projects/${project.id}/history/save`, { method: 'POST', body: { name: 'After rename' } });
+ assert.equal(saved.status, 200);
await waitFor((e) => e.type === 'history', 'the existing socket sees history changes');
- assert.ok(events.some((e) => e.type === 'history-progress' && e.op === 'commit'));
+ assert.ok(events.some((e) => e.type === 'history-progress' && e.op === 'save'));
const started = await api(`/api/projects/${project.id}/exports`, { method: 'POST', body: { kind: 'project', as: 'folder' } });
assert.equal(started.status, 200);
const job = (await started.json()).export;
@@ -370,7 +370,7 @@ test('the preview plays heavy footage from its proxy once made; what the file is
mkdirSync(join(project.path, 'assets'), { recursive: true });
const big = join(project.path, 'assets', 'big.mp4');
execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'testsrc=size=2560x1440:rate=25:duration=1', '-pix_fmt', 'yuv420p', big]);
- assert.deepEqual(await (await api('/api/prefs')).json(), { proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: null, keys: null });
+ assert.deepEqual(await (await api('/api/prefs')).json(), { proxies: { on: true, height: 720 }, seenVersion: null, projectsFolder: null, keys: null, autoVersions: false, showAutoVersions: false });
let answer;
for (const end = Date.now() + 30_000; answer?.states?.['assets/big.mp4']?.state !== 'ready' && Date.now() < end;) {
answer = await (await api(`/api/projects/${project.id}/proxies`, { method: 'POST', body: {} })).json();
@@ -383,7 +383,7 @@ test('the preview plays heavy footage from its proxy once made; what the file is
assert.ok(played > 0 && played !== statSync(big).size, 'the proxy');
assert.equal(await size('?film-facts=1'), statSync(big).size, 'what the file is: the file');
/* off: the original, and no proxy asked for */
- assert.deepEqual(await (await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: false } } })).json(), { proxies: { on: false, height: 720 }, seenVersion: null, projectsFolder: null, keys: null });
+ assert.deepEqual(await (await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: false } } })).json(), { proxies: { on: false, height: 720 }, seenVersion: null, projectsFolder: null, keys: null, autoVersions: false, showAutoVersions: false });
assert.equal(await size(), statSync(big).size);
assert.deepEqual((await (await api(`/api/projects/${project.id}/proxies`, { method: 'POST', body: {} })).json()).states, {});
await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: true } } });
@@ -487,33 +487,110 @@ test('files over the API: import a body of any size, list, move with film.html f
}
});
-test('history: nothing is committed on its own; the person commits, goes back as uncommitted changes, branches', async () => {
+test('history: the person commits versions; checking one out makes none and tells every page; a copy is a new project', async () => {
const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'History') } })).json();
const history = (path = '', body, method = body ? 'POST' : 'GET') => api(`/api/projects/${project.id}/history${path}`, { method, ...(body ? { body } : {}) });
writeFileSync(join(project.path, 'film.html'), filmHtml({ stage: { w: 640, h: 360 }, tracks: [] }));
await api(`/api/projects/${project.id}/edit`, { method: 'POST', body: { ops: [{ op: 'stage', w: 800, h: 450 }] } });
await new Promise((r) => setTimeout(r, 500));
const before = await (await history()).json();
- assert.deepEqual(before.commits, [], 'nothing committed by the agent\'s writes or the person\'s edits');
- assert.ok(before.status.changes, 'they are uncommitted changes');
- assert.equal((await history('/commit', { message: ' ' })).status, 400);
+ assert.deepEqual(before.versions, [], 'nothing committed by the agent\'s writes or the person\'s edits while Auto versions is off');
+ assert.deepEqual(before.status.changes.files.map((f) => f.change), ['added'], 'the changes, as files');
const events = collect(`/api/projects/${project.id}/events`, (e) => e.some((x) => x.type === 'history'));
- const { commit } = await (await history('/commit', { message: 'Wide' })).json();
- assert.ok((await events).some((e) => e.type === 'history-progress' && e.op === 'commit'), 'how far it is, while it runs');
+ const { commit } = await (await history('/save', { message: 'Wide' })).json();
+ assert.ok((await events).some((e) => e.type === 'history-progress' && e.op === 'save'), 'how far it is, while it runs');
+ const nothing = await history('/save', {});
+ assert.equal(nothing.status, 409);
+ assert.equal((await nothing.json()).code, 'nothing', 'the editor says why in its own words');
writeFileSync(join(project.path, 'film.html'), filmHtml({ stage: { w: 1, h: 1 }, tracks: [] }));
- const dirty = await history('/restore', { commit });
+ const { commit: square } = await (await history('/save', { message: 'Square' })).json();
+ assert.deepEqual((await (await history(`/versions/${square}`)).json()).files, [{ path: 'film.html', change: 'modified' }]);
+ writeFileSync(join(project.path, 'film.html'), filmHtml({ stage: { w: 2, h: 2 }, tracks: [] }));
+ const dirty = await history('/checkout', { commit });
assert.equal(dirty.status, 409);
- assert.equal((await dirty.json()).code, 'dirty', 'the editor says why in its own words');
+ assert.equal((await dirty.json()).code, 'dirty');
+ const moved = collect(`/api/projects/${project.id}/events`, (e) => e.some((x) => x.type === 'history' && x.moved));
+ const back = await (await history('/checkout', { commit, discard: true })).json();
+ assert.deepEqual(back.doc.stage, { w: 800, h: 450 });
+ assert.ok(await moved, 'the pages read Studio\'s state of the film again');
+ const after = await (await history()).json();
+ assert.deepEqual([after.status.head, after.status.branch, after.status.changes], [commit, null, null]);
+ assert.deepEqual(after.versions.map((v) => v.name), ['Square', 'Wide'], 'no version of its own');
+ writeFileSync(join(project.path, 'film.html'), filmHtml({ stage: { w: 3, h: 3 }, tracks: [] }));
const discarded = await (await history('/discard', {})).json();
assert.deepEqual(discarded.doc.stage, { w: 800, h: 450 });
- const branched = await (await history('/checkout', { branch: 'square', create: true })).json();
- assert.equal(branched.parkedBack, true);
+ const copied = await (await history('/copy', { commit: square, name: 'History, square' })).json();
+ assert.equal(copied.project.name, 'History, square');
+ assert.match(readFileSync(join(copied.project.path, 'film.html'), 'utf8'), /width=1, height=1|"w":1|1x1|content="width=1/);
+ assert.equal((await history('/restore', { commit })).status, 404, 'no restore that makes a version');
+});
+
+test('history previews play saved files and media on the film origin without changing the working project', async () => {
+ const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'History preview') } })).json();
+ const history = (path = '', body) => api(`/api/projects/${project.id}/history${path}`, body ? { method: 'POST', body } : {});
+ const film = (w) => filmHtml({ stage: { w, h: 450 }, tracks: [{ clips: [{ id: 'title', src: 'title.html', at: 0, time: [0, 2] }] }] });
+ writeFileSync(join(project.path, 'film.html'), film(800));
+ writeFileSync(join(project.path, 'title.html'), '<!-- saved title --><img src="cover.png">');
+ writeFileSync(join(project.path, 'cover.png'), 'saved image bytes');
+ writeFileSync(join(project.path, '.film', 'settings.json'), '{"fps":24}');
+ const { commit: first } = await (await history('/save', { message: 'First' })).json();
+ writeFileSync(join(project.path, 'film.html'), film(1200));
+ writeFileSync(join(project.path, 'cover.png'), 'new image bytes');
+ const { commit: second } = await (await history('/save', { message: 'Second' })).json();
+ writeFileSync(join(project.path, 'title.html'), '<!-- unsaved title --><img src="cover.png">');
+ const before = await (await history()).json();
+ const previewPath = `/versions/${first}/preview`;
+ const [one, two] = await Promise.all([history(previewPath), history(previewPath)]);
+ assert.equal(one.status, 200);
+ const preview = await one.json();
+ assert.equal(preview.folder, (await two.json()).folder, 'concurrent requests share the complete snapshot');
+ assert.deepEqual(preview.doc.stage, { w: 800, h: 450 });
+ assert.deepEqual(preview.missing, []);
+ assert.equal(new URL(preview.folder).origin, studio.filmOrigin, 'film code runs apart from the editor');
+ assert.match(await (await fetch(`${preview.folder}title.html`)).text(), /saved title/);
+ assert.equal(await (await fetch(`${preview.folder}cover.png`)).text(), 'saved image bytes', 'same-name media comes from the selected version');
+ assert.equal((await fetch(`${preview.folder}%2efilm/settings.json`)).status, 404, 'snapshot internals stay private');
+ const newer = await (await history(`/versions/${second}/preview`)).json();
+ assert.notEqual(newer.folder, preview.folder);
+ assert.equal(await (await fetch(`${newer.folder}cover.png`)).text(), 'new image bytes');
+ assert.match(readFileSync(join(project.path, 'title.html'), 'utf8'), /unsaved title/);
+ const after = await (await history()).json();
+ assert.deepEqual(after, before, 'HEAD, changes and the version list are untouched');
+ assert.equal((await history('/versions/not-a-commit/preview')).status, 400);
+ assert.equal((await history(`/versions/${'0'.repeat(40)}/preview`)).status, 404);
+ assert.equal((await api(`/api/projects/${project.id}/history${previewPath}`, { key: null })).status, 401);
+});
+
+test('history deletion is selectable, authenticated, recoverable, and protects the version in use', async () => {
+ const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Delete history') } })).json();
+ const history = (path = '', body) => api(`/api/projects/${project.id}/history${path}`, body ? { method: 'POST', body } : {});
+ writeFileSync(join(project.path, 'film.html'), filmHtml({ stage: { w: 640, h: 360 }, tracks: [] }));
+ const { commit: first } = await (await history('/save', { message: 'First' })).json();
+ writeFileSync(join(project.path, 'film.html'), filmHtml({ stage: { w: 800, h: 450 }, tracks: [] }));
+ const { commit: second } = await (await history('/save', { message: 'Current' })).json();
+ const prepared = await (await history(`/versions/${first}/preview`)).json();
+ const before = await (await history()).json();
+ const protectedVersion = await history('/delete', { commits: [first, second] });
+ assert.equal(protectedVersion.status, 409);
+ assert.equal((await protectedVersion.json()).code, 'current');
+ assert.equal((await api(`/api/projects/${project.id}/history/delete`, { method: 'POST', key: null, body: { commits: [first] } })).status, 401);
+ const events = collect(`/api/projects/${project.id}/events`, (items) => items.some((event) => event.type === 'history'));
+ assert.equal((await history('/delete', { commits: [first] })).status, 200);
+ assert.ok((await events).some((event) => event.type === 'history' && !event.moved), 'deleting records does not reload the working film');
const after = await (await history()).json();
- assert.equal(after.status.branch, 'square');
- assert.deepEqual(after.status.files, { held: 1, heldBytes: after.status.files.heldBytes, ignored: 0 }, 'the film, and nothing else in the folder');
- assert.deepEqual((await (await history('/files')).json()).held.map((f) => f.path), ['film.html']);
- assert.deepEqual(after.commits.map((c) => c.message), ['Wide'], 'no commit of its own on the way');
- assert.equal((await history('/branches/square', undefined, 'DELETE')).status, 409, 'not the branch checked out');
+ assert.deepEqual(after.status, before.status);
+ assert.deepEqual(after.versions.map((version) => version.commit), [second]);
+ assert.equal(after.deletedCount, 1);
+ const deleted = await (await history('?deleted=1')).json();
+ assert.deepEqual(deleted.versions.map((version) => version.commit), [first]);
+ assert.equal((await history(`/versions/${first}/preview`)).status, 409, 'prepared previews cannot bypass deletion');
+ assert.equal((await fetch(`${prepared.folder}film.html`)).status, 404, 'the prepared read-only snapshot was cleared');
+ assert.equal((await history('/recover', { commits: [first] })).status, 200);
+ const recovered = await (await history()).json();
+ assert.deepEqual(recovered.status, before.status);
+ assert.equal(recovered.deletedCount, 0);
+ assert.deepEqual(recovered.versions.map((version) => version.commit), [second, first]);
+ assert.equal((await history(`/versions/${first}/preview`)).status, 200);
});
test('a project whose folder is gone says so, never takes Studio down, and can be taken off the list', async () => {
diff --git a/packages/openfilm/studio/server/watch.mjs b/packages/openfilm/studio/server/watch.mjs
index 70c567f..dee757f 100644
--- a/packages/openfilm/studio/server/watch.mjs
+++ b/packages/openfilm/studio/server/watch.mjs
@@ -27,9 +27,11 @@ const WRITING = /(^|[/\\])([^/\\]+\.[0-9a-f-]{8,}\.tmp|\.\d+\.\d+\.importing)$/;
* `files`: `paths` are the files that changed (folder relative), or none when the system could not say.
* `ask` / `asked`: a question about spending for the person, and that it was answered; `notice`: something the person
* is told, such as a provider with no balance left (get.mjs).
- * `history-progress`: how far a version history action is (history.mjs), `op` the action ('commit', 'checkout'…).
+ * `history`: the version history changed (history.mjs); `moved`: its action changed the folder's files (a version
+ * restored), so Studio's own state of the film is read again. `history-progress`: how far an action is, `op` which
+ * ('save', 'restore'…).
* `project`: the project renamed, as it is now.
- * @typedef {{ type: 'film', rev: string } | { type: 'files', paths?: string[] } | { type: 'history' } | { type: 'export', job: object }
+ * @typedef {{ type: 'film', rev: string } | { type: 'files', paths?: string[] } | { type: 'history', moved?: boolean } | { type: 'export', job: object }
* | { type: 'history-progress', op: string, phase: string, done: number, total: number } | { type: 'project', project: object }
* | { type: 'ask', ask: object } | { type: 'asked', id: string } | { type: 'notice', notice: object }
* | { type: 'gone' }} FolderEvent `gone`: the project was deleted, or its folder or film file is missing
@@ -144,14 +146,15 @@ export function watchTree(root, onChange, native = process.platform === 'darwin'
/**
* Every project someone is watching, and who: `subscribe` starts the folder's watcher with its first listener and stops
- * it with its last.
+ * it with its last. `onChange` hears every change of a watched folder itself (not what `emit` tells).
+ * @param {{ onChange?: (root: string, e: FolderEvent) => void }} [o]
*/
-export function createWatchers() {
+export function createWatchers({ onChange } = {}) {
/** @typedef {{ root: string, listener: (e: FolderEvent) => void }} Subscription */
/** @type {Map<string, { close: () => void, listeners: Set<Subscription> }>} */
const byRoot = new Map();
/** @param {string} root @param {Set<Subscription>} listeners */
- const start = (root, listeners) => ({ listeners, close: watchFolder(root, (e) => { for (const { listener } of listeners) listener(e); }) });
+ const start = (root, listeners) => ({ listeners, close: watchFolder(root, (e) => { onChange?.(root, e); for (const { listener } of listeners) listener(e); }) });
return {
/** @param {string} root @param {(e: FolderEvent) => void} listener */
subscribe(root, listener) {
diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.ts
index 1c90d44..0508d87 100644
--- a/packages/openfilm/studio/ui/src/api.ts
+++ b/packages/openfilm/studio/ui/src/api.ts
@@ -85,6 +85,8 @@ export interface StudioPrefs {
projectsFolder: string | null;
/** the keyboard shortcuts: the scheme in use and the custom ones (lib/keymap `KeyPrefs`, checked there) */
keys?: unknown;
+ /** whether open projects save versions on their own (studio/server/auto-versions.mjs) */
+ autoVersions?: boolean;
}
/** Where the projects library is (src/locations.mjs): the folder, its default, whether the person chose it, the free space on its disk, how many projects are in it. */
export interface StudioLocation { path: string; default: string; chosen: boolean; free: number | null; count: number }
@@ -127,7 +129,7 @@ export const api = {
revealProject: (id: string) => call<object>(`projects/${encodeURIComponent(id)}/reveal`, { method: 'POST', json: {} }),
/** one of them in the system's file manager */
openLocation: (which: keyof StudioLocations) => call<{ ok: true }>(`locations/${which}`, { method: 'POST', json: {} }),
- setPrefs: (patch: { proxies?: Partial<StudioPrefs['proxies']>; seenVersion?: string; projectsFolder?: string | null; keys?: unknown }) => call<StudioPrefs>('prefs', { method: 'PATCH', json: patch }).then((prefs) => {
+ setPrefs: (patch: { proxies?: Partial<StudioPrefs['proxies']>; seenVersion?: string; projectsFolder?: string | null; keys?: unknown; autoVersions?: boolean }) => call<StudioPrefs>('prefs', { method: 'PATCH', json: patch }).then((prefs) => {
window.dispatchEvent(new Event(PREFS_EVENT));
return prefs;
}),
diff --git a/packages/openfilm/studio/ui/src/components/MenuSelect.tsx b/packages/openfilm/studio/ui/src/components/MenuSelect.tsx
index ecabcc3..dc20d89 100644
--- a/packages/openfilm/studio/ui/src/components/MenuSelect.tsx
+++ b/packages/openfilm/studio/ui/src/components/MenuSelect.tsx
@@ -14,7 +14,7 @@ export type MenuChoice = { value: string; label: string };
export type MenuGroup = { label?: string; choices: MenuChoice[] };
export function MenuSelect({
- label, value, groups, onPick, onPreview, onRevert, disabled = false, className = '', size = 'sm', prefix,
+ label, value, groups, onPick, onPreview, onRevert, disabled = false, className = '', size = 'sm', prefix, menuWidth = 'trigger',
}: {
/** what it chooses, for screen readers (the field shows the choice) */
label: string;
@@ -31,6 +31,8 @@ export function MenuSelect({
size?: 'sm' | 'md';
/** A word before the choice (Blend), as the inspector's other fields have their mark. */
prefix?: string;
+ /** Long choices can size the open menu independently of a compact field. */
+ menuWidth?: 'trigger' | 'content';
}) {
const [open, setOpen] = React.useState(false);
const [width, setWidth] = React.useState(0);
@@ -54,7 +56,7 @@ export function MenuSelect({
if (!open && previewing.current) { previewing.current = false; onRevert?.(); }
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps
- /* opened: as wide as the field, the chosen one in view and lit for the keys */
+ /* opened: at least as wide as the field, the chosen one in view and lit for the keys */
React.useLayoutEffect(() => {
if (!open) return;
setWidth(triggerRef.current?.getBoundingClientRect().width ?? 0);
@@ -123,7 +125,12 @@ export function MenuSelect({
onKeyDown={onKeyDown}
onMouseLeave={() => show(undefined)}
className="relative overflow-y-auto rounded-[8px] border border-[var(--border)] bg-[var(--panel)] p-1 shadow-[var(--shadow-lg)]"
- style={{ width: Math.max(width, 160), maxHeight: 'min(320px, var(--popover-max-h, 320px))' }}
+ style={{
+ width: menuWidth === 'content' ? 'max-content' : Math.max(width, 160),
+ minWidth: Math.max(width, 160),
+ maxWidth: 'calc(100vw - 24px)',
+ maxHeight: 'min(320px, var(--popover-max-h, 320px))',
+ }}
>
{groups.map((group, g) => (
<div key={group.label ?? g} role="group" aria-label={group.label}>
diff --git a/packages/openfilm/studio/ui/src/components/ProjectHistoryControls.tsx b/packages/openfilm/studio/ui/src/components/ProjectHistoryControls.tsx
index 5ac16df..9fe9925 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectHistoryControls.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectHistoryControls.tsx
@@ -1,60 +1,62 @@
-/**
- * The Version history panel: git, as a person knows it from GitHub, told as a film.
- *
- * ⑂ main ▾ the branch checked out; its menu lists every branch (switch, merge, rename, delete) and
- * makes new ones
- * Uncommitted changes what the film has that the last commit does not, in scenes and sounds; a message and
- * Commit, or Discard
- * History · main the branch's commits, newest first, each with the film's picture when it was committed
- * and what it changed; ⋯ restores one (as uncommitted changes) or branches from it
- * In history / Not in history the film's files (what a commit keeps) and the folder's others, which history
- * leaves alone; each opens to its list
- *
- * Every commit is the person's, made with their message; nothing here commits on its own. Going back to a version
- * puts it in the folder as uncommitted changes; switching branches with changes asks whether to leave them on their
- * branch (they are there again on coming back) or bring them along. Data and actions come from `useProjectHistory`.
- */
+/** Version history: a date-ordered list, the selected version's film, and the files it changed. */
import React from 'react';
import { createPortal } from 'react-dom';
-import { Check, ChevronDown, ChevronRight, Clapperboard, GitBranch, GitMerge, Loader2, MoreHorizontal, Pencil, Plus, Tag, Trash2, Undo2, X } from 'lucide-react';
-import { useT } from '@/i18n';
-import { formatBytes } from '@/lib/export-jobs';
import {
- commitPoster, historyAge, historyApi, summaryParts, type Branch, type Commit, type HistoryFile, type HistoryFiles, type HistoryProgress, type Summary,
+ Bookmark,
+ Check,
+ ChevronRight,
+ Clock3,
+ File,
+ Film,
+ History,
+ ListFilter,
+ ListChecks,
+ Loader2,
+ Plus,
+ RotateCcw,
+ Save,
+ Search,
+ Undo2,
+ Trash2,
+ X,
+} from 'lucide-react';
+import { useLanguage, useT } from '@/i18n';
+import {
+ filterHistoryVersions,
+ HISTORY_VERSION_TYPES,
+ historyApi,
+ historyVersionType,
+ versionLabel,
+ type Change,
+ type HistoryProgress,
+ type HistoryVersionType,
+ type HistoryState,
+ type Version,
} from '@/lib/project-history';
-import { Card, CardActions, CardButton, POPOVER_CHROME } from './Card';
-import { ContextMenu, type ContextMenuEntry } from './ContextMenu';
+import { Card, CardActions, CardButton } from './Card';
+import { LARGE_DIALOG, LARGE_DIALOG_BACKDROP } from './dialog-chrome';
import { Tooltip } from './Tooltip';
+import { VersionVideoPreview } from './VersionVideoPreview';
import type { ProjectHistory } from './use-project-history';
-const PANEL_W = 400;
-
type Translate = (key: string) => string;
+type Dialog = { kind: 'save' } | { kind: 'discard' } | { kind: 'restore' | 'copy'; version: Version } | { kind: 'delete'; commits: string[] };
-function ageLabel(at: number, now: number, t: Translate): string {
- const age = historyAge(at, now);
- if (!age) return '';
- if (age.unit === 'now') return t('history.justNow');
- const key = age.unit === 'minute' ? 'history.minutesAgo' : age.unit === 'hour' ? 'history.hoursAgo' : 'history.daysAgo';
- return t(key).replace('{n}', String(age.n));
-}
-
-/** How far an action is, in a few words: "Keeping media… 3 of 20". */
function progressText(progress: HistoryProgress, t: Translate): string {
- const key = { scan: 'versions.progressScan', store: 'versions.progressStore', write: 'versions.progressWrite', migrate: 'versions.progressMigrate' }[progress.phase];
+ const key = {
+ scan: 'versions.progressScan',
+ store: 'versions.progressStore',
+ write: 'versions.progressWrite',
+ migrate: 'versions.progressMigrate',
+ }[progress.phase];
return t(key).replace('{done}', String(progress.done)).replace('{total}', String(progress.total));
}
-/** What changed, as a short sentence: "2 scenes added · 1 sound edited". */
-function summaryText(summary: Summary, t: Translate): string {
- return summaryParts(summary).map(({ key, n }) => t(`versions.${key}${n === 1 ? 'One' : ''}`).replace('{n}', String(n))).join(' · ');
-}
-
-/**
- * The top bar's Version history button (GitBranch). It carries `data-history-trigger`, which the panel's
- * click-outside check recognizes, so clicking it again toggles the panel instead of closing and reopening it.
- */
-export function ProjectHistoryButton({ open, onClick, className }: {
+export function ProjectHistoryButton({
+ open,
+ onClick,
+ className,
+}: {
open: boolean;
onClick: () => void;
className?: string;
@@ -66,646 +68,854 @@ export function ProjectHistoryButton({ open, onClick, className }: {
type="button"
onClick={onClick}
aria-label={t('projectMenu.history')}
+ aria-haspopup="dialog"
aria-expanded={open}
- data-history-trigger=""
className={className}
>
- <GitBranch size={16} />
+ <History size={16} />
</button>
</Tooltip>
);
}
-/** The questions the panel asks, one at a time. */
-type Dialog =
- | { kind: 'switch'; target: string }
- | { kind: 'newBranch'; from?: Commit }
- | { kind: 'newBranchCarry'; name: string; from: Commit }
- | { kind: 'rename'; branch: string }
- | { kind: 'delete'; branch: string }
- | { kind: 'deleteForce'; branch: string; commits: number }
- | { kind: 'merge'; branch: string }
- | { kind: 'mergeConflict'; branch: string; message: string }
- | { kind: 'restore'; commit: Commit }
- | { kind: 'discard' };
-
export function ProjectHistoryControls({
projectId,
+ projectName,
history,
open,
- anchor,
onClose,
+ onOpenProject,
}: {
projectId: string;
+ projectName: string;
history: ProjectHistory;
open: boolean;
- /**
- * The bottom-right corner (viewport px) of what opened it — the top bar's right cluster, `{ x: rect.right,
- * y: rect.bottom + 4 }`. The panel hangs from it leftward. Without it: the top right of the window.
- */
- anchor?: { x: number; y: number } | null;
onClose: () => void;
+ onOpenProject: (id: string) => void;
}) {
const t = useT();
- const { state, busy, progress } = history;
- const panelRef = React.useRef<HTMLDivElement>(null);
- const [message, setMessage] = React.useState('');
+ const language = useLanguage();
+ const { state, busy, progress, refresh } = history;
+ const [selected, setSelected] = React.useState<string | null>(null);
+ const [deletedView, setDeletedView] = React.useState(false);
+ const [deletedState, setDeletedState] = React.useState<HistoryState | null>(null);
+ const [deletedFailed, setDeletedFailed] = React.useState(false);
+ const [deletedLimit, setDeletedLimit] = React.useState(50);
+ const [deletedAttempt, setDeletedAttempt] = React.useState(0);
+ const [selecting, setSelecting] = React.useState(false);
+ const [checked, setChecked] = React.useState<ReadonlySet<string>>(new Set());
+ const [search, setSearch] = React.useState('');
+ const [typeOverride, setTypeOverride] = React.useState<ReadonlySet<HistoryVersionType> | null>(null);
+ const [filtersOpen, setFiltersOpen] = React.useState(false);
+ const filterBox = React.useRef<HTMLDivElement>(null);
+ const filterButton = React.useRef<HTMLButtonElement>(null);
+ const filterPanelId = React.useId();
+ const filtersOpenRef = React.useRef(filtersOpen);
+ filtersOpenRef.current = filtersOpen;
+ const [namedOnly, setNamedOnly] = React.useState(false);
const [dialog, setDialog] = React.useState<Dialog | null>(null);
- const [branchesOpen, setBranchesOpen] = React.useState(false);
+ const [input, setInput] = React.useState('');
const [notice, setNotice] = React.useState<string | null>(null);
+ const [files, setFiles] = React.useState<Change[] | null>(null);
+ const [filesFailed, setFilesFailed] = React.useState(false);
+ const [filesAttempt, setFilesAttempt] = React.useState(0);
+ const [filesExpanded, setFilesExpanded] = React.useState(true);
+ const filesPanelId = React.useId();
+ const panel = React.useRef<HTMLDivElement>(null);
+ const close = React.useRef(onClose);
+ close.current = onClose;
const dialogRef = React.useRef(dialog);
dialogRef.current = dialog;
+ const status = state?.status;
+ const changes = status?.changes;
+ const listState = deletedView ? deletedState : state;
+ const all = React.useMemo(() => listState?.versions ?? [], [listState]);
+ // Search and type filters never change the selected video or remove the current-editing entry.
+ const selectedVersion = all.find((v) => v.commit === selected) ?? null;
+ const working = !selectedVersion;
+ const isHead = selectedVersion?.commit === status?.head;
+ const shownTypes = typeOverride ?? new Set(HISTORY_VERSION_TYPES.filter((type) => type !== 'auto'));
+ const filtersActive = shownTypes.size !== HISTORY_VERSION_TYPES.length || namedOnly;
+ const dates = React.useMemo(
+ () => ({
+ clock: new Intl.DateTimeFormat(language, { hour: 'numeric', minute: '2-digit' }),
+ day: new Intl.DateTimeFormat(language, { year: 'numeric', month: 'short', day: 'numeric' }),
+ full: new Intl.DateTimeFormat(language, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ }),
+ }),
+ [language]
+ );
+ const label = (v: Version) => {
+ const l = versionLabel(v, all);
+ return l.key
+ ? t(l.key)
+ .replace('{name}', l.name ?? '')
+ .replace('{time}', l.at ? dates.full.format(l.at) : '')
+ : l.name ?? '';
+ };
+ const dayOf = (at: number) => {
+ const day = new Date(at).toDateString();
+ if (day === new Date().toDateString()) return t('versions.today');
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ return day === yesterday.toDateString() ? t('versions.yesterday') : dates.day.format(at);
+ };
+ const typeLabel = (v: Version) =>
+ t(`versions.type${historyVersionType(v)[0].toUpperCase()}${historyVersionType(v).slice(1)}`);
+ const versions = filterHistoryVersions(all, {
+ types: shownTypes,
+ namedOnly,
+ search,
+ textOf: (v) => [label(v), typeLabel(v), v.at > 0 ? dates.full.format(v.at) : '', dayOf(v.at)].join(' '),
+ });
+ const selectable = versions.filter((version) => deletedView || version.commit !== status?.head);
+ const selectedCommits = [...checked].filter((id) => all.some((version) => version.commit === id) && (deletedView || id !== status?.head));
+ const switchView = (deleted: boolean) => {
+ setDeletedView(deleted);
+ setSelected(null);
+ setSelecting(false);
+ setChecked(new Set());
+ setNotice(null);
+ setSearch('');
+ setNamedOnly(false);
+ setTypeOverride(deleted ? new Set(HISTORY_VERSION_TYPES) : null);
+ };
+ const toggleChecked = (id: string) => setChecked((previous) => {
+ const next = new Set(previous);
+ if (next.has(id)) next.delete(id); else next.add(id);
+ return next;
+ });
React.useEffect(() => {
- if (!open) return;
- const onDown = (event: MouseEvent) => {
- /* a question is answered first; it is not a click away from the panel */
- if (dialogRef.current) return;
- const target = event.target as Element;
- if (panelRef.current?.contains(target)) return;
- /* its menus are drawn outside it */
- if (target.closest?.('[role="menu"]')) return;
- /* the button that opens it toggles it itself; closing here first would let its click reopen it */
- if (target.closest?.('[data-history-trigger]')) return;
- onClose();
+ if (!open || !deletedView) return;
+ let live = true;
+ setDeletedFailed(false);
+ void historyApi.load(projectId, deletedLimit, true).then((fresh) => {
+ if (!live) return;
+ if (fresh) setDeletedState(fresh);
+ setDeletedFailed(!fresh);
+ });
+ return () => { live = false; };
+ }, [open, projectId, deletedView, deletedLimit, deletedAttempt, state?.deletedCount]);
+ React.useEffect(() => { setChecked(new Set()); }, [search, namedOnly, typeOverride]);
+ const resetFilters = () => {
+ setSearch('');
+ setNamedOnly(false);
+ setTypeOverride(new Set(HISTORY_VERSION_TYPES));
+ };
+ React.useEffect(() => {
+ if (!filtersOpen) return;
+ const outside = (event: PointerEvent) => {
+ if (!filterBox.current?.contains(event.target as Node)) setFiltersOpen(false);
};
- const onKey = (event: KeyboardEvent) => {
- if (event.key === 'Escape' && !dialogRef.current) { if (branchesOpen) setBranchesOpen(false); else onClose(); }
+ window.addEventListener('pointerdown', outside, true);
+ return () => window.removeEventListener('pointerdown', outside, true);
+ }, [filtersOpen]);
+
+ React.useEffect(() => {
+ if (open) void refresh();
+ }, [open, refresh]);
+ React.useEffect(() => {
+ setSelected(null);
+ setDeletedView(false);
+ setDeletedState(null);
+ setDeletedLimit(50);
+ setSelecting(false);
+ setChecked(new Set());
+ setNamedOnly(false);
+ setSearch('');
+ setTypeOverride(null);
+ setFiltersOpen(false);
+ setDialog(null);
+ setNotice(null);
+ }, [open, projectId]);
+ React.useEffect(() => {
+ if (!open) return;
+ const previous = document.activeElement as HTMLElement | null;
+ panel.current?.querySelector<HTMLButtonElement>('[data-history-close]')?.focus();
+ const onKey = (e: KeyboardEvent) => {
+ if (dialogRef.current || e.defaultPrevented) return;
+ if (e.key === 'Escape' && filtersOpenRef.current) {
+ e.preventDefault();
+ setFiltersOpen(false);
+ filterButton.current?.focus();
+ return;
+ }
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ close.current();
+ }
+ if (e.key === 'Tab') {
+ const buttons = [
+ ...(panel.current?.querySelectorAll<HTMLElement>('button:not(:disabled),input:not(:disabled)') ?? []),
+ ].filter((el) => el.getClientRects().length);
+ const first = buttons[0],
+ last = buttons.at(-1);
+ if (e.shiftKey && document.activeElement === first) {
+ e.preventDefault();
+ last?.focus();
+ } else if (!e.shiftKey && document.activeElement === last) {
+ e.preventDefault();
+ first?.focus();
+ }
+ }
};
- document.addEventListener('mousedown', onDown);
window.addEventListener('keydown', onKey);
return () => {
- document.removeEventListener('mousedown', onDown);
window.removeEventListener('keydown', onKey);
+ previous?.focus();
};
- }, [open, onClose, branchesOpen]);
-
- /* loaded again on opening: commits may have been made while it was closed */
- const { refresh } = history;
- React.useEffect(() => { if (open) void refresh(); }, [open, refresh]);
- React.useEffect(() => { if (!open) { setBranchesOpen(false); setNotice(null); } }, [open]);
+ }, [open]);
+ const commit = selectedVersion?.commit ?? null;
+ React.useEffect(() => {
+ if (!open || !commit || deletedView) return;
+ let active = true;
+ setFiles(null);
+ setFilesFailed(false);
+ void historyApi.versionFiles(projectId, commit).then((result) => {
+ if (active) {
+ setFiles(result);
+ setFilesFailed(result === null);
+ }
+ });
+ return () => {
+ active = false;
+ };
+ }, [open, projectId, commit, filesAttempt, deletedView]);
if (!open) return null;
-
- const now = Date.now();
- const status = state?.status ?? null;
- const commits = state?.commits ?? [];
- const branch = status?.branch ?? 'main';
- const changes = status?.changes ?? null;
- const committed = commits.length > 0;
- const say = (text: string) => setNotice(text);
-
- /* ── the actions, with their questions ── */
- const switchTo = (target: string) => {
- setBranchesOpen(false);
- if (changes) { setDialog({ kind: 'switch', target }); return; }
- void doCheckout({ branch: target });
+ const currentFiles = working ? changes?.files ?? [] : files;
+ const currentCount = working ? changes?.count ?? 0 : currentFiles?.length ?? 0;
+ const title = selectedVersion ? label(selectedVersion) : t(deletedView ? 'versions.deletedVersions' : 'versions.workingCopy');
+ const recover = async (commits: string[]) => {
+ if (await history.recover(commits)) {
+ setChecked(new Set());
+ setSelected(null);
+ setNotice(t('versions.recoveredRecords').replace('{n}', String(commits.length)));
+ }
};
- const doCheckout = async (o: { branch: string; create?: boolean; from?: string; carry?: 'leave' | 'bring' }) => {
+ const restore = async (v: Version, saveFirst: boolean) => {
setDialog(null);
- const result = await history.checkout(o);
- if (!result.ok && result.code === 'conflict') say(t('versions.errorCarry'));
- else if (result.ok && result.body.parkedBack === false) say(t('versions.parkedStuck'));
- else if (result.ok) setNotice(null);
+ if (saveFirst && !(await history.save(''))) return;
+ const result = await history.checkout(v.commit);
+ if (result.ok) {
+ setSelected(v.commit);
+ setNotice(result.body.missing?.length ? t('versions.missing') : t('versions.restored'));
+ } else if (result.code === 'dirty') setDialog({ kind: 'restore', version: v });
};
- const doCommit = async () => {
- if (!message.trim()) return;
- if (await history.commit(message.trim())) { setMessage(''); setNotice(null); }
- };
- const doRestore = async (commit: Commit, discardFirst: boolean) => {
- setDialog(null);
- if (discardFirst && !(await history.discard())) return;
- const result = await history.restore(commit.commit);
- if (result.ok) setMessage(t('versions.restoredMessage').replace('{name}', commit.message));
- else if (result.code === 'dirty') setDialog({ kind: 'restore', commit });
- };
- const doDelete = async (name: string, force: boolean) => {
- setDialog(null);
- const result = await history.remove(name, force);
- if (!result.ok && result.code === 'unmerged') setDialog({ kind: 'deleteForce', branch: name, commits: result.commits ?? 1 });
- };
- const doMerge = async (name: string, text: string, prefer?: 'ours' | 'theirs') => {
- setDialog(null);
- const result = await history.merge({ branch: name, message: text, ...(prefer ? { prefer } : {}) });
- if (!result.ok && result.code === 'conflict') setDialog({ kind: 'mergeConflict', branch: name, message: text });
- else if (!result.ok && result.code === 'dirty') say(t('versions.errorDirty'));
- else if (result.ok && result.body.merged === false) say(t('versions.nothingToMerge').replace('{name}', name).replace('{branch}', branch));
+ const submit = async () => {
+ if (!dialog) return;
+ if (dialog.kind === 'delete') {
+ const commits = dialog.commits;
+ setDialog(null);
+ if (await history.delete(commits)) {
+ setChecked(new Set());
+ if (selected && commits.includes(selected)) setSelected(null);
+ setNotice(t('versions.deletedRecords').replace('{n}', String(commits.length)));
+ }
+ return;
+ }
+ if (dialog.kind === 'restore') {
+ await restore(dialog.version, !!changes);
+ return;
+ }
+ if (dialog.kind === 'discard') {
+ setDialog(null);
+ if (await history.discard()) setSelected(null);
+ return;
+ }
+ if (dialog.kind === 'save') {
+ if (await history.save(input.trim())) {
+ setDialog(null);
+ setSelected(null);
+ }
+ } else {
+ setDialog(null);
+ const result = await history.copy(dialog.version.commit, input.trim());
+ if (result.ok) onOpenProject(result.body.project.id);
+ }
};
-
- const commitMenu = (commit: Commit, head: boolean): ContextMenuEntry[] => [
- ...(head && !changes ? [] : [{ id: 'restore', icon: <Undo2 size={14} />, label: t('versions.restore'), onSelect: () => setDialog({ kind: 'restore', commit }) }]),
- { id: 'branch', icon: <GitBranch size={14} />, label: t('versions.branchFrom'), onSelect: () => setDialog({ kind: 'newBranch', from: commit }) },
- ];
-
+ const askTitle = !dialog
+ ? ''
+ : dialog.kind === 'save'
+ ? t('versions.saveTitle')
+ : dialog.kind === 'copy'
+ ? t('versions.copyTitle').replace('{name}', label(dialog.version))
+ : dialog.kind === 'discard'
+ ? t('versions.discardTitle')
+ : dialog.kind === 'delete'
+ ? t('versions.deleteTitle').replace('{n}', String(dialog.commits.length))
+ : t('versions.restoreTitle').replace('{name}', label(dialog.version));
+ const askBody = !dialog
+ ? ''
+ : dialog.kind === 'save'
+ ? t('versions.saveBody')
+ : dialog.kind === 'copy'
+ ? t('versions.copyBody')
+ : dialog.kind === 'discard'
+ ? t('versions.discardBody')
+ : dialog.kind === 'delete'
+ ? t('versions.deleteBody')
+ : t(changes ? 'versions.saveRestoreBody' : 'versions.restoreBody');
+ let previousDay = '';
return (
<>
{createPortal(
<div
- ref={panelRef}
- role="dialog"
- aria-label={t('versions.title')}
- className="fixed z-[110] flex flex-col overflow-hidden"
- style={{
- ...POPOVER_CHROME,
- right: anchor ? Math.max(window.innerWidth - anchor.x, 12) : 12,
- top: anchor ? anchor.y : 40,
- width: PANEL_W,
- animation: 'openfilm-rise 0.14s ease-out both',
- maxHeight: `calc(100vh - ${(anchor ? anchor.y : 40) + 12}px)`,
+ className={LARGE_DIALOG_BACKDROP}
+ onClick={() => {
+ if (!dialogRef.current && !busy) onClose();
}}
>
- {/* the title, and the branch checked out */}
- <div className="flex shrink-0 items-center gap-2 px-4 pb-2 pt-3">
- <span className="min-w-0 flex-1 truncate text-[13px] font-medium text-[var(--text)]">{t('versions.title')}</span>
- {busy ? <Loader2 size={13} className="animate-spin text-[var(--text-faint)]" aria-label={t('versions.working')} /> : null}
- <button
- type="button"
- onClick={onClose}
- aria-label={t('versions.close')}
- className="flex h-6 w-6 items-center justify-center rounded-md text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
- >
- <X size={14} strokeWidth={1.75} />
- </button>
- </div>
- {progress ? (
- <div role="status" className="shrink-0 px-4 pb-2">
- <div className="truncate text-[11.5px] text-[var(--text-muted)]">{progressText(progress, t)}</div>
- <div className="mt-1 h-[3px] overflow-hidden rounded-full bg-[var(--surface-2)]">
- <div className="h-full rounded-full bg-[var(--accent)] transition-[width] duration-150" style={{ width: `${progress.total ? Math.min(100, (progress.done / progress.total) * 100) : 0}%` }} />
+ <div
+ ref={panel}
+ role="dialog"
+ aria-modal="true"
+ aria-label={t('versions.title')}
+ className={LARGE_DIALOG}
+ style={{ animation: 'openfilm-rise 0.16s ease-out both' }}
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ if (e.key !== 'Escape' && e.key !== 'Tab') e.stopPropagation();
+ }}
+ >
+ <aside className="flex min-h-0 w-[180px] shrink-0 flex-col border-r border-[var(--border-soft)] bg-[var(--surface-2)] sm:w-[260px]">
+ <div className="flex shrink-0 items-center gap-2 px-5 pb-4 pt-5">
+ <h2 className="min-w-0 flex-1 truncate text-[15px] font-semibold tracking-tight">{t('versions.title')}</h2>
+ <button type="button" disabled={!!busy || !state} aria-label={t(selecting ? 'versions.cancelSelection' : 'versions.selectVersions')} aria-pressed={selecting}
+ onClick={() => { setSelecting(!selecting); setChecked(new Set()); }}
+ className={`flex shrink-0 items-center gap-1 rounded-lg p-1.5 text-[11px] text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] disabled:opacity-40 ${selecting ? 'bg-[var(--surface)] text-[var(--text)]' : ''}`}>
+ <ListChecks size={14} /><span className="hidden sm:inline">{t(selecting ? 'versions.cancelSelection' : 'versions.selectVersions')}</span>
+ </button>
</div>
- </div>
- ) : null}
- <div className="relative shrink-0 px-3 pb-2">
- <button
- type="button"
- onClick={() => setBranchesOpen((v) => !v)}
- disabled={!committed}
- aria-expanded={branchesOpen}
- aria-haspopup="listbox"
- aria-label={t('versions.branchOf').replace('{branch}', branch)}
- className="flex h-8 w-full items-center gap-2 rounded-lg border border-[var(--border)] px-2.5 text-left text-[12.5px] text-[var(--text)] transition hover:bg-[var(--bg-hover)] disabled:cursor-default disabled:opacity-60"
- >
- <GitBranch size={13} className="shrink-0 text-[var(--text-dim)]" />
- <span className="min-w-0 flex-1 truncate font-medium">{branch}</span>
- {committed ? (
- <span className="shrink-0 text-[11.5px] text-[var(--text-faint)]">
- {t(status && status.branches.length === 1 ? 'versions.branchCountOne' : 'versions.branchCount').replace('{n}', String(status?.branches.length ?? 1))}
- </span>
- ) : null}
- <ChevronDown size={13} className={`shrink-0 text-[var(--text-faint)] transition-transform ${branchesOpen ? 'rotate-180' : ''}`} />
- </button>
- {branchesOpen && status ? (
- <BranchList
- branches={status.branches}
- current={branch}
- now={now}
- busy={busy !== null}
- t={t}
- onSwitch={switchTo}
- onNew={() => { setBranchesOpen(false); setDialog({ kind: 'newBranch' }); }}
- onMerge={(name) => { setBranchesOpen(false); setDialog({ kind: 'merge', branch: name }); }}
- onRename={(name) => { setBranchesOpen(false); setDialog({ kind: 'rename', branch: name }); }}
- onDelete={(name) => { setBranchesOpen(false); setDialog({ kind: 'delete', branch: name }); }}
- />
- ) : null}
- </div>
-
- <div className="min-h-0 flex-1 overflow-y-auto px-3 pb-3">
- {notice ? (
- <p role="status" className="mb-2 rounded-lg bg-[var(--surface-2)] px-3 py-2 text-[12px] leading-relaxed text-[var(--text-dim)]">{notice}</p>
- ) : null}
-
- {/* what is not committed yet, and committing it */}
- {state === null ? (
- <div className="flex justify-center py-6"><Loader2 size={16} className="animate-spin text-[var(--text-faint)]" /></div>
- ) : changes || !committed ? (
- <section className="mb-3 rounded-xl border border-[var(--border)] p-2.5">
- <div className="flex items-center gap-2.5">
- <Thumb src={`/api/projects/${encodeURIComponent(projectId)}/poster?v=${encodeURIComponent(`${status?.head ?? ''}:${changes?.count ?? 0}:${JSON.stringify(changes?.summary ?? null)}`)}`} large />
- <div className="min-w-0 flex-1">
- <div className="truncate text-[12.5px] font-medium text-[var(--text)]">{t('versions.changesTitle')}</div>
- <div className="mt-0.5 line-clamp-2 text-[11.5px] leading-snug text-[var(--text-muted)]">
- {committed ? (changes ? summaryText(changes.summary, t) : '') : t('versions.firstCommitHint')}
- </div>
- </div>
- </div>
- <form
- className="mt-2.5 flex items-center gap-2"
- onSubmit={(event) => { event.preventDefault(); void doCommit(); }}
- >
+ <div className="mx-3 mb-3 grid shrink-0 grid-cols-2 gap-1 rounded-lg bg-[var(--fill-tsp)] p-1">
+ <button type="button" disabled={!!busy} aria-pressed={!deletedView} onClick={() => switchView(false)} className={`rounded-md px-2 py-1.5 text-[11px] ${!deletedView ? 'bg-[var(--surface)] text-[var(--text)] shadow-[var(--shadow-sm)]' : 'text-[var(--text-muted)] hover:text-[var(--text)]'}`}>{t('versions.savedVersions')}</button>
+ <button type="button" disabled={!!busy} aria-pressed={deletedView} onClick={() => switchView(true)} className={`rounded-md px-2 py-1.5 text-[11px] ${deletedView ? 'bg-[var(--surface)] text-[var(--text)] shadow-[var(--shadow-sm)]' : 'text-[var(--text-muted)] hover:text-[var(--text)]'}`}>{t('versions.deletedVersions')} {state?.deletedCount ? `(${state.deletedCount})` : ''}</button>
+ </div>
+ <div ref={filterBox} className="relative z-10 mx-3 mb-4 flex shrink-0 gap-2">
+ <div className="relative min-w-0 flex-1">
+ <Search
+ size={13}
+ aria-hidden
+ className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-[var(--text-faint)]"
+ />
<input
- value={message}
- onChange={(event) => setMessage(event.target.value)}
- maxLength={500}
- aria-label={t('versions.messagePlaceholder')}
- placeholder={t('versions.messagePlaceholder')}
- disabled={busy !== null}
- className="h-8 min-w-0 flex-1 rounded-lg bg-[var(--surface-2)] px-2.5 text-[12.5px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)] focus:ring-1 focus:ring-[var(--border-strong)]"
- onKeyDown={(event) => event.stopPropagation()}
+ type="search"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ aria-label={t('versions.search')}
+ placeholder={t('versions.search')}
+ className="h-8 w-full rounded-lg border border-[var(--border)] bg-[var(--surface)] pl-8 pr-2 text-[12px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)] focus:border-[var(--border-strong)]"
/>
- <CardButton type="submit" weight="primary" disabled={busy !== null || !message.trim()}>
- {busy === 'commit' ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}
- {t('versions.commit')}
- </CardButton>
- </form>
- {committed ? (
+ </div>
+ <button
+ ref={filterButton}
+ type="button"
+ onClick={() => setFiltersOpen((v) => !v)}
+ aria-label={t('versions.filterVersions')}
+ aria-expanded={filtersOpen}
+ aria-controls={filterPanelId}
+ className={`relative flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border transition ${
+ filtersActive || filtersOpen
+ ? 'border-[var(--border-strong)] bg-[var(--surface)] text-[var(--text)]'
+ : 'border-[var(--border)] text-[var(--text-muted)] hover:bg-[var(--bg-hover)]'
+ }`}
+ >
+ <ListFilter size={14} strokeWidth={filtersActive ? 2.25 : 1.6} />
+ </button>
+ {filtersOpen ? (
+ <fieldset
+ id={filterPanelId}
+ aria-label={t('versions.filterVersions')}
+ className="absolute left-0 right-0 top-[calc(100%+6px)] rounded-xl border border-[var(--border-strong)] bg-[var(--surface)] p-2.5 shadow-[var(--shadow-lg)]"
+ >
+ <legend className="sr-only">{t('versions.filterVersions')}</legend>
+ <p className="px-1 pb-2 text-[10px] font-medium text-[var(--text-faint)]">
+ {t('versions.versionTypes')}
+ </p>
+ {HISTORY_VERSION_TYPES.map((type) => (
+ <label
+ key={type}
+ className="flex cursor-pointer items-center gap-2.5 rounded-md px-1.5 py-1.5 text-[12px] hover:bg-[var(--bg-hover)]"
+ >
+ <input
+ type="checkbox"
+ checked={shownTypes.has(type)}
+ onChange={(e) => {
+ const next = new Set(shownTypes);
+ if (e.target.checked) next.add(type);
+ else next.delete(type);
+ setTypeOverride(next);
+ }}
+ className="h-3 w-3 accent-[var(--text)]"
+ />
+ <span className="flex-1">{t(`versions.type${type[0].toUpperCase()}${type.slice(1)}`)}</span>
+ <span className="text-[10px] tabular-nums text-[var(--text-faint)]">
+ {all.filter((v) => historyVersionType(v) === type).length}
+ </span>
+ </label>
+ ))}
+ <div className="my-2 border-t border-[var(--border-soft)]" />
+ <label className="flex cursor-pointer items-center gap-2.5 rounded-md px-1.5 py-1.5 text-[11px] hover:bg-[var(--bg-hover)]">
+ <input
+ type="checkbox"
+ checked={namedOnly}
+ onChange={(e) => setNamedOnly(e.target.checked)}
+ className="h-3 w-3 accent-[var(--text)]"
+ />
+ {t('versions.namedOnly')}
+ </label>
+ <button
+ type="button"
+ onClick={() => {
+ setTypeOverride(new Set(HISTORY_VERSION_TYPES));
+ setNamedOnly(false);
+ }}
+ className="mt-2 w-full rounded-md border border-[var(--border)] py-1.5 text-[11px] text-[var(--text-muted)] hover:bg-[var(--bg-hover)]"
+ >
+ {t('versions.showAllTypes')}
+ </button>
+ </fieldset>
+ ) : null}
+ </div>
+ <div className="shrink-0 px-3 pb-3">
+ <button
+ type="button"
+ disabled={!state}
+ onClick={() => {
+ switchView(false);
+ }}
+ aria-pressed={working && !deletedView}
+ className={`relative flex w-full items-center gap-2.5 rounded-xl px-3 py-3 text-left transition ${
+ working && !deletedView ? 'bg-[var(--surface)] shadow-[var(--shadow-sm)]' : 'hover:bg-[var(--bg-hover)]'
+ }`}
+ >
+ {working && !deletedView ? (
+ <span aria-hidden className="absolute bottom-4 left-0 top-4 w-0.5 rounded-full bg-[var(--text)]" />
+ ) : null}
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--fill-tsp)] text-[var(--text-muted)]">
+ <Film size={15} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-[12px] font-semibold">{t('versions.workingCopy')}</span>
+ <span className="mt-1 block text-[10px] leading-relaxed text-[var(--text-muted)]">
+ {!state
+ ? t('versions.working')
+ : changes
+ ? t('versions.unsavedFiles').replace('{n}', String(changes.count))
+ : t('versions.matchesSaved')}
+ </span>
+ </span>
+ {state && !changes ? (
+ <Check size={12} aria-hidden className="shrink-0 text-[var(--text-faint)]" />
+ ) : null}
+ </button>
+ </div>
+ {selecting && <div className="flex shrink-0 items-center gap-2 border-t border-[var(--border-soft)] px-4 py-2 text-[11px]">
+ <button type="button" disabled={!!busy || !selectable.length} onClick={() => setChecked(new Set(selectable.every((version) => checked.has(version.commit)) ? [] : selectable.map((version) => version.commit)))} className="text-[var(--text-muted)] hover:text-[var(--text)] disabled:opacity-40">{t(selectable.length && selectable.every((version) => checked.has(version.commit)) ? 'versions.clearSelection' : 'versions.selectVisible')}</button>
+ <span className="flex-1 text-[var(--text-faint)]">{t('versions.selectionCount').replace('{n}', String(selectedCommits.length))}</span>
+ <button type="button" disabled={!!busy || !selectedCommits.length} onClick={() => deletedView ? void recover(selectedCommits) : setDialog({ kind: 'delete', commits: selectedCommits })} className={`flex items-center gap-1 rounded-md px-1.5 py-1 hover:bg-[var(--bg-hover)] disabled:opacity-40 ${deletedView ? 'text-[var(--text)]' : 'text-[var(--err)]'}`}>
+ {deletedView ? <RotateCcw size={12} /> : <Trash2 size={12} />}{t(deletedView ? 'versions.recoverRecords' : 'versions.deleteSelected')}
+ </button>
+ </div>}
+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain border-t border-[var(--border-soft)] px-3 pb-3">
+ {deletedView && !deletedState && !deletedFailed ? <Loader2 size={15} className="mx-auto my-6 animate-spin text-[var(--text-faint)]" /> : null}
+ {deletedView && deletedFailed ? <button type="button" onClick={() => setDeletedAttempt((n) => n + 1)} className="px-2 py-4 text-[12px] text-[var(--text-muted)]">{t('versions.loadFailed')} {t('versions.retry')}</button> : null}
+ {versions.map((v) => {
+ const day = dayOf(v.at),
+ showDay = previousDay !== day;
+ previousDay = day;
+ const chosen = selectedVersion?.commit === v.commit;
+ const type = historyVersionType(v),
+ description = typeLabel(v);
+ const Icon =
+ v.name && type === 'manual'
+ ? Bookmark
+ : { manual: Save, auto: Clock3, restore: RotateCcw, other: History }[type];
+ return (
+ <React.Fragment key={v.commit}>
+ {showDay ? (
+ <p className="px-2 pb-2 pt-4 text-[10px] font-medium text-[var(--text-faint)]">{day}</p>
+ ) : null}
+ <div className="flex items-start gap-1">
+ {selecting && <input type="checkbox" checked={checked.has(v.commit) && (deletedView || v.commit !== status?.head)} disabled={!!busy || (!deletedView && v.commit === status?.head)}
+ aria-label={t('versions.selectVersion').replace('{name}', label(v))} title={!deletedView && v.commit === status?.head ? t('versions.errorDeleteCurrent') : undefined}
+ onChange={() => toggleChecked(v.commit)} className="ml-1 mt-4 h-3.5 w-3.5 shrink-0 accent-[var(--text)] disabled:opacity-30" />}
+ <button
+ type="button"
+ onClick={() => {
+ setSelected(v.commit);
+ setNotice(null);
+ }}
+ aria-pressed={chosen}
+ className={`relative mb-1 flex min-w-0 flex-1 items-start gap-2.5 rounded-xl px-3 py-3 text-left transition ${
+ chosen ? 'bg-[var(--surface)] shadow-[var(--shadow-sm)]' : 'hover:bg-[var(--bg-hover)]'
+ }`}
+ >
+ {chosen ? (
+ <span
+ aria-hidden
+ className="absolute bottom-4 left-0 top-4 w-0.5 rounded-full bg-[var(--text)]"
+ />
+ ) : null}
+ <span className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-[var(--fill-tsp)] text-[var(--text-faint)]">
+ <Icon size={13} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span
+ className={`line-clamp-2 break-words text-[12px] font-medium leading-relaxed ${
+ chosen ? 'text-[var(--text)]' : 'text-[var(--text-dim)]'
+ }`}
+ title={label(v)}
+ >
+ {label(v)}
+ </span>
+ <span className="mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-[10px] leading-relaxed text-[var(--text-faint)]">
+ <span className="tabular-nums">{v.at > 0 ? dates.clock.format(v.at) : ''}</span>
+ {label(v) !== description ? (
+ <>
+ <span aria-hidden>·</span>
+ <span>{description}</span>
+ </>
+ ) : null}
+ </span>
+ {v.commit === status?.head ? (
+ <span className="mt-1.5 inline-block rounded bg-[var(--fill-tsp)] px-1.5 text-[9px] leading-[17px] text-[var(--text-muted)]">
+ {t(changes ? 'versions.lastSaved' : 'versions.inUse')}
+ </span>
+ ) : null}
+ </span>
+ </button>
+ </div>
+ </React.Fragment>
+ );
+ })}
+ {listState && !versions.length ? (
+ <div className="px-2 py-7 text-center">
+ <p className="text-[12px] leading-relaxed text-[var(--text-muted)]">
+ {t(all.length ? 'versions.noMatchingVersions' : deletedView ? 'versions.noDeletedVersions' : 'versions.noVersions')}
+ </p>
+ {all.length ? (
+ <button
+ type="button"
+ onClick={resetFilters}
+ className="mt-2 text-[11px] text-[var(--text-muted)] underline underline-offset-4"
+ >
+ {t('versions.resetFilters')}
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+ {listState?.more ? (
<button
type="button"
- onClick={() => setDialog({ kind: 'discard' })}
- disabled={busy !== null}
- className="mt-1.5 px-0.5 text-[11.5px] text-[var(--text-faint)] transition hover:text-[var(--err)] disabled:opacity-50"
+ disabled={!!busy}
+ onClick={() => deletedView ? setDeletedLimit((limit) => limit + 50) : void history.showMore()}
+ className="w-full px-3 py-2 text-left text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]"
>
- {t('versions.discard')}
+ {t('versions.showMore')}
</button>
) : null}
- </section>
- ) : (
- <p className="mb-3 flex items-center gap-1.5 px-1 text-[12px] text-[var(--text-faint)]">
- <Check size={12} /> {t('versions.noChanges')}
- </p>
- )}
-
- {/* the branch's commits */}
- {committed ? (
- <>
- <div className="mb-1 px-1 text-[11.5px] font-medium text-[var(--text-faint)]">{t('versions.historyOf').replace('{branch}', branch)}</div>
- <ol>
- {commits.map((commit, index) => (
- <CommitRow
- key={commit.commit}
- projectId={projectId}
- commit={commit}
- head={commit.commit === status?.head}
- last={index === commits.length - 1}
- age={ageLabel(commit.at, now, t)}
- busy={busy !== null}
- menu={commitMenu(commit, commit.commit === status?.head)}
- t={t}
- />
- ))}
- </ol>
- </>
- ) : null}
-
- {status?.files ? <FilesHeld projectId={projectId} files={status.files} t={t} /> : null}
+ </div>
+ {working && state && !deletedView ? (
+ <div className="shrink-0 border-t border-[var(--border-soft)] p-3">
+ <button
+ type="button"
+ disabled={!!busy || !changes}
+ title={!changes ? t('versions.matchesSaved') : undefined}
+ onClick={() => {
+ setInput('');
+ setDialog({ kind: 'save' });
+ }}
+ className="flex w-full items-center justify-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--surface)] px-2 py-2 text-[12px] hover:bg-[var(--bg-hover)] disabled:cursor-default disabled:opacity-40"
+ >
+ <Plus size={13} />
+ {t('versions.saveVersion')}
+ </button>
+ </div>
+ ) : null}
+ </aside>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <header className="flex shrink-0 items-start gap-3 px-5 py-4">
+ <div className="min-w-0 flex-1">
+ <h3 className="truncate text-[14px] font-semibold" title={title}>
+ {title}
+ </h3>
+ <p className="mt-0.5 truncate text-[11px] text-[var(--text-muted)]">
+ {selectedVersion ? dates.full.format(selectedVersion.at) : t('versions.workingCopyHint')}
+ </p>
+ </div>
+ {busy ? <Loader2 size={15} className="mt-1 animate-spin text-[var(--text-faint)]" /> : null}
+ <button
+ data-history-close
+ type="button"
+ onClick={onClose}
+ aria-label={t('versions.close')}
+ className="rounded-lg p-1 text-[var(--text-faint)] hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
+ >
+ <X size={16} />
+ </button>
+ </header>
+ {!state ? (
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 px-6 text-center">
+ {history.failed ? (
+ <>
+ <p className="text-[12px] text-[var(--text-muted)]">{t('versions.loadFailed')}</p>
+ <CardButton onClick={() => void refresh()}>{t('versions.retry')}</CardButton>
+ </>
+ ) : (
+ <Loader2 size={18} className="animate-spin text-[var(--text-faint)]" />
+ )}
+ </div>
+ ) : deletedView ? (
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 px-6 text-center text-[var(--text-faint)]">
+ <Trash2 size={28} strokeWidth={1.3} />
+ <p className="max-w-sm text-[12px] leading-relaxed">{t('versions.deletedPreviewHint')}</p>
+ {selectedVersion && <CardButton disabled={!!busy} onClick={() => void recover([selectedVersion.commit])}><RotateCcw size={12} />{t('versions.recoverRecords')}</CardButton>}
+ </div>
+ ) : (
+ <div
+ className="grid min-h-0 flex-1"
+ style={{ gridTemplateRows: `minmax(0, 1fr) ${filesExpanded ? 'clamp(128px, 22dvh, 216px)' : '40px'}` }}
+ >
+ <VersionVideoPreview
+ key={`${projectId}:${commit ?? 'working'}`}
+ projectId={projectId}
+ commit={commit}
+ />
+ <section className="flex min-h-0 flex-col border-t border-[var(--border-soft)]" aria-label={t('versions.fileChanges')}>
+ <div className="flex h-10 shrink-0 items-center gap-2 px-5">
+ <h4 className="min-w-0 text-[12px] font-medium">
+ <button
+ type="button"
+ onClick={() => setFilesExpanded((expanded) => !expanded)}
+ aria-expanded={filesExpanded}
+ aria-controls={filesPanelId}
+ className="flex items-center gap-2 rounded py-1 text-[var(--text-muted)] transition hover:text-[var(--text)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--accent)]"
+ >
+ <ChevronRight size={13} className={`shrink-0 transition-transform ${filesExpanded ? 'rotate-90' : ''}`} />
+ {t('versions.fileChanges')}
+ <span className="rounded bg-[var(--fill-tsp)] px-1.5 py-0.5 text-[10px] tabular-nums text-[var(--text-faint)]">{currentCount}</span>
+ </button>
+ </h4>
+ <span className="ml-auto hidden text-[10px] text-[var(--text-faint)] md:inline">
+ {t(working ? 'versions.sinceSaved' : 'versions.sincePrevious')}
+ </span>
+ {working && changes && status?.head ? (
+ <Tooltip label={t('versions.discardAll')}>
+ <button
+ type="button"
+ disabled={!!busy}
+ onClick={() => setDialog({ kind: 'discard' })}
+ aria-label={t('versions.discardAll')}
+ className="rounded p-1 text-[var(--text-muted)] hover:bg-[var(--bg-hover)]"
+ >
+ <Undo2 size={13} />
+ </button>
+ </Tooltip>
+ ) : null}
+ </div>
+ <div id={filesPanelId} hidden={!filesExpanded} className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-3 pb-2 [scrollbar-gutter:stable]">
+ {!working && filesFailed ? (
+ <button
+ type="button"
+ onClick={() => setFilesAttempt((n) => n + 1)}
+ className="px-2 py-1 text-[12px] text-[var(--text-muted)]"
+ >
+ {t('versions.filesFailed')} <span className="underline">{t('versions.retry')}</span>
+ </button>
+ ) : currentFiles === null ? (
+ <div className="px-2 py-2">
+ <Loader2 size={13} className="animate-spin text-[var(--text-faint)]" />
+ </div>
+ ) : currentFiles.length ? (
+ <ul>
+ {currentFiles.map((f) => (
+ <FileRow key={f.path} file={f} t={t} />
+ ))}
+ {currentCount > currentFiles.length ? (
+ <li className="px-2 py-1 text-[11px] text-[var(--text-faint)]">
+ {t('versions.moreFiles').replace('{n}', String(currentCount - currentFiles.length))}
+ </li>
+ ) : null}
+ </ul>
+ ) : (
+ <p className="px-2 pb-2 text-[12px] text-[var(--text-faint)]">{t('versions.noChanges')}</p>
+ )}
+ </div>
+ </section>
+ </div>
+ )}
+ <footer className="flex shrink-0 flex-wrap items-center gap-2 border-t border-[var(--border-soft)] bg-[color-mix(in_srgb,var(--surface-2)_45%,transparent)] px-5 py-3.5">
+ <div
+ className="min-w-0 flex-1 basis-full text-[11px] leading-relaxed text-[var(--text-muted)] lg:basis-0"
+ role="status"
+ >
+ {progress
+ ? progressText(progress, t)
+ : notice ?? t(deletedView ? 'versions.deletedPreviewHint' : working ? 'versions.workingCopyHint' : 'versions.previewHint')}
+ </div>
+ {selectedVersion && !deletedView ? (
+ <>
+ <CardButton
+ weight="quiet"
+ disabled={!!busy || !!isHead}
+ title={isHead ? t('versions.errorDeleteCurrent') : undefined}
+ onClick={() => setDialog({ kind: 'delete', commits: [selectedVersion.commit] })}
+ ><Trash2 size={12} />{t('versions.deleteVersion')}</CardButton>
+ <CardButton
+ className="ml-auto"
+ disabled={!!busy}
+ onClick={() => {
+ setInput(
+ t('versions.copyDefault')
+ .replace('{project}', projectName)
+ .replace('{name}', label(selectedVersion))
+ );
+ setDialog({ kind: 'copy', version: selectedVersion });
+ }}
+ >
+ {t('versions.copy')}
+ </CardButton>
+ <CardButton
+ weight="primary"
+ disabled={!!busy || (!!isHead && !changes)}
+ onClick={() => setDialog({ kind: 'restore', version: selectedVersion })}
+ >
+ <RotateCcw size={12} />
+ {t('versions.restore')}
+ </CardButton>
+ </>
+ ) : null}
+ </footer>
+ </div>
</div>
</div>,
- document.body,
+ document.body
)}
- <Questions
- dialog={dialog}
- branch={branch}
- t={t}
- onCancel={() => setDialog(null)}
- onSwitch={(target, carry) => void doCheckout({ branch: target, carry })}
- onNewBranch={(name, from) => {
- /* from where the folder is, or with nothing uncommitted: nothing to leave or bring */
- if (!from || from.commit === status?.head || !changes) { void doCheckout({ branch: name, create: true, ...(from ? { from: from.commit } : {}) }); return; }
- setDialog({ kind: 'newBranchCarry', name, from });
- }}
- onNewBranchCarry={(name, from, carry) => void doCheckout({ branch: name, create: true, from: from.commit, carry })}
- onRename={(from, name) => { setDialog(null); void history.rename(from, name); }}
- onDelete={(name, force) => void doDelete(name, force)}
- onMerge={(name, text, prefer) => void doMerge(name, text, prefer)}
- onRestore={(commit) => void doRestore(commit, Boolean(changes))}
- onDiscard={() => { setDialog(null); void history.discard().then((done) => { if (done) setMessage(''); }); }}
- dirty={Boolean(changes)}
- />
+ {dialog ? (
+ <Ask
+ title={askTitle}
+ body={askBody}
+ onCancel={() => setDialog(null)}
+ input={
+ dialog.kind === 'save' || dialog.kind === 'copy'
+ ? {
+ value: input,
+ onChange: setInput,
+ placeholder: t(dialog.kind === 'save' ? 'versions.namePlaceholder' : 'versions.copyName'),
+ }
+ : undefined
+ }
+ actions={[
+ { label: t('versions.cancel'), weight: 'quiet', onClick: () => setDialog(null) },
+ {
+ label: t(
+ dialog.kind === 'save'
+ ? 'versions.saveVersion'
+ : dialog.kind === 'copy'
+ ? 'versions.copyConfirm'
+ : dialog.kind === 'discard'
+ ? 'versions.discardConfirm'
+ : dialog.kind === 'delete'
+ ? 'versions.deleteConfirm'
+ : changes
+ ? 'versions.saveAndRestore'
+ : 'versions.restore'
+ ),
+ weight: dialog.kind === 'discard' || dialog.kind === 'delete' ? 'danger' : 'primary',
+ disabled: !!busy || (dialog.kind === 'copy' && !input.trim()),
+ onClick: () => void submit(),
+ },
+ ]}
+ />
+ ) : null}
</>
);
}
-/**
- * What history keeps of the folder: the film's files, and the other files it leaves alone (renders, frames, other
- * takes). Each opens to its list, loaded when opened.
- */
-function FilesHeld({ projectId, files, t }: { projectId: string; files: HistoryFiles; t: Translate }) {
- const [open, setOpen] = React.useState<'held' | 'ignored' | null>(null);
- const [lists, setLists] = React.useState<{ held: HistoryFile[]; ignored: HistoryFile[] } | null>(null);
- const toggle = (which: 'held' | 'ignored') => {
- const next = open === which ? null : which;
- setOpen(next);
- if (next) void historyApi.files(projectId).then((l) => { if (l) setLists(l); });
- };
- const row = (which: 'held' | 'ignored', label: string) => (
- <button
- type="button"
- onClick={() => toggle(which)}
- aria-expanded={open === which}
- className="flex w-full items-center gap-1 rounded-md px-1 py-0.5 text-left text-[11.5px] text-[var(--text-faint)] transition hover:text-[var(--text-dim)]"
- >
- {open === which ? <ChevronDown size={12} className="shrink-0" /> : <ChevronRight size={12} className="shrink-0" />}
- <span className="min-w-0 flex-1 truncate">{label}</span>
- </button>
- );
- const n = (key: string, count: number) => t(count === 1 ? `${key}One` : key).replace('{n}', count.toLocaleString());
- const list = open && lists ? lists[open] : null;
+function FileRow({ file, t }: { file: Change; t: Translate }) {
+ const slash = file.path.lastIndexOf('/');
+ const name = file.path.slice(slash + 1),
+ dir = file.path.slice(0, Math.max(0, slash));
+ const color = { added: 'var(--ok)', modified: 'var(--text-muted)', deleted: 'var(--err)' }[file.change];
return (
- <div className="mt-3 border-t border-[var(--border)] pt-2">
- {row('held', `${n('versions.heldFiles', files.held)} · ${formatBytes(files.heldBytes)}`)}
- {files.ignored ? row('ignored', n('versions.ignoredFiles', files.ignored)) : null}
- {open ? (
- list ? (
- <ul className="mt-1 max-h-[180px] overflow-y-auto rounded-lg bg-[var(--surface-2)] px-2 py-1.5">
- {list.map((f) => (
- <li key={f.path} className="flex items-center gap-2 py-[1px] text-[11px] text-[var(--text-muted)]" title={f.path}>
- <span className="min-w-0 flex-1 truncate">{f.path}</span>
- <span className="shrink-0 tabular-nums text-[var(--text-faint)]">{formatBytes(f.size)}</span>
- </li>
- ))}
- </ul>
- ) : (
- <div className="flex justify-center py-2"><Loader2 size={13} className="animate-spin text-[var(--text-faint)]" /></div>
- )
- ) : null}
- </div>
- );
-}
-
-/** The film's picture at a commit (or now): a placeholder until there is one. */
-function Thumb({ src, large = false }: { src: string | null; large?: boolean }) {
- const [failed, setFailed] = React.useState(false);
- React.useEffect(() => { setFailed(false); }, [src]);
- const size = large ? 'h-[45px] w-[80px]' : 'h-[34px] w-[60px]';
- if (!src || failed) {
- return (
- <span className={`${size} flex shrink-0 items-center justify-center rounded-md bg-[var(--surface-2)] text-[var(--text-faint)]`}>
- <Clapperboard size={large ? 16 : 13} />
+ <li className="flex min-h-8 items-center gap-2 rounded-md px-2 py-1.5 hover:bg-[var(--bg-hover)]" title={file.path}>
+ <File size={13} className="shrink-0 text-[var(--text-faint)]" />
+ <span
+ className={`min-w-0 shrink truncate text-[12px] ${
+ file.change === 'deleted' ? 'text-[var(--text-muted)] line-through' : 'text-[var(--text-dim)]'
+ }`}
+ >
+ {name}
</span>
- );
- }
- return <img src={src} alt="" onError={() => setFailed(true)} className={`${size} shrink-0 rounded-md bg-black object-cover`} />;
-}
-
-function CommitRow({ projectId, commit, head, last, age, busy, menu, t }: {
- projectId: string;
- commit: Commit;
- head: boolean;
- last: boolean;
- age: string;
- busy: boolean;
- menu: ContextMenuEntry[];
- t: Translate;
-}) {
- const [anchor, setAnchor] = React.useState<{ x: number; y: number; top: number } | null>(null);
- const button = React.useRef<HTMLButtonElement>(null);
- const merge = commit.parents.length > 1;
- return (
- <li className="group relative flex items-stretch gap-2">
- {/* the rail: a line through the commits, a filled dot where the branch is */}
- <span className="relative w-[12px] shrink-0" aria-hidden>
- {!last ? <span className="absolute bottom-[-4px] left-[5.5px] top-[22px] w-px bg-[var(--border)]" /> : null}
- <span className={`absolute left-[2px] top-[17px] h-[8px] w-[8px] rounded-full ${head ? 'bg-[var(--text)]' : 'border border-[var(--border-strong)] bg-[var(--bg-surface)]'}`} />
+ {dir ? (
+ <span className="min-w-0 flex-1 truncate text-[11px] text-[var(--text-faint)]">{dir}</span>
+ ) : (
+ <span className="flex-1" />
+ )}
+ <span className="shrink-0 text-[10px]" style={{ color }}>
+ {t(`versions.file${file.change[0].toUpperCase()}${file.change.slice(1)}`)}
</span>
- <div className={`mb-0.5 flex min-w-0 flex-1 items-center gap-2.5 rounded-lg px-2 py-1.5 transition ${head ? 'bg-[var(--bg-hover)]' : 'hover:bg-[var(--bg-hover)]'}`}>
- <Thumb src={commitPoster(projectId, commit.commit)} />
- <div className="min-w-0 flex-1" title={commit.body ? `${commit.message}\n\n${commit.body}` : commit.message}>
- <div className="flex min-w-0 items-center gap-1.5">
- {merge ? <GitMerge size={12} className="shrink-0 text-[var(--text-faint)]" /> : null}
- <span className={`truncate text-[12.5px] leading-snug ${head ? 'font-medium text-[var(--text)]' : 'text-[var(--text-dim)]'}`}>{commit.message}</span>
- {commit.tags.map((tag) => (
- <span key={tag} className="flex shrink-0 items-center gap-0.5 rounded bg-[var(--surface-2)] px-1 text-[10.5px] text-[var(--text-muted)]"><Tag size={9} />{tag}</span>
- ))}
- </div>
- <div className="mt-0.5 truncate text-[11px] text-[var(--text-faint)]">
- {[summaryText(commit.summary, t), age, commit.commit.slice(0, 7)].filter(Boolean).join(' · ')}
- </div>
- </div>
- {head ? <span className="shrink-0 text-[10.5px] text-[var(--text-muted)]">{t('versions.current')}</span> : null}
- <button
- ref={button}
- type="button"
- disabled={busy}
- aria-label={t('versions.moreActions')}
- aria-haspopup="menu"
- aria-expanded={anchor != null}
- onClick={(event) => {
- const box = event.currentTarget.getBoundingClientRect();
- setAnchor((cur) => (cur ? null : { x: box.right, y: box.bottom + 4, top: box.top - 4 }));
- }}
- className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-[var(--text-faint)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] ${anchor ? '' : 'opacity-0 focus-visible:opacity-100 group-hover:opacity-100'}`}
- >
- <MoreHorizontal size={14} />
- </button>
- {anchor ? <ContextMenu x={anchor.x} y={anchor.y} flipTo={anchor.top} align="end" trigger={button} onClose={() => setAnchor(null)} items={menu} /> : null}
- </div>
</li>
);
}
-function BranchList({ branches, current, now, busy, t, onSwitch, onNew, onMerge, onRename, onDelete }: {
- branches: Branch[];
- current: string;
- now: number;
- busy: boolean;
- t: Translate;
- onSwitch: (name: string) => void;
- onNew: () => void;
- onMerge: (name: string) => void;
- onRename: (name: string) => void;
- onDelete: (name: string) => void;
-}) {
- return (
- <div
- role="listbox"
- aria-label={t('versions.branches')}
- className="absolute left-3 right-3 top-[calc(100%-4px)] z-10 overflow-hidden rounded-xl border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg"
- style={{ animation: 'openfilm-rise 0.12s ease-out both' }}
- >
- <div className="max-h-[280px] overflow-y-auto p-1">
- {branches.map((b) => (
- <BranchRow key={b.name} branch={b} current={b.name === current} currentName={current} now={now} busy={busy} t={t}
- onSwitch={onSwitch} onMerge={onMerge} onRename={onRename} onDelete={onDelete} />
- ))}
- </div>
- <button
- type="button"
- onClick={onNew}
- disabled={busy}
- className="flex w-full items-center gap-2 border-t border-[var(--border)] px-3 py-2 text-left text-[12.5px] text-[var(--text)] transition hover:bg-[var(--bg-hover)] disabled:opacity-50"
- >
- <Plus size={13} /> {t('versions.newBranch')}
- </button>
- </div>
- );
-}
-
-function BranchRow({ branch, current, currentName, now, busy, t, onSwitch, onMerge, onRename, onDelete }: {
- branch: Branch;
- current: boolean;
- currentName: string;
- now: number;
- busy: boolean;
- t: Translate;
- onSwitch: (name: string) => void;
- onMerge: (name: string) => void;
- onRename: (name: string) => void;
- onDelete: (name: string) => void;
-}) {
- const [anchor, setAnchor] = React.useState<{ x: number; y: number; top: number } | null>(null);
- const button = React.useRef<HTMLButtonElement>(null);
- const items: ContextMenuEntry[] = [
- ...(current ? [] : [{ id: 'merge', icon: <GitMerge size={14} />, label: t('versions.mergeInto').replace('{branch}', currentName), onSelect: () => onMerge(branch.name) }]),
- { id: 'rename', icon: <Pencil size={14} />, label: t('versions.rename'), onSelect: () => onRename(branch.name) },
- ...(current ? [] : [
- { id: 'sep', separator: true as const },
- { id: 'delete', icon: <Trash2 size={14} />, label: t('versions.delete'), danger: true, onSelect: () => onDelete(branch.name) },
- ]),
- ];
- return (
- <div className="group flex items-center gap-1 rounded-lg transition hover:bg-[var(--bg-hover)]">
- <button
- type="button"
- role="option"
- aria-selected={current}
- aria-label={branch.name}
- disabled={busy}
- onClick={() => (current ? undefined : onSwitch(branch.name))}
- className="flex min-w-0 flex-1 items-start gap-2 px-2 py-1.5 text-left disabled:opacity-60"
- >
- <span className="mt-[3px] w-[13px] shrink-0">{current ? <Check size={13} className="text-[var(--text)]" /> : null}</span>
- <span className="min-w-0 flex-1">
- <span className={`block truncate text-[12.5px] ${current ? 'font-medium text-[var(--text)]' : 'text-[var(--text-dim)]'}`}>{branch.name}</span>
- <span className="block truncate text-[11px] text-[var(--text-faint)]">
- {[branch.message, ageLabel(branch.at, now, t)].filter(Boolean).join(' · ')}
- {branch.parked ? <span className="text-[var(--accent)]"> · {t('versions.parked')}</span> : null}
- </span>
- </span>
- </button>
- <button
- ref={button}
- type="button"
- disabled={busy}
- aria-label={t('versions.moreActions')}
- aria-haspopup="menu"
- aria-expanded={anchor != null}
- onClick={(event) => {
- const box = event.currentTarget.getBoundingClientRect();
- setAnchor((cur) => (cur ? null : { x: box.right, y: box.bottom + 4, top: box.top - 4 }));
- }}
- className={`mr-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-[var(--text-faint)] transition hover:bg-[var(--surface-2)] hover:text-[var(--text)] ${anchor ? '' : 'opacity-0 focus-visible:opacity-100 group-hover:opacity-100'}`}
- >
- <MoreHorizontal size={14} />
- </button>
- {anchor ? <ContextMenu x={anchor.x} y={anchor.y} flipTo={anchor.top} align="end" trigger={button} onClose={() => setAnchor(null)} items={items} /> : null}
- </div>
- );
-}
-
-/** Every question the panel asks, as one dialog whose words and choices follow what is asked. */
-function Questions({ dialog, branch, dirty, t, onCancel, onSwitch, onNewBranch, onNewBranchCarry, onRename, onDelete, onMerge, onRestore, onDiscard }: {
- dialog: Dialog | null;
- branch: string;
- dirty: boolean;
- t: Translate;
- onCancel: () => void;
- onSwitch: (target: string, carry: 'leave' | 'bring') => void;
- onNewBranch: (name: string, from?: Commit) => void;
- onNewBranchCarry: (name: string, from: Commit, carry: 'leave' | 'bring') => void;
- onRename: (from: string, name: string) => void;
- onDelete: (name: string, force: boolean) => void;
- onMerge: (name: string, message: string, prefer?: 'ours' | 'theirs') => void;
- onRestore: (commit: Commit) => void;
- onDiscard: () => void;
-}) {
- const [value, setValue] = React.useState('');
- /* each question starts with its own default text */
- React.useEffect(() => {
- if (!dialog) return;
- setValue(dialog.kind === 'rename' ? dialog.branch : dialog.kind === 'merge' ? t('versions.mergeMessage').replace('{name}', dialog.branch) : '');
- }, [dialog, t]);
- if (!dialog) return null;
- const fill = (key: string, vars: Record<string, string | number> = {}) =>
- Object.entries({ branch, ...vars }).reduce((s, [k, v]) => s.replaceAll(`{${k}}`, String(v)), t(key));
- const cancel = { label: t('versions.cancel'), weight: 'quiet' as const, onClick: onCancel };
- const typed = value.trim();
-
- switch (dialog.kind) {
- case 'switch':
- return (
- <Ask title={fill('versions.switchTitle', { name: dialog.target })} body={fill('versions.switchBody')} onCancel={onCancel}
- actions={[cancel,
- { label: fill('versions.bringChanges', { name: dialog.target }), weight: 'secondary', onClick: () => onSwitch(dialog.target, 'bring') },
- { label: fill('versions.leaveChanges'), weight: 'primary', onClick: () => onSwitch(dialog.target, 'leave') }]} />
- );
- case 'newBranchCarry':
- return (
- <Ask title={fill('versions.switchTitle', { name: dialog.name })} body={fill('versions.switchBody')} onCancel={onCancel}
- actions={[cancel,
- { label: fill('versions.bringChanges', { name: dialog.name }), weight: 'secondary', onClick: () => onNewBranchCarry(dialog.name, dialog.from, 'bring') },
- { label: fill('versions.leaveChanges'), weight: 'primary', onClick: () => onNewBranchCarry(dialog.name, dialog.from, 'leave') }]} />
- );
- case 'newBranch':
- return (
- <Ask
- title={dialog.from ? fill('versions.newBranchFromTitle', { name: dialog.from.message }) : t('versions.newBranchTitle')}
- body={fill(dialog.from ? 'versions.newBranchFromBody' : dirty ? 'versions.newBranchBody' : 'versions.newBranchBodyClean')}
- input={{ value, onChange: setValue, placeholder: t('versions.branchName') }}
- onCancel={onCancel}
- actions={[cancel, { label: t('versions.create'), weight: 'primary', disabled: !typed, onClick: () => onNewBranch(typed, dialog.from) }]} />
- );
- case 'rename':
- return (
- <Ask title={fill('versions.renameTitle', { name: dialog.branch })} input={{ value, onChange: setValue, placeholder: t('versions.branchName') }} onCancel={onCancel}
- actions={[cancel, { label: t('versions.save'), weight: 'primary', disabled: !typed, onClick: () => onRename(dialog.branch, typed) }]} />
- );
- case 'delete':
- return (
- <Ask title={fill('versions.deleteTitle', { name: dialog.branch })} body={fill('versions.deleteBody', { name: dialog.branch })} onCancel={onCancel}
- actions={[cancel, { label: t('versions.delete'), weight: 'danger', onClick: () => onDelete(dialog.branch, false) }]} />
- );
- case 'deleteForce':
- return (
- <Ask title={fill('versions.deleteForceTitle', { name: dialog.branch })}
- body={fill(dialog.commits === 1 ? 'versions.deleteForceBodyOne' : 'versions.deleteForceBody', { name: dialog.branch, n: dialog.commits })} onCancel={onCancel}
- actions={[cancel, { label: t('versions.deleteForce'), weight: 'danger', onClick: () => onDelete(dialog.branch, true) }]} />
- );
- case 'merge':
- return (
- <Ask title={fill('versions.mergeTitle', { name: dialog.branch })} body={dirty ? fill('versions.errorDirty') : fill('versions.mergeBody', { name: dialog.branch })}
- input={dirty ? undefined : { value, onChange: setValue, placeholder: t('versions.messagePlaceholder') }} onCancel={onCancel}
- actions={[cancel, { label: t('versions.mergeConfirm'), weight: 'primary', disabled: dirty || !typed, onClick: () => onMerge(dialog.branch, typed) }]} />
- );
- case 'mergeConflict':
- return (
- <Ask title={fill('versions.mergeConflictTitle', { name: dialog.branch })} body={fill('versions.mergeConflictBody', { name: dialog.branch })} onCancel={onCancel}
- actions={[cancel,
- { label: fill('versions.keepTheirs', { name: dialog.branch }), weight: 'secondary', onClick: () => onMerge(dialog.branch, dialog.message, 'theirs') },
- { label: fill('versions.keepOurs'), weight: 'primary', onClick: () => onMerge(dialog.branch, dialog.message, 'ours') }]} />
- );
- case 'restore':
- return (
- <Ask title={fill('versions.restoreTitle', { name: dialog.commit.message })} body={fill(dirty ? 'versions.restoreDirtyBody' : 'versions.restoreBody')} onCancel={onCancel}
- actions={[cancel, dirty
- ? { label: t('versions.restoreDiscard'), weight: 'danger', onClick: () => onRestore(dialog.commit) }
- : { label: t('versions.restoreConfirm'), weight: 'primary', onClick: () => onRestore(dialog.commit) }]} />
- );
- case 'discard':
- return (
- <Ask title={t('versions.discardTitle')} body={t('versions.discardBody')} onCancel={onCancel}
- actions={[cancel, { label: t('versions.discard'), weight: 'danger', onClick: onDiscard }]} />
- );
- default:
- return null;
- }
-}
-
/** A question in the middle of the window: a few words, maybe a field, and its choices (the last one is the default). */
-function Ask({ title, body, input, actions, onCancel }: {
+function Ask({
+ title,
+ body,
+ input,
+ actions,
+ onCancel,
+}: {
title: string;
body?: string;
input?: { value: string; onChange: (value: string) => void; placeholder: string };
- actions: Array<{ label: string; weight: 'primary' | 'secondary' | 'quiet' | 'danger'; disabled?: boolean; onClick: () => void }>;
+ actions: Array<{
+ label: string;
+ weight: 'primary' | 'secondary' | 'quiet' | 'danger';
+ disabled?: boolean;
+ onClick: () => void;
+ }>;
onCancel: () => void;
}) {
const field = React.useRef<HTMLInputElement>(null);
const last = React.useRef<HTMLButtonElement>(null);
+ const root = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
+ const previous = document.activeElement as HTMLElement | null;
(input ? field.current : last.current)?.focus();
if (input) field.current?.select();
- const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { e.stopPropagation(); onCancel(); } };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.stopPropagation();
+ onCancel();
+ }
+ if (e.key === 'Tab') {
+ const controls = [...(root.current?.querySelectorAll<HTMLElement>('button:not(:disabled),input') ?? [])];
+ const first = controls[0],
+ end = controls.at(-1);
+ if (e.shiftKey && document.activeElement === first) {
+ e.preventDefault();
+ end?.focus();
+ } else if (!e.shiftKey && document.activeElement === end) {
+ e.preventDefault();
+ first?.focus();
+ }
+ }
+ };
window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
+ return () => {
+ window.removeEventListener('keydown', onKey);
+ if (previous?.isConnected && !(previous instanceof HTMLButtonElement && previous.disabled)) previous.focus();
+ else document.querySelector<HTMLButtonElement>('[data-history-close]')?.focus();
+ };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const main = actions[actions.length - 1];
@@ -715,27 +925,46 @@ function Ask({ title, body, input, actions, onCancel }: {
style={{ animation: 'openfilm-rise 0.16s ease-out both' }}
onClick={onCancel}
>
- <div className="w-full max-w-[440px]" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label={title}>
+ <div
+ ref={root}
+ className="w-full max-w-[440px]"
+ onClick={(e) => e.stopPropagation()}
+ role="dialog"
+ aria-modal="true"
+ aria-label={title}
+ >
<Card title={title} body={body} onClose={onCancel}>
{input ? (
<form
className="mt-2.5"
- onSubmit={(e) => { e.preventDefault(); if (main && !main.disabled) main.onClick(); }}
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (main && !main.disabled) main.onClick();
+ }}
>
<input
ref={field}
value={input.value}
onChange={(e) => input.onChange(e.target.value)}
placeholder={input.placeholder}
+ aria-label={input.placeholder}
maxLength={200}
- onKeyDown={(e) => { if (e.key !== 'Escape') e.stopPropagation(); }}
+ onKeyDown={(e) => {
+ if (e.key !== 'Escape') e.stopPropagation();
+ }}
className="h-8 w-full rounded-lg bg-[var(--surface-2)] px-2.5 text-[12.5px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)] focus:ring-1 focus:ring-[var(--border-strong)]"
/>
</form>
) : null}
<CardActions className="flex-wrap">
{actions.map((a, i) => (
- <CardButton key={a.label} ref={i === actions.length - 1 ? last : undefined} weight={a.weight} disabled={a.disabled} onClick={a.onClick}>
+ <CardButton
+ key={a.label}
+ ref={i === actions.length - 1 ? last : undefined}
+ weight={a.weight}
+ disabled={a.disabled}
+ onClick={a.onClick}
+ >
{a.label}
</CardButton>
))}
@@ -743,6 +972,6 @@ function Ask({ title, body, input, actions, onCancel }: {
</Card>
</div>
</div>,
- document.body,
+ document.body
);
}
diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
index 357b783..5f69c18 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
@@ -85,6 +85,7 @@ import { ProjectLayoutMenu } from './ProjectLayoutMenu';
import { ProjectMenu } from './ProjectMenu';
import { ProjectHistoryButton, ProjectHistoryControls } from './ProjectHistoryControls';
import { useProjectHistory } from './use-project-history';
+import { historyMoved } from '@/lib/project-history';
import { ProjectsPopover } from './ProjectsLibrary';
import { FilmFullscreenBar, useFullscreenKeys } from './FilmFullscreenBar';
import { ViewerBar } from './ViewerBar';
@@ -2588,14 +2589,10 @@ export function ProjectView({ projectId, onProject, onLeave }: {
void subs.transcribe().then((r) => { if (!r.ok) setSubtitleProblem({ text: r.error ?? '', connect: !!r.needsTranscriber }); });
}, [subs, subtitleProblem]);
const [desktopOpen, setDesktopOpen] = React.useState(false);
- const headerOpsRef = React.useRef<HTMLDivElement>(null);
const [historyOpen, setHistoryOpen] = React.useState(false);
- const [historyAnchor, setHistoryAnchor] = React.useState<{ x: number; y: number } | null>(null);
- const history = useProjectHistory(projectId, {
- onError: toast.showError,
- onMoved: () => { film.forget(); void api.film(projectId).then((f) => { setLoaded(f); }); },
- beforeCommit: film.settled,
- });
+ const history = useProjectHistory(projectId, { onError: toast.showError, beforeChange: film.settled });
+ const forgetSteps = React.useRef(film.forget);
+ forgetSteps.current = film.forget;
const refreshHistory = React.useRef(history.refresh);
refreshHistory.current = history.refresh;
const historyOpenRef = React.useRef(historyOpen);
@@ -2605,6 +2602,14 @@ export function ProjectView({ projectId, onProject, onLeave }: {
changes, once the burst settles */
let later: ReturnType<typeof setTimeout> | null = null;
const stop = projectEvents(projectId, (e) => {
+ /* a version restored, here or in another window: the folder's files changed under the editor. Its undo steps
+ were of the film before, and the film, its settings, markers and subtitles are read again (each where it is
+ kept: use-editor-tools, use-subtitle-style, use-film-subtitles) */
+ if (historyMoved(e)) {
+ forgetSteps.current();
+ void api.film(projectId).then((f) => { setLoaded(f); }, () => {});
+ void api.settings(projectId).then(setSettings, () => {});
+ }
if (e.type === 'history') { void refreshHistory.current(); return; }
if ((e.type === 'film' || e.type === 'files') && historyOpenRef.current) {
if (later) clearTimeout(later);
@@ -2614,8 +2619,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
return () => { if (later) clearTimeout(later); stop(); };
}, [projectId]);
const openHistory = () => {
- const rect = headerOpsRef.current?.getBoundingClientRect();
- if (rect) setHistoryAnchor({ x: rect.right, y: rect.bottom + 4 });
+ pause();
setHistoryOpen((v) => !v);
};
const [exportOpen, setExportOpen] = React.useState(false);
@@ -2712,7 +2716,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
{inTabs ? (
<TabStrip onRename={renameTab} onNew={() => setProjectsOpen(true)} onCoverFromFrame={coverFromFrame} maxLength={TITLE_MAX_CHARS} />
) : <div className="min-w-0 flex-1" />}
- <div ref={headerOpsRef} className="pointer-events-auto flex min-w-0 items-center justify-end gap-1">
+ <div className="pointer-events-auto flex min-w-0 items-center justify-end gap-1">
<ProjectLayoutMenu className={TOP_BTN}
/* an app that keeps the media in its own panel opens it there, from its own button: not a pane of Studio's */
assets={hostAssets ? null : assetsPaneOpen} onAssets={setAssetsPaneOpen}
@@ -3121,7 +3125,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {
</div>
</div>
- <ProjectHistoryControls projectId={projectId} history={history} open={historyOpen} anchor={historyAnchor} onClose={() => setHistoryOpen(false)} />
+ <ProjectHistoryControls projectId={projectId} projectName={loaded?.project.name ?? ''} history={history} open={historyOpen}
+ onClose={() => setHistoryOpen(false)}
+ onOpenProject={(id) => { setHistoryOpen(false); if (studioHost?.tabs) studioHost.tabs.open(id); else onProject(id); }} />
<ProjectsPopover open={projectsOpen} currentProjectId={projectId} onOpen={(id) => { if (!studioHost?.tabs) setProjectsOpen(false); onProject(id); }} onCurrentRemoved={onLeave} onClose={() => setProjectsOpen(false)} />
{examplesOpen ? (
<ExamplesDialog projectId={projectId} open={examplesOpen === true ? undefined : examplesOpen} onClose={() => setExamplesOpen(false)}
@@ -3149,6 +3155,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
frame="native"
film={exportFilm as never}
playheadMs={timeMs}
+ markersMs={tools.timeline.snapPointsMs}
mgBlocks={mgBlocks}
{...(exportClipId ? { focusClipId: exportClipId } : {})}
onQueued={(jobs) => exportTrayRef.current?.push(jobs)}
diff --git a/packages/openfilm/studio/ui/src/components/VersionVideoPreview.tsx b/packages/openfilm/studio/ui/src/components/VersionVideoPreview.tsx
new file mode 100644
index 0000000..5677a31
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/VersionVideoPreview.tsx
@@ -0,0 +1,189 @@
+/** A saved version plays from its own read-only folder, with its own clock and audio mix. */
+import React from 'react';
+import { Loader2, Pause, Play, Volume2, VolumeX } from 'lucide-react';
+import { api } from '@/api';
+import { Preview, type FilmInfo, type PreviewHandle } from '@/editor/Preview';
+import { Player } from '@/editor/player';
+import { useT } from '@/i18n';
+import { historyApi, type VersionPreview } from '@/lib/project-history';
+
+const clock = (seconds: number) =>
+ `${Math.floor(seconds / 60)
+ .toString()
+ .padStart(2, '0')}:${Math.floor(seconds % 60)
+ .toString()
+ .padStart(2, '0')}`;
+
+export function VersionVideoPreview({ projectId, commit }: { projectId: string; commit: string | null }) {
+ const t = useT();
+ const [snapshot, setSnapshot] = React.useState<VersionPreview | null>(null);
+ const [failed, setFailed] = React.useState(false);
+ const [attempt, setAttempt] = React.useState(0);
+ React.useEffect(() => {
+ let active = true;
+ setSnapshot(null);
+ setFailed(false);
+ const load = async () => {
+ if (commit) {
+ const result = await historyApi.preview(projectId, commit);
+ if (active) {
+ if (result.ok) setSnapshot(result.body);
+ else setFailed(true);
+ }
+ } else {
+ try {
+ const film = await api.film(projectId);
+ if (active) setSnapshot({ folder: film.folder, doc: film.doc, missing: [] });
+ } catch {
+ if (active) setFailed(true);
+ }
+ }
+ };
+ void load();
+ return () => {
+ active = false;
+ };
+ }, [projectId, commit, attempt]);
+
+ if (failed || (snapshot && !snapshot.doc))
+ return (
+ <div
+ role="alert"
+ className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 bg-[var(--canvas)] px-6 py-8 text-center"
+ >
+ <p className="text-[12px] text-[var(--text-muted)]">{t('versions.previewFailed')}</p>
+ <button
+ type="button"
+ onClick={() => setAttempt((n) => n + 1)}
+ className="rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px]"
+ >
+ {t('versions.retry')}
+ </button>
+ </div>
+ );
+ if (!snapshot)
+ return (
+ <div
+ role="status"
+ aria-label={t('versions.previewLoading')}
+ className="flex min-h-0 flex-1 items-center justify-center gap-2 bg-[var(--canvas)] text-[12px] text-[var(--text-muted)]"
+ >
+ <Loader2 size={15} className="animate-spin" />
+ {t('versions.previewLoading')}
+ </div>
+ );
+ return <SnapshotPlayer snapshot={snapshot} />;
+}
+
+function SnapshotPlayer({ snapshot }: { snapshot: VersionPreview }) {
+ const t = useT();
+ const preview = React.useRef<PreviewHandle>(null);
+ const [player] = React.useState(() => new Player());
+ const [stage, setStage] = React.useState(snapshot.doc?.stage ?? { w: 1920, h: 1080 });
+ const [duration, setDuration] = React.useState(0);
+ const [time, setTime] = React.useState(0);
+ const [playing, setPlaying] = React.useState(false);
+ const [muted, setMuted] = React.useState(false);
+ const [error, setError] = React.useState<string | null>(null);
+ const now = React.useCallback(() => player.time(), [player]);
+ React.useEffect(() => {
+ player.onAnchor = (anchor) => preview.current?.play?.(anchor);
+ return () => {
+ player.onAnchor = null;
+ player.close();
+ };
+ }, [player]);
+ React.useEffect(() => {
+ if (!playing) return;
+ let frame = 0;
+ const tick = () => {
+ const at = player.time();
+ setTime(at);
+ if (at >= player.duration - 0.001) {
+ player.pause();
+ preview.current?.seek(Math.max(0, player.duration - 0.001));
+ setPlaying(false);
+ } else frame = requestAnimationFrame(tick);
+ };
+ frame = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(frame);
+ }, [playing, player]);
+ React.useEffect(() => {
+ if (error) {
+ player.pause();
+ setPlaying(false);
+ }
+ }, [error, player]);
+ const onInfo = React.useCallback(
+ (info: FilmInfo) => {
+ setStage({ w: info.width, h: info.height });
+ setDuration(info.duration);
+ player.load(snapshot.folder, info.sounds, info.duration);
+ },
+ [player, snapshot.folder]
+ );
+ const seek = (at: number) => {
+ player.seek(at);
+ if (!player.playing) preview.current?.seek(Math.min(at, Math.max(0, duration - 0.001)));
+ setTime(at);
+ };
+ const toggle = () => {
+ if (!duration || error) return;
+ if (player.playing) {
+ player.pause();
+ preview.current?.seek(player.time());
+ } else player.play();
+ setPlaying(player.playing);
+ };
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="relative min-h-0 flex-1 bg-[var(--canvas)]" aria-label={t('versions.videoPreview')}>
+ <Preview ref={preview} folder={snapshot.folder} stage={stage} time={now} onInfo={onInfo} onError={setError} />
+ </div>
+ {snapshot.missing.length ? (
+ <p
+ role="status"
+ className="shrink-0 border-t border-[var(--border-soft)] bg-[var(--surface-2)] px-4 py-1.5 text-[11px] text-[var(--warn)]"
+ >
+ {t('versions.previewMissing').replace('{n}', String(snapshot.missing.length))}
+ </p>
+ ) : null}
+ <div className="flex h-11 shrink-0 items-center gap-3 border-t border-[var(--border-soft)] px-4">
+ <button
+ type="button"
+ disabled={!duration || !!error}
+ onClick={toggle}
+ aria-label={t(playing ? 'versions.pause' : 'versions.play')}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[var(--text-dim)] hover:bg-[var(--bg-hover)] disabled:opacity-40"
+ >
+ {playing ? <Pause size={16} /> : <Play size={16} />}
+ </button>
+ <span className="shrink-0 text-[11px] tabular-nums text-[var(--text-muted)]">
+ {clock(time)} / {clock(duration)}
+ </span>
+ <input
+ type="range"
+ aria-label={t('versions.seek')}
+ min={0}
+ max={duration || 1}
+ step={0.01}
+ value={time}
+ disabled={!duration || !!error}
+ onChange={(e) => seek(Number(e.target.value))}
+ className="h-1 min-w-0 flex-1 cursor-pointer accent-[var(--text)]"
+ />
+ <button
+ type="button"
+ aria-label={t(muted ? 'versions.unmute' : 'versions.mute')}
+ onClick={() => {
+ player.setMuted(!muted);
+ setMuted(!muted);
+ }}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[var(--text-muted)] hover:bg-[var(--bg-hover)]"
+ >
+ {muted ? <VolumeX size={15} /> : <Volume2 size={15} />}
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/openfilm/studio/ui/src/components/WhatsNew.tsx b/packages/openfilm/studio/ui/src/components/WhatsNew.tsx
index aec808e..7b04556 100644
--- a/packages/openfilm/studio/ui/src/components/WhatsNew.tsx
+++ b/packages/openfilm/studio/ui/src/components/WhatsNew.tsx
@@ -1,8 +1,9 @@
/**
* "What's new" after an update (lib/whats-new.ts): once Studio runs a newer version than the one whose notes were last
- * shown, the notes since then, in the language shown, grouped as new, improved and fixed, with the full changelog a
- * click away. Closing it marks this version seen. A new install shows nothing (it only remembers the version).
- * Settings › About shows this release's notes again, and Developer previews the newest (WHATS_NEW_EVENT).
+ * shown, the notes since then, in the language shown, grouped as new, improved and fixed; under them, scrolling on,
+ * every earlier release's, so the whole history reads in the person's language (the changelog on GitHub, a click
+ * away, is in English). Closing it marks this version seen. A new install shows nothing (it only remembers the
+ * version). Settings › About shows this release's notes again, and Developer previews the newest (WHATS_NEW_EVENT).
*/
import React from 'react';
import { createPortal } from 'react-dom';
@@ -21,7 +22,6 @@ const KIND_ICON: Record<NoteKind, React.ReactNode> = {
export function WhatsNew() {
const t = useT();
- const language = useLanguage();
const [shown, setShown] = React.useState<ReleaseNotes[] | null>(null);
/** the version to mark seen when closed (after an update), null when opened on asking */
const [marking, setMarking] = React.useState<string | null>(null);
@@ -67,10 +67,9 @@ export function WhatsNew() {
if (!shown || typeof document === 'undefined') return null;
const newest = shown[0];
- const date = (iso: string) => {
- const d = new Date(`${iso}T12:00:00`);
- return Number.isNaN(d.getTime()) ? iso : d.toLocaleDateString(language, { year: 'numeric', month: 'long', day: 'numeric' });
- };
+ /* the releases before those shown, the newest first */
+ const oldest = shown[shown.length - 1];
+ const earlier = RELEASES.filter((r) => compareVersions(r.version, oldest.version) < 0);
return createPortal(
/* over Settings (z 10050), where About and Developer open it */
@@ -80,7 +79,7 @@ export function WhatsNew() {
aria-modal="true"
aria-labelledby="whats-new-title"
onClick={(e) => e.stopPropagation()}
- className="flex max-h-[min(640px,88vh)] w-full max-w-[520px] flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--surface)] shadow-[var(--shadow-lg)]"
+ className="flex max-h-[min(760px,88vh)] w-full max-w-[560px] flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--surface)] shadow-[var(--shadow-lg)]"
>
<div className="flex items-start gap-3 px-6 pb-2 pt-6">
<div className="min-w-0 flex-1">
@@ -95,35 +94,15 @@ export function WhatsNew() {
</button>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-6 pb-2">
- {shown.map((release) => {
- const notes = release.notes[language] ?? release.notes.en;
- return (
- <section key={release.version} className="py-3">
- <p className="mb-2.5 text-[12.5px] text-[var(--text-muted)]">
- {shown.length > 1 ? `OpenFilm ${release.version} · ` : ''}{date(release.date)}
- </p>
- <div className="flex flex-col gap-3.5">
- {KINDS.map((kind) => {
- const items = notes.filter((n) => n.kind === kind);
- if (!items.length) return null;
- return (
- <div key={kind}>
- <p className="mb-1.5 flex items-center gap-1.5 text-[12.5px] font-semibold text-[var(--text)]">
- <span className="text-[var(--text-muted)]">{KIND_ICON[kind]}</span>
- {t(`whatsNew.kind.${kind}`)}
- </p>
- <ul className="flex flex-col gap-1.5 pl-5">
- {items.map((n, i) => (
- <li key={i} className="list-disc text-[13.5px] leading-[1.6] text-[var(--text-muted)] marker:text-[var(--text-faint)]">{n.text}</li>
- ))}
- </ul>
- </div>
- );
- })}
- </div>
- </section>
- );
- })}
+ {shown.map((release) => <Release key={release.version} release={release} heading={shown.length > 1} />)}
+ {earlier.length > 0 && (
+ <>
+ <p className="mt-2 border-t border-[var(--border)] pt-4 text-[11.5px] font-medium uppercase tracking-[0.08em] text-[var(--text-faint)]">
+ {t('whatsNew.earlier')}
+ </p>
+ {earlier.map((release) => <Release key={release.version} release={release} heading />)}
+ </>
+ )}
</div>
<div className="flex items-center gap-3 border-t border-[var(--border)] px-6 py-4">
<a href={CHANGELOG} target="_blank" rel="noreferrer"
@@ -141,6 +120,41 @@ export function WhatsNew() {
);
}
+/** One release's notes in the language shown, grouped as new, improved and fixed; `heading`: its version beside its date. */
+function Release({ release, heading }: { release: ReleaseNotes; heading: boolean }) {
+ const t = useT();
+ const language = useLanguage();
+ const notes = release.notes[language] ?? release.notes.en;
+ const d = new Date(`${release.date}T12:00:00`);
+ const date = Number.isNaN(d.getTime()) ? release.date : d.toLocaleDateString(language, { year: 'numeric', month: 'long', day: 'numeric' });
+ return (
+ <section className="py-3">
+ <p className="mb-2.5 text-[12.5px] text-[var(--text-muted)]">
+ {heading ? <span className="font-medium text-[var(--text)]">{`OpenFilm ${release.version} · `}</span> : null}{date}
+ </p>
+ <div className="flex flex-col gap-3.5">
+ {KINDS.map((kind) => {
+ const items = notes.filter((n) => n.kind === kind);
+ if (!items.length) return null;
+ return (
+ <div key={kind}>
+ <p className="mb-1.5 flex items-center gap-1.5 text-[12.5px] font-semibold text-[var(--text)]">
+ <span className="text-[var(--text-muted)]">{KIND_ICON[kind]}</span>
+ {t(`whatsNew.kind.${kind}`)}
+ </p>
+ <ul className="flex flex-col gap-1.5 pl-5">
+ {items.map((n, i) => (
+ <li key={i} className="list-disc text-[13.5px] leading-[1.6] text-[var(--text-muted)] marker:text-[var(--text-faint)]">{n.text}</li>
+ ))}
+ </ul>
+ </div>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
+
/** Whether this release has notes to show again (Settings › About). */
export const hasNotes = (version: string | undefined) => Boolean(version && releaseNotes(version));
/** The newest release's notes, for a preview before it ships (Developer). */
diff --git a/packages/openfilm/studio/ui/src/components/dialog-chrome.ts b/packages/openfilm/studio/ui/src/components/dialog-chrome.ts
new file mode 100644
index 0000000..ddd3050
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/dialog-chrome.ts
@@ -0,0 +1,5 @@
+/** The export and version-history windows share their size, placement and surface. */
+export const LARGE_DIALOG_BACKDROP =
+ 'fixed inset-0 z-[130] flex items-center justify-center bg-black/50 p-3 sm:p-5 lg:p-6';
+export const LARGE_DIALOG =
+ 'flex h-[88dvh] max-h-[1000px] w-[92vw] max-w-[1600px] min-h-0 min-w-0 overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--surface)] shadow-[var(--shadow-lg)]';
diff --git a/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx b/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx
index a39a5ce..35dde46 100644
--- a/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx
+++ b/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx
@@ -1,9 +1,8 @@
/**
* The export center: the project menu's "Export".
*
- * Organized by where the film is going, not by format: a platform, an editor, a GIF, the sound, stills. Each
- * destination has its own few settings and a one-line summary of what comes out, and one primary button says what
- * happens.
+ * Video files share one page: Default and platform presets fill the same editable encoding settings. Other
+ * destinations cover editing projects, transparent assets, GIFs, sound, stills and project files.
*
* Everything renders on this machine, in Studio's server (see lib/export-jobs): the dialog closes as soon as the
* exports are queued, and the export tray follows them.
@@ -11,7 +10,7 @@
* What was chosen last time for each destination is kept in this browser (localStorage) and comes back next time.
*/
import {
- AlertTriangle, AudioLines, Captions, Check, ChevronDown, Clapperboard, Download, Film, FolderArchive, FolderOpen, Images, Layers, Loader2, MonitorPlay, Presentation,
+ AlertTriangle, AudioLines, Captions, ChevronDown, Clapperboard, Film, FolderArchive, FolderOpen, Images, Layers, Loader2,
Sparkles, X,
} from 'lucide-react';
import React from 'react';
@@ -22,21 +21,20 @@ import { studioHost } from '@/lib/host';
import { MenuSelect } from '@/components/MenuSelect';
import { CustomFrame } from '@/components/FramePicker';
import { FRAME_RATES } from '@/lib/timecode';
+import { applyRangeDelivery, readExportRanges, requestDurationMs, type ExportRangeDraft, type RangeDelivery } from '@/lib/export-range';
import { api } from '@/api';
+import { DEFAULT_VIDEO_EXPORT, legacySocialVideo, patchVideoExport, readVideoExport, videoExportPreset, type VideoExportSettings } from '@/lib/video-export-preset';
import {
CODEC_LABEL,
EXPORT_ALPHA_CODECS,
exportPresetsFor,
- exportDimsForShortEdge,
exportEstimateBytes,
exportFilmPixels,
exportFramedDims,
exportGifDims,
exportGifEstimateBytes,
exportPreset,
- presetFps,
rangeMarks,
- type ExportPresetGroup,
type ExportQuality,
type ExportVideoCodec,
} from '@/lib/export-spec';
@@ -55,19 +53,23 @@ import {
type ProjectSizes,
} from '@/lib/export-jobs';
import { FILM_FRAME_IDS, filmFrameBox, filmFrameRatio, type FilmFrameFill, type FilmFrameId } from '@/lib/film-frame';
+import { cleanMoments, loadSharedMoments, MOMENTS_MAX, momentSeconds, saveMoments } from '@/lib/export-moments';
+import { MomentPicker } from './MomentPicker';
+import { RangePicker } from './RangePicker';
+import { LARGE_DIALOG, LARGE_DIALOG_BACKDROP } from '../dialog-chrome';
-type Dest = 'social' | 'video' | 'alpha' | 'nle' | 'gif' | 'audio' | 'subtitles' | 'images' | 'slides' | 'project';
+type Dest = 'video' | 'alpha' | 'nle' | 'gif' | 'audio' | 'subtitles' | 'images' | 'project';
+type ImageOutput = 'files' | 'zip' | 'pdf' | 'pptx';
+const IMAGE_OUTPUTS: readonly ImageOutput[] = ['files', 'zip', 'pdf', 'pptx'];
const DESTS: readonly { id: Dest; icon: React.ReactNode }[] = [
{ id: 'video', icon: <Film size={16} /> },
{ id: 'nle', icon: <Clapperboard size={16} /> },
- { id: 'social', icon: <MonitorPlay size={16} /> },
{ id: 'alpha', icon: <Layers size={16} /> },
{ id: 'gif', icon: <Sparkles size={16} /> },
{ id: 'audio', icon: <AudioLines size={16} /> },
{ id: 'subtitles', icon: <Captions size={16} /> },
{ id: 'images', icon: <Images size={16} /> },
- { id: 'slides', icon: <Presentation size={16} /> },
{ id: 'project', icon: <FolderArchive size={16} /> },
];
@@ -91,21 +93,7 @@ const WHOLE_FILM = '__film__';
interface Settings {
dest: Dest;
- presets: string[];
- socialQuality: ExportQuality;
- /** Burned-in subtitles on platform exports: each platform's habit, all, or none. */
- socialSubs: 'auto' | 'on' | 'off';
- video: {
- codec: ExportVideoCodec;
- shortEdge: number;
- fps: number | 'source';
- quality: ExportQuality;
- frame: FrameChoice;
- fill: FilmFrameFill;
- audio: boolean;
- burn: boolean;
- sidecar: 'none' | 'srt' | 'vtt';
- };
+ video: VideoExportSettings;
gif: { width: number; fps: number; frame: FrameChoice; fill: FilmFrameFill; burn: boolean };
/** `source`: a block's clip id, or the whole film. */
alpha: { codec: ExportVideoCodec; source: string; shortEdge: number; scale: number; fps: number; audio: boolean };
@@ -117,8 +105,7 @@ interface Settings {
/** How the pages are written: for a draft, and for Premiere Pro or DaVinci Resolve (Final Cut Pro takes ProRes). */
alphaDraft: NleAlpha; alphaXml: NleAlpha };
subtitles: { format: 'srt' | 'vtt' | 'txt' };
- images: { format: 'png' | 'jpg'; shortEdge: number; frame: FrameChoice; fill: FilmFrameFill; burn: boolean };
- slides: { format: 'pptx' | 'pdf'; shortEdge: number; frame: FrameChoice; fill: FilmFrameFill; burn: boolean };
+ images: { as: ImageOutput; format: 'png' | 'jpg'; shortEdge: number; frame: FrameChoice; fill: FilmFrameFill; burn: boolean };
/** The project itself: a zip or a folder, and which parts besides its work (conversations and logs are private). */
project: { as: 'zip' | 'folder' } & Record<ProjectPart, boolean>;
/** Where exports are written. Empty = the default folder. */
@@ -127,46 +114,57 @@ interface Settings {
const DEFAULTS: Settings = {
dest: 'video',
- presets: ['youtube'],
- socialQuality: 'high',
- socialSubs: 'auto',
- video: {
- codec: 'h264', shortEdge: 1080, fps: 'source', quality: 'high', frame: 'current', fill: 'contain', audio: true, burn: true, sidecar: 'none',
- },
+ video: { ...DEFAULT_VIDEO_EXPORT },
gif: { width: 640, fps: 15, frame: 'current', fill: 'contain', burn: true },
alpha: { codec: 'prores4444', source: WHOLE_FILM, shortEdge: 1080, scale: 1, fps: 30, audio: true },
audio: { format: 'wav', mix: true, stems: false },
nle: { app: 'auto', fps: 'source', audio: 'clips', subtitles: true, alphaDraft: 'auto', alphaXml: 'prores4444' },
subtitles: { format: 'srt' },
- images: { format: 'png', shortEdge: 1080, frame: 'current', fill: 'contain', burn: false },
- slides: { format: 'pptx', shortEdge: 1080, frame: 'current', fill: 'contain', burn: false },
+ images: { as: 'files', format: 'png', shortEdge: 1080, frame: 'current', fill: 'contain', burn: false },
project: { as: 'zip', history: false, chat: false, logs: false },
folder: '',
};
const STORE_KEY = 'openfilm.exportCenter.v1';
-/** What was chosen last time; the first time, the defaults (哔哩哔哩 rather than YouTube in Chinese). */
-function loadSettings(language: string): Settings {
- const first = language === 'zh-CN' ? { ...DEFAULTS, presets: ['bilibili'] } : DEFAULTS;
+/** Retain previous settings, including projects last exported from the former social-platform page. */
+function loadSettings(language: string, projectFps: number): Settings {
+ const first = DEFAULTS;
try {
- const raw = JSON.parse(localStorage.getItem(STORE_KEY) ?? 'null') as Partial<Settings> | null;
+ const raw = JSON.parse(localStorage.getItem(STORE_KEY) ?? 'null') as (Omit<Partial<Settings>, 'dest'> & {
+ dest?: Dest | 'social' | 'slides';
+ presets?: string[]; socialQuality?: ExportQuality; socialSubs?: 'auto' | 'on' | 'off';
+ slides?: Omit<Settings['images'], 'as' | 'format'> & { format?: 'pdf' | 'pptx' };
+ }) | null;
if (!raw || typeof raw !== 'object') return first;
const nle = { ...DEFAULTS.nle, ...raw.nle };
if (nle.app !== 'auto' && nle.app !== 'draft' && !Object.hasOwn(NLE_APPS, nle.app)) nle.app = 'auto';
+ const images = { ...DEFAULTS.images, ...raw.images };
+ if (!IMAGE_OUTPUTS.includes(images.as)) images.as = 'files';
+ if (raw.dest === 'slides') {
+ const { format, ...framing } = raw.slides ?? {};
+ Object.assign(images, framing, { as: format === 'pdf' ? 'pdf' : 'pptx' });
+ }
+ const offered = exportPresetsFor(language);
+ const previousPlatform = Array.isArray(raw.presets)
+ ? raw.presets.find((id) => offered.some((p) => p.id === id))
+ : language === 'zh-CN' ? 'bilibili' : 'youtube';
+ const video = raw.dest === 'social'
+ ? legacySocialVideo(previousPlatform ?? 'default', raw.socialQuality, raw.socialSubs, projectFps)
+ : readVideoExport(raw.video);
+ if (exportPreset(video.preset) && !offered.some((p) => p.id === video.preset)) video.preset = 'custom';
return {
...DEFAULTS,
...raw,
- presets: Array.isArray(raw.presets) ? raw.presets.filter((id) => exportPreset(id)) : DEFAULTS.presets,
+ dest: raw.dest === 'slides' ? 'images' : raw.dest === 'social' ? 'video' : raw.dest ?? DEFAULTS.dest,
/* sound starts on each time: switched off for one export and kept, every later one came out silent unnoticed */
- video: { ...DEFAULTS.video, ...raw.video, audio: true },
+ video,
gif: { ...DEFAULTS.gif, ...raw.gif },
alpha: { ...DEFAULTS.alpha, ...raw.alpha, audio: true },
audio: { ...DEFAULTS.audio, ...raw.audio },
nle,
subtitles: { ...DEFAULTS.subtitles, ...raw.subtitles },
- images: { ...DEFAULTS.images, ...raw.images },
- slides: { ...DEFAULTS.slides, ...raw.slides },
+ images,
/* the parts besides the work start off each time (history, chat and logs are the person's own): only zip or
folder is kept */
project: { ...DEFAULTS.project, ...(raw.project?.as === 'folder' ? { as: 'folder' } : {}) },
@@ -188,7 +186,6 @@ const GIF_WIDTHS = [320, 480, 640, 800, 1080];
const GIF_FPS = [10, 12, 15, 20, 24];
const VIDEO_CODECS: ExportVideoCodec[] = ['h264', 'hevc', 'prores422hq', 'prores4444', 'hevc_alpha', 'vp9', 'png'];
const ALPHA_SCALES = [0.5, 1, 2];
-const PRESET_GROUPS: ExportPresetGroup[] = ['landscape', 'vertical', 'feed'];
/** The rates editors take; a source at another NTSC rate (23.976, 59.94) comes as the "source" choice. */
const NLE_FPS = [23.976, 24, 25, 29.97, 30, 50, 59.94, 60];
/** How a draft and an XML write their pages (exports.mjs), the default first. */
@@ -230,8 +227,10 @@ export interface ExportCenterProps {
/** Video clips not probed yet: the film is not known to be silent while there are any. */
unprobed?: number;
} | null;
- /** Where the playhead is: the poster is that frame (the middle of the film without it). */
+ /** Where the playhead is: the image picked to begin with (the middle of the film without it). */
playheadMs?: number;
+ /** The markers on the film (ms): the images or slides can be one at each. */
+ markersMs?: readonly number[];
/** The timeline's motion-graphic blocks: a transparent export can be just one of them. */
mgBlocks?: readonly { clipId: string; label: string; startMs: number; durMs: number }[];
/** From a block's "Export this clip": opens on transparent assets with that block chosen. */
@@ -245,7 +244,7 @@ export interface ExportCenterProps {
}
/** What draws or plays the film, and so needs every file it uses. */
-const RENDERS: ReadonlySet<Dest> = new Set(['social', 'video', 'alpha', 'gif', 'audio', 'images', 'slides']);
+const RENDERS: ReadonlySet<Dest> = new Set(['video', 'alpha', 'gif', 'audio', 'images']);
export function ExportCenter(props: ExportCenterProps) {
const { open, onClose } = props;
@@ -258,7 +257,9 @@ export function ExportCenter(props: ExportCenterProps) {
const [draftApps, setDraftApps] = React.useState<{ jianying: boolean; capcut: boolean }>({ jianying: false, capcut: false });
const [s, setS] = React.useState<Settings>(DEFAULTS);
const [hydrated, setHydrated] = React.useState(false);
- const [range, setRange] = React.useState<{ on: boolean; from: number; to: number }>({ on: false, from: 0, to: 0 });
+ const [range, setRange] = React.useState(false);
+ const [rangeParts, setRangeParts] = React.useState<ExportRangeDraft[]>([]);
+ const [rangeDelivery, setRangeDelivery] = React.useState<RangeDelivery>('separate');
const [working, setWorking] = React.useState<string | null>(null);
const [result, setResult] = React.useState<{ ok: boolean; text: string } | null>(null);
const [defaultFolder, setDefaultFolder] = React.useState<string>('');
@@ -277,7 +278,7 @@ export function ExportCenter(props: ExportCenterProps) {
React.useEffect(() => {
if (!open) return;
- const loaded = loadSettings(language);
+ const loaded = loadSettings(language, props.projectFps ?? 30);
setS(props.focusClipId
? { ...loaded, dest: 'alpha', alpha: { ...loaded.alpha, source: props.focusClipId } }
: loaded);
@@ -288,7 +289,7 @@ export function ExportCenter(props: ExportCenterProps) {
/* a name is this export's, not a setting: each visit starts from the project's own */
setExportName(props.title);
setNameTyped(false);
- setRange((r) => ({ ...r, on: false }));
+ setRange(false);
void listExports(props.projectId).then((r) => { setCan(r.can); setDraftApps({ jianying: Boolean(r.drafts?.jianying), capcut: Boolean(r.drafts?.capcut) }); setDefaultFolder(r.folder); setCaptionCount(r.subtitles ?? 0); setProjectSizes(r.project ?? null); }).catch(() => {});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
@@ -299,7 +300,7 @@ export function ExportCenter(props: ExportCenterProps) {
React.useEffect(() => {
if (!open) return undefined;
- const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape' && !working) onClose(); };
+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape' && !e.defaultPrevented && !working) onClose(); };
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [open, onClose, working]);
@@ -333,38 +334,38 @@ export function ExportCenter(props: ExportCenterProps) {
return () => { live = false; };
}, [open, footageSrc, props.projectId]);
- /* where a part can start and end: the picture clips' edges, each named by its clips (rangeMarks) */
+ /* Clip edges remain shortcuts; the time fields can name any point in the film. */
const boundaries = React.useMemo(() => rangeMarks(film?.scenes ?? [], totalMs), [film, totalMs]);
- /* one still from the middle of each picture clip (clips starting together give one): what the server makes */
- const stillCount = React.useMemo(() => {
- if (!film) return 1;
- let lastAt = -Infinity;
- let n = 0;
- for (const sc of [...film.scenes].sort((a, b) => a.startMs - b.startMs)) {
- if (!(sc.durMs > 0) || sc.startMs >= totalMs || sc.startMs - lastAt < 400) continue;
- lastAt = sc.startMs;
- n++;
- }
- return Math.max(1, Math.min(120, n));
- }, [film, totalMs]);
-
React.useEffect(() => {
- setRange((r) => ({ ...r, from: 0, to: totalMs }));
- }, [totalMs]);
+ setRangeParts([{ id: 'initial', from: '0', to: String(Math.min(3000, totalMs) / 1000) }]);
+ }, [totalMs, props.projectId]);
- const exportRange = range.on && range.to > range.from && (range.from > 0 || range.to < totalMs)
- ? { fromMs: range.from, toMs: range.to }
- : undefined;
- const rangeMs = exportRange ? exportRange.toMs - exportRange.fromMs : totalMs;
- const rangeSec: [number, number] | undefined = exportRange ? [exportRange.fromMs / 1000, exportRange.toMs / 1000] : undefined;
+ const projectFps = props.projectFps ?? 30;
+ const parsedRanges = readExportRanges(rangeParts, totalMs, projectFps);
+ const rangeMs = range && parsedRanges ? parsedRanges.reduce((n, [from, to]) => n + (to - from) * 1000, 0) : totalMs;
const resolveFrame = (f: FrameChoice): FilmFrameId => (f === 'current' ? props.frame : f);
/* 'source' is the project's own rate */
- const projectFps = props.projectFps ?? 30;
const fpsFor = (f: number | 'source'): number => (f === 'source' ? projectFps : f);
+ /* All four deliveries share the same picks. Read the old separate lists on first use, without losing a selection. */
+ const [moments, setMoments] = React.useState<number[]>([]);
+ React.useEffect(() => {
+ if (!open || !(totalMs > 0)) return;
+ const output = loadSettings(language, projectFps).images.as;
+ const previous = output === 'pdf' || output === 'pptx' ? 'slides' : 'images';
+ const list = cleanMoments(loadSharedMoments(props.projectId, previous) ?? [], totalMs, projectFps, MOMENTS_MAX.frames);
+ setMoments(list);
+ saveMoments(props.projectId, 'frames', list);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open, props.projectId, totalMs > 0]);
+ const pickMoments = (list: number[]) => {
+ setMoments(list);
+ saveMoments(props.projectId, 'frames', list);
+ };
+
const patch = <K extends keyof Settings>(key: K, value: Partial<Settings[K]> | Settings[K]) => {
- setS((prev) => ({
+ setS((prev) => key === 'video' ? { ...prev, video: patchVideoExport(prev.video, value as Partial<VideoExportSettings>) } : ({
...prev,
[key]: typeof value === 'object' && !Array.isArray(value) && value !== null
? { ...(prev[key] as object), ...(value as object) }
@@ -373,9 +374,14 @@ export function ExportCenter(props: ExportCenterProps) {
};
const dest: Dest = DESTS.some((d) => d.id === s.dest) ? s.dest : 'video';
+ const imageDocument = s.images.as === 'pdf' || s.images.as === 'pptx';
const alphaBlock = blocks.find((b) => b.clipId === s.alpha.source);
+ const canRange = totalMs > 0 && (dest === 'video' || dest === 'gif' || dest === 'audio' || dest === 'subtitles' || (dest === 'alpha' && !alphaBlock));
+ const rangeInvalid = canRange && range && !parsedRanges;
+ const rangeError = rangeParts.length ? t('exportCenter.rangeInvalid').replace('{end}', String(totalMs / 1000)) : t('exportCenter.rangePickOne');
/* how long what comes out is: one element alone is its own length, not the film's */
const outMs = dest === 'alpha' && alphaBlock ? alphaBlock.durMs : rangeMs;
+ const selectedVideoPreset = exportPreset(s.video.preset);
const videoCodec: ExportVideoCodec = codecAvailable(s.video.codec, can) && VIDEO_CODECS.includes(s.video.codec) ? s.video.codec : 'h264';
const alphaCodec: ExportVideoCodec = EXPORT_ALPHA_CODECS.includes(s.alpha.codec) && codecAvailable(s.alpha.codec, can) ? s.alpha.codec : 'prores4444';
const audioFormat = s.audio.format === 'mp3' && can && !can.mp3 ? 'wav' : s.audio.format;
@@ -403,36 +409,30 @@ export function ExportCenter(props: ExportCenterProps) {
);
/* ── the exports this screen asks for ── */
- const requests = React.useMemo((): ExportRequest[] => {
- const ranged = rangeSec ? { range: rangeSec } : {};
+ const baseRequests = React.useMemo((): ExportRequest[] => {
/* subtitles drawn into the picture: only a film that has some */
const burn = (on: boolean) => (captions > 0 && on ? { burnSubtitles: true } : {});
switch (dest) {
- case 'social':
- return s.presets.map((id) => presets.find((p) => p.id === id) ?? null).filter((p) => p !== null).map((p) => ({
- kind: 'video', codec: 'h264', frame: p.frame, fill: 'contain', shortEdge: p.shortEdge, fps: presetFps(p, projectFps),
- quality: s.socialQuality, audio: true, preset: p.name, label: p.name,
- ...burn(s.socialSubs === 'auto' ? p.burnSubtitles : s.socialSubs === 'on'), ...ranged,
- }));
case 'video': {
const v = s.video;
return [{
kind: 'video', codec: videoCodec, frame: resolveFrame(v.frame), fill: v.fill, shortEdge: v.shortEdge, fps: fpsFor(v.fps),
- quality: v.quality, audio: v.audio, label: codecName(videoCodec), ...burn(v.burn),
- ...(captions > 0 && v.sidecar !== 'none' && videoCodec !== 'png' ? { sidecar: v.sidecar } : {}), ...ranged,
+ quality: v.quality, audio: v.audio, label: selectedVideoPreset?.name ?? codecName(videoCodec), ...burn(v.burn),
+ ...(selectedVideoPreset ? { preset: selectedVideoPreset.name } : {}),
+ ...(captions > 0 && v.sidecar !== 'none' && videoCodec !== 'png' ? { sidecar: v.sidecar } : {}),
}];
}
case 'alpha': {
const a = s.alpha;
return alphaBlock
? [{ kind: 'video', codec: alphaCodec, clip: alphaBlock.clipId, scale: a.scale, fps: a.fps, quality: 'high', audio: a.audio, label: alphaBlock.label }]
- : [{ kind: 'video', codec: alphaCodec, frame: 'native', shortEdge: a.shortEdge, fps: a.fps, quality: 'high', audio: a.audio, label: codecName(alphaCodec), ...ranged }];
+ : [{ kind: 'video', codec: alphaCodec, frame: 'native', shortEdge: a.shortEdge, fps: a.fps, quality: 'high', audio: a.audio, label: codecName(alphaCodec) }];
}
case 'gif':
- return [{ kind: 'gif', frame: resolveFrame(s.gif.frame), fill: s.gif.fill, width: s.gif.width, fps: s.gif.fps, label: 'GIF', ...burn(s.gif.burn), ...ranged }];
+ return [{ kind: 'gif', frame: resolveFrame(s.gif.frame), fill: s.gif.fill, width: s.gif.width, fps: s.gif.fps, label: 'GIF', ...burn(s.gif.burn) }];
case 'audio': {
const stems = s.audio.stems;
- return [{ kind: 'audio', format: audioFormat, stems, mix: stems ? s.audio.mix : true, label: t(stems ? 'exportCenter.audioStems' : 'exportCenter.audioMix'), ...ranged }];
+ return [{ kind: 'audio', format: audioFormat, stems, mix: stems ? s.audio.mix : true, label: t(stems ? 'exportCenter.audioStems' : 'exportCenter.audioMix') }];
}
case 'nle':
return [{
@@ -440,17 +440,15 @@ export function ExportCenter(props: ExportCenterProps) {
subtitles: s.nle.subtitles, label: nleApp === 'draft' ? tApp('exportCenter.nleDraftTitle') : `${NLE_APPS[nleApp].name} XML`,
}];
case 'subtitles':
- return [{ kind: 'subtitles', format: s.subtitles.format, label: s.subtitles.format === 'txt' ? t('exportCenter.transcript') : s.subtitles.format.toUpperCase(), ...ranged }];
- case 'images':
- return [{
- kind: 'stills', format: s.images.format, shortEdge: s.images.shortEdge, frame: resolveFrame(s.images.frame), fill: s.images.fill,
- label: t('exportCenter.stills'), ...burn(s.images.burn),
- }];
- case 'slides':
- return [{
- kind: 'slides', format: s.slides.format, shortEdge: s.slides.shortEdge, frame: resolveFrame(s.slides.frame), fill: s.slides.fill,
- label: s.slides.format === 'pdf' ? 'PDF' : 'PowerPoint', ...burn(s.slides.burn),
- }];
+ return [{ kind: 'subtitles', format: s.subtitles.format, label: s.subtitles.format === 'txt' ? t('exportCenter.transcript') : s.subtitles.format.toUpperCase() }];
+ case 'images': {
+ const at = momentSeconds(moments);
+ if (!at.length) return [];
+ const framing = { shortEdge: s.images.shortEdge, frame: resolveFrame(s.images.frame), fill: s.images.fill, at, ...burn(s.images.burn) };
+ return s.images.as === 'pdf' || s.images.as === 'pptx'
+ ? [{ kind: 'slides', format: s.images.as, ...framing, label: s.images.as.toUpperCase() }]
+ : [{ kind: 'stills', as: s.images.as, format: s.images.format, ...framing, label: t('exportCenter.summaryImages').replace('{n}', String(at.length)) }];
+ }
case 'project':
return [{
kind: 'project', as: s.project.as, parts: projectParts,
@@ -458,7 +456,11 @@ export function ExportCenter(props: ExportCenterProps) {
}];
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [dest, s, can, presets, nleApp, nleAlpha, draftApp, rangeSec?.[0], rangeSec?.[1], props.frame, blocks, nleSourceFps, captions, projectParts]);
+ }, [dest, s, can, nleApp, nleAlpha, draftApp, props.frame, blocks, nleSourceFps, captions, projectParts, moments]);
+
+ const requests = React.useMemo(() => canRange && range && parsedRanges
+ ? applyRangeDelivery(baseRequests, parsedRanges, rangeDelivery) : baseRequests,
+ [baseRequests, canRange, range, parsedRanges, rangeDelivery]);
/* a range, not a size: what is in the picture decides a video's or a GIF's size (export-spec.ts); sound is exact */
const estBytes = React.useMemo(() => requests.reduce<[number, number]>(([low, high], r) => {
@@ -469,20 +471,20 @@ export function ExportCenter(props: ExportCenterProps) {
const frame = r.frame ?? 'native', fill = r.fill ?? 'contain';
const size = exportFramedDims(stage, frame, fill, r.shortEdge ?? Math.min(stage.w, stage.h));
return add(exportEstimateBytes({
- codec: r.codec, size, filmPixels: exportFilmPixels(stage, frame, fill, size), fps: r.fps, quality: r.quality, durationMs: rangeMs,
+ codec: r.codec, size, filmPixels: exportFilmPixels(stage, frame, fill, size), fps: r.fps, quality: r.quality, durationMs: requestDurationMs(r, totalMs),
audio: r.audio && r.codec !== 'png' && !knownSilent,
}));
}
if (r.kind === 'gif') {
const frame = r.frame ?? 'native', fill = r.fill ?? 'contain';
const size = exportGifDims(filmFrameBox(stage, frame, fill), r.width);
- return add(exportGifEstimateBytes({ size, filmPixels: exportFilmPixels(stage, frame, fill, size), fps: r.fps, durationMs: rangeMs }));
+ return add(exportGifEstimateBytes({ size, filmPixels: exportFilmPixels(stage, frame, fill, size), fps: r.fps, durationMs: requestDurationMs(r, totalMs) }));
}
if (r.kind === 'audio') {
/* 48 kHz 16-bit stereo; AAC and MP3 at 256k (exports.mjs SOUND_CODECS) */
const per = r.format === 'wav' ? 192_000 : 32_000;
const files = (r.mix ? 1 : 0) + (r.stems ? soundKinds.size : 0);
- const bytes = per * (rangeMs / 1000) * Math.max(1, files);
+ const bytes = per * (requestDurationMs(r, totalMs) / 1000) * Math.max(1, files);
return add([bytes, bytes]);
}
if (r.kind === 'project' && projectSizes) {
@@ -490,13 +492,14 @@ export function ExportCenter(props: ExportCenterProps) {
return add([bytes, bytes]);
}
return [low, high];
- }, [0, 0]), [requests, stage, rangeMs, soundKinds, knownSilent, projectSizes]);
+ }, [0, 0]), [requests, stage, totalMs, soundKinds, knownSilent, projectSizes]);
/* "about 0.8 MB–8 MB"; one size when both ends read the same */
const estText = estBytes[1] > 0 ? [...new Set(estBytes.map((b) => formatBytes(b)))].join('–') : '';
const folder = s.folder || defaultFolder;
const fileCount = requests.reduce((n, r) => {
+ if (r.kind === 'stills' && r.as === 'files') return n + (r.at?.length ?? 1);
if (r.kind === 'audio') return n + (r.mix ? 1 : 0) + (r.stems ? Math.max(1, soundKinds.size) : 0);
if (r.kind === 'video' && r.sidecar) return n + 2;
return n + 1;
@@ -511,7 +514,9 @@ export function ExportCenter(props: ExportCenterProps) {
const emptyReason = ((): string | null => {
if (missingReason) return missingReason;
if (!totalMs && dest !== 'project') return t('exportCenter.emptyFilm');
- if (dest === 'social' && requests.length === 0) return t('exportCenter.pickPreset');
+ if (rangeInvalid) return rangeError;
+ if (dest === 'images' && moments.length === 0) return t('exportCenter.pickMoments');
+ if (dest === 'images' && imageDocument && moments.length > MOMENTS_MAX.slides) return t('exportCenter.imagePageLimit').replace('{n}', String(MOMENTS_MAX.slides));
if (dest === 'subtitles' && captionCount != null && captions === 0) return t('exportCenter.noCaptions');
if (dest === 'audio' && knownSilent) return t('exportCenter.noAudio');
return null;
@@ -519,7 +524,7 @@ export function ExportCenter(props: ExportCenterProps) {
/* ── doing it ── */
const queue = async (jobs: ExportRequest[]) => {
- if (working) return;
+ if (working || rangeInvalid) return;
setResult(null);
if (!folder) {
setResult({ ok: false, text: t('exportCenter.noFolder') });
@@ -530,7 +535,7 @@ export function ExportCenter(props: ExportCenterProps) {
/* the name typed here, unless there is none or its field is hidden (a draft is named by its app): every way out
of this screen comes through here */
const typed = nameTyped && !toDrafts ? exportName.trim() : '';
- const named = typed ? jobs.map((job) => ({ ...job, name: typed })) : jobs;
+ const named = typed ? jobs.map((job, index) => ({ ...job, name: typed + (canRange && range && rangeDelivery === 'separate' && (parsedRanges?.length ?? 0) > 1 ? ` - ${String(index + 1).padStart(2, '0')}` : '') })) : jobs;
const queued = await startExports(props.projectId, named, s.folder || undefined);
props.onQueued?.(queued);
onClose();
@@ -541,16 +546,6 @@ export function ExportCenter(props: ExportCenterProps) {
}
};
- /* the poster is the frame at the playhead; at the very start (often a fade from black) the film's middle */
- const posterAt = props.playheadMs != null && props.playheadMs > 0 && props.playheadMs < totalMs ? props.playheadMs / 1000 : undefined;
- const exportPoster = () => {
- const at = posterAt;
- void queue([{
- kind: 'poster', format: s.images.format, shortEdge: s.images.shortEdge, frame: resolveFrame(s.images.frame), fill: s.images.fill,
- label: t('exportCenter.poster'), ...(at != null ? { at } : {}), ...(captions > 0 && s.images.burn ? { burnSubtitles: true } : {}),
- }]);
- };
-
const commitFolder = () => {
if (folderDraft == null) return;
const next = folderDraft.trim();
@@ -586,14 +581,14 @@ export function ExportCenter(props: ExportCenterProps) {
<div
/* a plain dim, no backdrop blur: a blur over the whole window is drawn again on every frame of a wheel scroll in
the dialog, and the window flickered on macOS */
- className="fixed inset-0 z-[130] flex items-center justify-center bg-black/50 p-4"
+ className={LARGE_DIALOG_BACKDROP}
onClick={() => { if (!working) onClose(); }}
>
<div
role="dialog"
aria-modal="true"
aria-label={t('exportCenter.title')}
- className="flex h-[min(640px,calc(100vh-32px))] w-full max-w-[880px] overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--surface)] shadow-[var(--shadow-lg)]"
+ className={LARGE_DIALOG}
style={{ animation: 'openfilm-rise 0.16s ease-out both' }}
onClick={(e) => e.stopPropagation()}
>
@@ -650,68 +645,33 @@ export function ExportCenter(props: ExportCenterProps) {
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pb-4 pt-3">
<div className="flex flex-col gap-5">
- {dest === 'social' && (
+ {dest === 'video' && (
<>
- {PRESET_GROUPS.map((group) => (
- <Field key={group} label={t(`exportCenter.group.${group}`)}>
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
- {presets.filter((p) => p.group === group).map((p) => {
- const on = s.presets.includes(p.id);
- const dims = exportDimsForShortEdge(filmFrameBox(stage, p.frame), p.shortEdge);
- const tooLong = p.maxDurationSec != null && rangeMs / 1000 > p.maxDurationSec;
- return (
- <button
- key={p.id}
- type="button"
- aria-pressed={on}
- onClick={() => patch('presets', on ? s.presets.filter((id) => id !== p.id) : [...s.presets, p.id])}
- className={`relative flex flex-col items-start gap-0.5 rounded-xl border px-3 py-2.5 text-left transition ${
- on ? 'border-[var(--text)] bg-[var(--bg-hover)]' : 'border-[var(--border)] hover:border-[var(--text-faint)]'
- }`}
- >
- <span className="flex w-full items-center gap-1.5">
- <AspectGlyph frame={p.frame} stage={stage} />
- <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-[var(--text)]">{p.name}</span>
- {on && <Check size={13} className="shrink-0 text-[var(--text)]" />}
- </span>
- <span className="text-[11px] tabular-nums text-[var(--text-faint)]">
- {dims.w}×{dims.h} · {presetFps(p, projectFps)}fps
- </span>
- {tooLong && (
- <span className="text-[10.5px] leading-snug text-[var(--warn)]">
- {t('exportCenter.tooLong').replace('{max}', formatFilmTime(p.maxDurationSec! * 1000))}
- </span>
- )}
- </button>
- );
- })}
- </div>
- </Field>
- ))}
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
- <Field label={t('exportCenter.quality')}>
- <QualityPicker value={s.socialQuality} onChange={(q) => patch('socialQuality', q)} t={t} />
- </Field>
- {captions > 0 && (
- <Field label={t('exportCenter.burnSubtitles')}>
- <Segmented
- value={s.socialSubs}
- options={[
- { value: 'auto', label: t('exportCenter.subsAuto') },
- { value: 'on', label: t('exportCenter.subsOn') },
- { value: 'off', label: t('exportCenter.subsOff') },
+ <Field label={t('exportCenter.videoPreset')}>
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <div className="inline-flex w-fit min-w-[128px] max-w-full">
+ <MenuSelect
+ className="max-w-[280px]"
+ menuWidth="content"
+ label={t('exportCenter.videoPreset')}
+ value={s.video.preset}
+ size="md"
+ groups={[
+ { choices: [{ value: 'default', label: t('exportCenter.presetDefault') }] },
+ { label: t('exportCenter.platformPresets'), choices: presets.map((p) => ({ value: p.id, label: `${p.name} · ${p.frame}` })) },
+ ...(s.video.preset === 'custom' ? [{ choices: [{ value: 'custom', label: t('exportCenter.presetCustom') }] }] : []),
]}
- onChange={(v) => patch('socialSubs', v)}
+ onPick={(id) => { if (id !== 'custom') patch('video', videoExportPreset(id, projectFps)); }}
/>
- </Field>
- )}
- </div>
- <Hint>{t('exportCenter.socialHint')}</Hint>
- </>
- )}
-
- {dest === 'video' && (
- <>
+ </div>
+ <span className="text-[11px] leading-relaxed text-[var(--text-muted)]">
+ {s.video.preset === 'custom' ? t('exportCenter.presetCustomHint') : selectedVideoPreset
+ ? `${selectedVideoPreset.frame} · ${s.video.shortEdge === 2160 ? '4K' : `${s.video.shortEdge}p`} · ${fpsFor(s.video.fps)} fps`
+ : t('exportCenter.presetDefaultHint')}
+ </span>
+ </div>
+ {selectedVideoPreset?.maxDurationSec != null && rangeMs / 1000 > selectedVideoPreset.maxDurationSec ? <p className="mt-2 text-[11px] text-[var(--warn)]">{t('exportCenter.tooLong').replace('{max}', formatFilmTime(selectedVideoPreset.maxDurationSec * 1000))}</p> : null}
+ </Field>
<Field label={t('exportCenter.codec')}>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
{VIDEO_CODECS.map((c) => {
@@ -748,7 +708,7 @@ export function ExportCenter(props: ExportCenterProps) {
onChange={(shortEdge) => patch('video', { shortEdge })}
/>
</Field>
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
+ <div className="flex flex-wrap items-start gap-x-8 gap-y-4">
<Field label={t('exportCenter.fps')}>
<FpsSelect
label={t('exportCenter.fps')}
@@ -1048,118 +1008,94 @@ export function ExportCenter(props: ExportCenterProps) {
</>
)}
+ {/* One set of frames, delivered as picture files, a zip, PDF or PPTX. */}
{dest === 'images' && (
- <>
- <Field label={t('exportCenter.poster')}>
- <button
- type="button"
- onClick={exportPoster}
- disabled={Boolean(working) || !totalMs || !folder}
- className="inline-flex h-9 items-center gap-2 self-start rounded-lg border border-[var(--border)] px-3 text-[12.5px] font-medium text-[var(--text)] transition hover:bg-[var(--bg-hover)] disabled:cursor-not-allowed disabled:opacity-40"
- >
- <Download size={14} />
- {posterAt != null ? t('exportCenter.posterAt').replace('{time}', formatFilmTime(posterAt * 1000)) : t('exportCenter.posterMiddle')}
- </button>
- </Field>
- <Field label={t('exportCenter.sceneStills')}>
- <p className="-mt-1 mb-1 text-[12px] text-[var(--text-muted)]">
- {t('exportCenter.sceneStillsDesc').replace('{n}', String(stillCount))}
- </p>
- <Segmented
- value={s.images.format}
- options={[{ value: 'png', label: 'PNG' }, { value: 'jpg', label: 'JPG' }]}
- onChange={(format) => patch('images', { format })}
- />
- </Field>
- <FrameField
- value={s.images.frame}
- fill={s.images.fill}
- current={props.frame}
+ <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_272px]">
+ <MomentPicker
+ projectId={props.projectId}
+ totalMs={totalMs}
+ fps={projectFps}
stage={stage}
- onChange={(frame) => patch('images', { frame })}
- onFill={(fill) => patch('images', { fill })}
- t={t}
+ frame={resolveFrame(s.images.frame)}
+ fill={s.images.fill}
+ scenes={film?.scenes ?? []}
+ markersMs={props.markersMs ?? []}
+ playheadMs={props.playheadMs}
+ value={moments}
+ onChange={pickMoments}
+ max={imageDocument ? MOMENTS_MAX.slides : MOMENTS_MAX.frames}
+ note={captions > 0 && s.images.burn ? t('exportCenter.moments.noSubtitles') : undefined}
/>
- <Field label={t('exportCenter.resolution')}>
- <Chips
- value={s.images.shortEdge}
- options={STILL_EDGES.map((p) => ({ value: p, label: p === 2160 ? '4K' : `${p}p` }))}
- onChange={(shortEdge) => patch('images', { shortEdge })}
- />
- </Field>
- {captions > 0 && (
- <Toggle checked={s.images.burn} onChange={(burn) => patch('images', { burn })} label={t('exportCenter.burnIn')} />
- )}
- </>
- )}
-
- {dest === 'slides' && (
- <>
- <Field label={t('exportCenter.format')}>
- <div className="grid grid-cols-2 gap-2">
- {(['pptx', 'pdf'] as const).map((f) => (
- <OptionCard
- key={f}
- on={s.slides.format === f}
- title={f === 'pptx' ? 'PowerPoint' : 'PDF'}
- desc={t(`exportCenter.slidesHint.${f}`)}
- onClick={() => patch('slides', { format: f })}
+ <div className="flex min-w-0 flex-col gap-5">
+ <Field label={t('exportCenter.imageOutput')}>
+ <div className="grid grid-cols-2 gap-2">
+ {IMAGE_OUTPUTS.map((output) => (
+ <OptionCard
+ key={output}
+ on={s.images.as === output}
+ title={output === 'files' ? t('exportCenter.imageFiles') : output.toUpperCase()}
+ desc={t(output === 'files' ? 'exportCenter.imageFilesHint' : output === 'zip' ? 'exportCenter.imageZipHint' : `exportCenter.slidesHint.${output}`)}
+ onClick={() => patch('images', { as: output })}
+ />
+ ))}
+ </div>
+ </Field>
+ {!imageDocument && (
+ <Field label={t('exportCenter.imageFormat')}>
+ <Segmented
+ value={s.images.format}
+ options={[{ value: 'png', label: 'PNG' }, { value: 'jpg', label: 'JPG' }]}
+ onChange={(format) => patch('images', { format })}
/>
- ))}
- </div>
- </Field>
- <FrameField
- value={s.slides.frame}
- fill={s.slides.fill}
- current={props.frame}
- stage={stage}
- onChange={(frame) => patch('slides', { frame })}
- onFill={(fill) => patch('slides', { fill })}
- t={t}
- />
- {captions > 0 && (
- <Toggle checked={s.slides.burn} onChange={(burn) => patch('slides', { burn })} label={t('exportCenter.burnIn')} />
- )}
- </>
+ </Field>
+ )}
+ <FrameField
+ value={s.images.frame}
+ fill={s.images.fill}
+ current={props.frame}
+ stage={stage}
+ onChange={(frame) => patch('images', { frame })}
+ onFill={(fill) => patch('images', { fill })}
+ t={t}
+ />
+ <Field label={t('exportCenter.resolution')}>
+ <Chips
+ value={s.images.shortEdge}
+ options={STILL_EDGES.map((p) => ({ value: p, label: p === 2160 ? '4K' : `${p}p` }))}
+ onChange={(shortEdge) => patch('images', { shortEdge })}
+ />
+ </Field>
+ {captions > 0 && (
+ <Toggle checked={s.images.burn} onChange={(burn) => patch('images', { burn })} label={t('exportCenter.burnIn')} />
+ )}
+ </div>
+ </div>
)}
{/* range: any destination with a picture or a sound over time can take a part */}
- {(dest === 'social' || dest === 'video' || dest === 'gif' || dest === 'audio' || dest === 'subtitles' || (dest === 'alpha' && !alphaBlock)) && totalMs > 0 && (
+ {canRange && (
<Field label={t('exportCenter.range')}>
<Segmented
- value={range.on ? 'part' : 'all'}
+ value={range ? 'part' : 'all'}
options={[
{ value: 'all', label: `${t('exportCenter.rangeAll')} · ${formatFilmTime(totalMs)}` },
{ value: 'part', label: t('exportCenter.rangePart') },
]}
- onChange={(v) => setRange((r) => ({ ...r, on: v === 'part' }))}
+ onChange={(v) => setRange(v === 'part')}
/>
- {range.on && (
- <div className="mt-2 flex flex-wrap items-center gap-2 text-[12px] text-[var(--text-muted)]">
- <div className="flex w-[220px] min-w-0">
- <MenuSelect
- label={t('exportCenter.rangeFrom')}
- size="md"
- value={String(range.from)}
- groups={[{ choices: boundaries.starts.map((m) => ({ value: String(m.ms), label: [formatFilmTime(m.ms), m.title].filter(Boolean).join(' · ') })) }]}
- onPick={(v) => {
- const from = Number(v);
- setRange((r) => ({ ...r, from, to: r.to > from ? r.to : (boundaries.ends.find((m) => m.ms > from)?.ms ?? totalMs) }));
- }}
- />
- </div>
- <span>→</span>
- <div className="flex w-[220px] min-w-0">
- <MenuSelect
- label={t('exportCenter.rangeTo')}
- size="md"
- value={String(range.to)}
- groups={[{ choices: boundaries.ends.filter((m) => m.ms > range.from).map((m) => ({ value: String(m.ms), label: [formatFilmTime(m.ms), m.title].filter(Boolean).join(' · ') })) }]}
- onPick={(v) => setRange((r) => ({ ...r, to: Number(v) }))}
- />
- </div>
- <span className="tabular-nums">{formatFilmTime(rangeMs)}</span>
- </div>
+ {range && (
+ <RangePicker
+ projectId={props.projectId}
+ totalMs={totalMs}
+ fps={projectFps}
+ stage={stage}
+ boundaries={boundaries}
+ value={rangeParts}
+ onChange={setRangeParts}
+ delivery={rangeDelivery}
+ onDelivery={setRangeDelivery}
+ error={rangeInvalid ? rangeError : null}
+ />
)}
</Field>
)}
@@ -1230,7 +1166,10 @@ export function ExportCenter(props: ExportCenterProps) {
) : (
<>
{/* a project is not a length of film: its size only */}
- {dest !== 'project' ? (
+ {/* pictures are counted, not timed */}
+ {dest === 'images' ? (
+ <span className="block text-[var(--text-muted)] tabular-nums">{momentsSummary(s.images.as, moments.length, t)}</span>
+ ) : dest !== 'project' ? (
<span className="block text-[var(--text-muted)] tabular-nums">
{t('exportCenter.summary').replace('{n}', String(fileCount)).replace('{dur}', formatFilmTime(outMs))}
</span>
@@ -1259,6 +1198,12 @@ export function ExportCenter(props: ExportCenterProps) {
/* ── small parts ────────────────────────────────────────────────────────── */
+/** What the picked moments come out as: one picture, pictures in a zip, or pages. */
+function momentsSummary(output: ImageOutput, n: number, t: (k: string) => string): string {
+ if (output === 'pdf' || output === 'pptx') return `${output.toUpperCase()} · ${t(n === 1 ? 'exportCenter.summarySlide' : 'exportCenter.summarySlides').replace('{n}', String(n))}`;
+ return t(output === 'zip' ? 'exportCenter.summaryImagesZip' : n === 1 ? 'exportCenter.summaryImage' : 'exportCenter.summaryImages').replace('{n}', String(n));
+}
+
/** A folder's own name, the last part of its path (the whole path is the button's tooltip). */
function folderName(path: string): string {
return path.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || path;
@@ -1319,13 +1264,16 @@ function FpsSelect({ label, value, rates, own, onPick }: {
const all = [...new Set([...rates, ...(own ? [own.fps] : [])])].sort((a, b) => a - b);
const name = (f: number) => `${f} fps${own && f === own.fps ? ` · ${own.note}` : ''}`;
return (
- <MenuSelect
- size="md"
- label={label}
- value={String(value)}
- groups={[{ choices: all.map((f) => ({ value: String(f), label: name(f) })) }]}
- onPick={(v) => onPick(Number(v))}
- />
+ <div className="inline-flex w-fit min-w-[132px] max-w-full">
+ <MenuSelect
+ size="md"
+ className="max-w-[180px]"
+ label={label}
+ value={String(value)}
+ groups={[{ choices: all.map((f) => ({ value: String(f), label: name(f) })) }]}
+ onPick={(v) => onPick(Number(v))}
+ />
+ </div>
);
}
diff --git a/packages/openfilm/studio/ui/src/components/export/ExportTimeInput.tsx b/packages/openfilm/studio/ui/src/components/export/ExportTimeInput.tsx
new file mode 100644
index 0000000..a4a85db
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/export/ExportTimeInput.tsx
@@ -0,0 +1,76 @@
+import React from 'react';
+import { ChevronDown } from 'lucide-react';
+import { ContextMenu } from '@/components/ContextMenu';
+import { formatTimecode } from '@/lib/timecode';
+import { parseExportTime } from '@/lib/export-range';
+
+/** A typed position with the existing clip boundaries available from its arrow. */
+export function ExportTimeInput({ label, boundaryLabel, value, fps, marks, invalid, onChange, compact = false }: {
+ label: string;
+ boundaryLabel: string;
+ value: string;
+ fps: number;
+ marks: readonly { ms: number; title: string }[];
+ invalid: boolean;
+ onChange: (value: string) => void;
+ compact?: boolean;
+}) {
+ const [menu, setMenu] = React.useState<{ x: number; y: number; top: number } | null>(null);
+ const trigger = React.useRef<HTMLButtonElement | null>(null);
+ const inputId = React.useId();
+ const current = parseExportTime(value, fps);
+ return (
+ <div className={`flex max-w-full flex-col gap-1.5 ${compact ? 'w-full' : 'w-[220px]'}`}>
+ <div className="flex flex-col gap-1.5">
+ <label htmlFor={inputId} className="text-[11.5px] text-[var(--text-faint)]">{label}</label>
+ <span className={`flex h-9 items-center overflow-hidden rounded-lg border bg-[var(--fill-tsp)] focus-within:border-[var(--accent)] ${invalid ? 'border-[var(--warn)]' : 'border-[var(--border)]'}`}>
+ <input
+ id={inputId}
+ type="text"
+ aria-label={label}
+ aria-invalid={invalid}
+ value={value}
+ placeholder="00:00.000"
+ spellCheck={false}
+ onChange={(e) => onChange(e.target.value)}
+ onFocus={(e) => e.currentTarget.select()}
+ onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); }}
+ className="h-full min-w-0 flex-1 bg-transparent pl-3 font-mono text-[13px] tabular-nums text-[var(--text)] outline-none"
+ />
+ <button
+ ref={trigger}
+ type="button"
+ aria-label={`${label} · ${boundaryLabel}`}
+ title={boundaryLabel}
+ aria-haspopup="menu"
+ aria-expanded={Boolean(menu)}
+ onClick={(e) => {
+ if (menu) { setMenu(null); return; }
+ const rect = e.currentTarget.getBoundingClientRect();
+ setMenu({ x: rect.right, y: rect.bottom + 4, top: rect.top - 4 });
+ }}
+ className="flex h-full w-8 shrink-0 items-center justify-center text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
+ >
+ <ChevronDown size={13} />
+ </button>
+ </span>
+ </div>
+ {menu && <ContextMenu
+ x={menu.x}
+ y={menu.y}
+ flipTo={menu.top}
+ align="end"
+ dense
+ trigger={trigger}
+ items={marks.map((mark) => ({
+ id: String(mark.ms),
+ label: [formatTimecode(mark.ms, { fps }), mark.title].filter(Boolean).join(' · '),
+ checked: current != null && Math.abs(current - mark.ms) < 0.001,
+ onSelect: () => onChange(String(mark.ms / 1000)),
+ }))}
+ onClose={() => setMenu(null)}
+ />}
+ </div>
+ );
+}
+
diff --git a/packages/openfilm/studio/ui/src/components/export/MomentPicker.tsx b/packages/openfilm/studio/ui/src/components/export/MomentPicker.tsx
new file mode 100644
index 0000000..ab6ab37
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/export/MomentPicker.tsx
@@ -0,0 +1,640 @@
+/**
+ * Picking the moments an image or slides export takes (lib/export-moments): the film drawn large at one moment, a strip
+ * of the film to find it on, and the frames picked so far, each drawn as it will come out (the frame and fill chosen
+ * beside it).
+ *
+ * The strip zooms and scrolls as the timeline does (Ctrl/⌘ + wheel or a pinch around the pointer, a sideways swipe or
+ * Shift + wheel to scroll, the zoom bar under it), down to a second across. Pointer gestures only find a moment;
+ * adding one requires the Add frame button or Enter. The frames picked are not all marked on it: the one selected below shows its dot there, to be dragged.
+ *
+ * Every picture is the server's (pageframes.mjs), the film drawn as an export draws it, so what is seen here is what is
+ * exported, burned subtitles aside. The server draws one frame at a time, a second or more each for a film with
+ * footage, so the pictures are asked for one at a time here too, the large one first (the latest moment only: scrubbing
+ * never queues every frame passed over), then the strip in sight, nearest the moment shown first, then the frames
+ * picked. All are drawn at one width, so a frame picked from the large picture is not drawn again.
+ */
+import { Check, Loader2, MoveHorizontal, Plus, X, ZoomIn, ZoomOut } from 'lucide-react';
+import React from 'react';
+
+import { useT } from '@/i18n';
+import { ContextMenu, type ContextMenuEntry } from '@/components/ContextMenu';
+import {
+ STRIP_WHOLE, clampView, cleanMoments, everyCount, everyMoments, filmFrameUrl, momentAt, sameFrame, sceneMiddles, stepFor, stripZoomMax,
+ viewShowing, zoomView, type StripView,
+} from '@/lib/export-moments';
+import { filmFrameBox, type FilmFrameBox, type FilmFrameFill, type FilmFrameId } from '@/lib/film-frame';
+import { formatRulerLabel, formatTimecode, stepFrames } from '@/lib/timecode';
+
+/** How wide every picture is drawn: the large one's width, the others shown smaller. */
+const FRAME_W = 960;
+const STRIP_H = 56;
+/** How long a cell of the strip may be (ms): the shortest at least a cell's width across. */
+const CELL_STEPS = [100, 200, 500, 1000, 2000, 5000, 10_000, 15_000, 30_000, 60_000, 120_000, 300_000, 600_000, 1_800_000];
+/** How far apart the ruler's labels may be (ms): the closest at least TICK_PX apart. */
+const TICK_STEPS = [100, 200, 500, 1000, 2000, 5000, 10_000, 15_000, 30_000, 60_000, 120_000, 300_000, 600_000, 1_800_000, 3_600_000];
+const TICK_PX = 72;
+/** The intervals "every few seconds" offers. */
+const EVERY_SECONDS = [1, 2, 3, 5, 10, 15, 30, 60];
+
+export interface MomentPickerProps {
+ projectId: string;
+ totalMs: number;
+ fps: number;
+ stage: { w: number; h: number };
+ frame: FilmFrameId;
+ fill: FilmFrameFill;
+ /** The picture clips, for "the middle of each scene". */
+ scenes: readonly { startMs: number; durMs: number }[];
+ /** The markers on the film (ms). */
+ markersMs: readonly number[];
+ playheadMs?: number | undefined;
+ value: readonly number[];
+ onChange: (list: number[]) => void;
+ max: number;
+ /** A line under the strip (what the pictures leave out). */
+ note?: string | undefined;
+}
+
+export function MomentPicker(props: MomentPickerProps) {
+ const { projectId, totalMs, fps, value, onChange, max } = props;
+ const t = useT();
+ const box = React.useMemo(() => filmFrameBox(props.stage, props.frame, props.fill), [props.stage, props.frame, props.fill]);
+ const playhead = props.playheadMs != null && props.playheadMs > 0 && props.playheadMs < totalMs ? momentAt(props.playheadMs, totalMs, fps) : null;
+ const [cursor, setCursor] = React.useState(() => value[0] ?? playhead ?? momentAt(totalMs / 2, totalMs, fps));
+ /** the frame picked that is selected (its dot shows on the strip), if it is still picked */
+ const [selectedMs, setSelected] = React.useState<number | null>(null);
+ const selected = selectedMs != null && value.some((m) => sameFrame(m, selectedMs, fps)) ? selectedMs : null;
+ const rootRef = React.useRef<HTMLDivElement | null>(null);
+ const picked = value.some((m) => sameFrame(m, cursor, fps));
+ const full = value.length >= max;
+
+ /* what the strip shows, and how wide it is */
+ const stripRef = React.useRef<HTMLDivElement | null>(null);
+ const [stripW, setStripW] = React.useState(0);
+ React.useLayoutEffect(() => {
+ const el = stripRef.current;
+ if (!el) return undefined;
+ const ro = new ResizeObserver(() => setStripW(el.clientWidth));
+ ro.observe(el);
+ setStripW(el.clientWidth);
+ return () => ro.disconnect();
+ }, []);
+ const [view, setViewRaw] = React.useState<StripView>(STRIP_WHOLE);
+ const setView = React.useCallback((v: StripView) => setViewRaw(clampView(v, totalMs)), [totalMs]);
+ const span = totalMs / view.zoom;
+ const msPerPx = stripW > 0 ? span / stripW : 1;
+
+ /* the cells in sight: a cell is a step of the film long, at least a picture's width across */
+ const cellStep = stepFor(msPerPx, STRIP_H * (props.stage.w / Math.max(1, props.stage.h)), CELL_STEPS);
+ const cells = React.useMemo(() => {
+ if (!(stripW > 0)) return [];
+ const out: { at: number; ms: number }[] = [];
+ for (let k = Math.floor(view.start / cellStep); k * cellStep < Math.min(totalMs, view.start + span); k++) {
+ out.push({ at: k * cellStep, ms: momentAt(k * cellStep + cellStep / 2, totalMs, fps) });
+ }
+ return out;
+ }, [stripW, view.start, span, cellStep, totalMs, fps]);
+
+ const url = (ms: number) => filmFrameUrl(projectId, ms, FRAME_W);
+ const frames = useFrames([
+ url(cursor),
+ ...[...cells].sort((a, b) => Math.abs(a.ms - cursor) - Math.abs(b.ms - cursor)).map((c) => url(c.ms)),
+ ...value.map(url),
+ ]);
+
+ /** the moment shown, the strip scrolled to it when it is out of sight */
+ const goTo = (ms: number) => {
+ setCursor(ms);
+ setView(viewShowing(view, ms, totalMs));
+ };
+ const set = (list: number[]) => {
+ onChange(list);
+ setSelected(null);
+ if (list.length && !list.some((m) => sameFrame(m, cursor, fps))) goTo(list[0]!);
+ };
+ /** Confirmation is idempotent: adding an already-picked frame never removes it. */
+ const add = (ms: number) => {
+ const at = momentAt(ms, totalMs, fps);
+ if (value.some((m) => sameFrame(m, at, fps))) { setSelected(at); return; }
+ if (full) return;
+ onChange(cleanMoments([...value, at], totalMs, fps, max));
+ setSelected(at);
+ };
+ const remove = (ms: number) => {
+ onChange(value.filter((m) => !sameFrame(m, ms, fps)));
+ if (selected != null && sameFrame(selected, ms, fps)) setSelected(null);
+ };
+ const move = (from: number, to: number) => {
+ onChange(cleanMoments(value.map((m) => (sameFrame(m, from, fps) ? to : m)), totalMs, fps, max));
+ setSelected(to);
+ goTo(to);
+ };
+ const focus = () => rootRef.current?.focus({ preventScroll: true });
+
+ const onKey = (e: React.KeyboardEvent) => {
+ // Buttons and fields keep their own keyboard behavior; Enter confirms the strip's preview only.
+ if (e.defaultPrevented || e.nativeEvent.isComposing || (e.target as Element).closest('button,input,select,textarea,[contenteditable]')) return;
+ const step = (from: number, dir: 1 | -1) => (e.shiftKey ? momentAt(from + dir * 1000, totalMs, fps) : momentAt(stepFrames(from, dir, fps), totalMs, fps));
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
+ const dir = e.key === 'ArrowLeft' ? -1 : 1;
+ /* Alt moves the frame selected; the arrows alone, the moment shown */
+ if (e.altKey && selected != null) move(selected, step(selected, dir));
+ else { goTo(step(cursor, dir)); if (selected != null && !sameFrame(selected, cursor, fps)) setSelected(null); }
+ } else if (e.key === 'Enter') add(cursor);
+ else if (e.key === 'Delete' || e.key === 'Backspace') {
+ if (selected != null) remove(selected);
+ else if (picked) remove(cursor);
+ else return;
+ } else if (e.key === 'Home' || e.key === 'End') goTo(momentAt(e.key === 'Home' ? 0 : totalMs, totalMs, fps));
+ else return;
+ e.preventDefault();
+ e.stopPropagation();
+ };
+
+ /* "every few seconds": the intervals that give more than one frame and no more than the most */
+ const [everyMenu, setEveryMenu] = React.useState<{ x: number; y: number; top: number } | null>(null);
+ const everyRef = React.useRef<HTMLButtonElement | null>(null);
+ const everyItems: ContextMenuEntry[] = EVERY_SECONDS
+ .map((s) => ({ s, n: everyCount(s * 1000, totalMs) }))
+ .filter(({ n }) => n > 1 && n <= max)
+ .map(({ s, n }) => ({
+ id: String(s),
+ label: t('exportCenter.moments.everyN').replace('{s}', String(s)).replace('{n}', String(n)),
+ onSelect: () => set(everyMoments(s * 1000, totalMs, fps, max)),
+ }));
+ const markers = React.useMemo(() => cleanMoments(props.markersMs, totalMs, fps, max), [props.markersMs, totalMs, fps, max]);
+
+ const quick = 'h-7 rounded-full border border-[var(--border)] px-3 text-[12px] font-medium text-[var(--text-muted)] transition hover:border-[var(--text-faint)] hover:text-[var(--text)]';
+ return (
+ <div ref={rootRef} tabIndex={0} onKeyDown={onKey} className="flex min-w-0 flex-col gap-3 outline-none">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="mr-1 text-[11.5px] font-medium uppercase tracking-wide text-[var(--text-faint)]">{t('exportCenter.moments.quick')}</span>
+ {playhead != null && <button type="button" className={quick} onClick={() => set([playhead])}>{t('exportCenter.moments.playhead')}</button>}
+ <button type="button" className={quick} onClick={() => set(sceneMiddles(props.scenes, totalMs, fps, max))}>{t('exportCenter.moments.scenes')}</button>
+ {markers.length > 0 && <button type="button" className={quick} onClick={() => set(markers)}>{t('exportCenter.moments.markers')}</button>}
+ {everyItems.length > 0 && (
+ <button
+ ref={everyRef}
+ type="button"
+ className={quick}
+ onClick={(e) => {
+ if (everyMenu) { setEveryMenu(null); return; }
+ const r = e.currentTarget.getBoundingClientRect();
+ setEveryMenu({ x: r.left, y: r.bottom + 4, top: r.top - 4 });
+ }}
+ >
+ {t('exportCenter.moments.every')}
+ </button>
+ )}
+ </div>
+
+ <Preview frames={frames} url={url(cursor)} box={box} ms={cursor} fps={fps}>
+ <button
+ type="button"
+ onClick={() => add(cursor)}
+ disabled={picked || full}
+ className="flex h-8 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 text-[12.5px] font-medium text-[var(--text)] transition hover:bg-[var(--bg-hover)] disabled:opacity-50"
+ >
+ {picked ? <Check size={14} /> : <Plus size={14} />}
+ {t(picked ? 'exportCenter.moments.added' : 'exportCenter.moments.add')}
+ {!picked ? <kbd className="ml-1 font-sans text-[11px] text-[var(--text-faint)]">↵</kbd> : null}
+ </button>
+ </Preview>
+
+ <Strip
+ stripRef={stripRef}
+ stripW={stripW}
+ view={view}
+ setView={setView}
+ msPerPx={msPerPx}
+ cells={cells.map((c) => ({ ...c, src: frames.get(url(c.ms)) }))}
+ cellStep={cellStep}
+ totalMs={totalMs}
+ fps={fps}
+ cursor={cursor}
+ selected={selected}
+ markers={markers}
+ onCursor={(ms) => { setCursor(ms); if (selected != null && !sameFrame(selected, ms, fps)) setSelected(null); focus(); }}
+ onDragSelected={(ms) => setCursor(ms)}
+ onMoveSelected={(to) => { if (selected != null) move(selected, to); focus(); }}
+ label={t('exportCenter.moments.strip')}
+ />
+ <div className="-mt-1 flex flex-wrap items-start justify-between gap-x-4 gap-y-2">
+ <p className="min-w-0 flex-1 basis-[260px] text-[11.5px] leading-relaxed text-[var(--text-faint)]">
+ {t('exportCenter.moments.hint')}
+ {props.note ? <span className="block">{props.note}</span> : null}
+ </p>
+ {stripZoomMax(totalMs) > 1 && (
+ <ZoomControls view={view} totalMs={totalMs} setView={setView} anchor={cursor >= view.start && cursor <= view.start + span ? (cursor - view.start) / span : 0.5} t={t} />
+ )}
+ </div>
+
+ <div className="flex items-center justify-between gap-3 pt-1">
+ <span className="text-[11.5px] font-medium uppercase tracking-wide text-[var(--text-faint)]">
+ {t('exportCenter.moments.picked').replace('{n}', String(value.length))}
+ {full ? <span className="ml-2 normal-case tracking-normal text-[var(--warn)]">{t('exportCenter.moments.limit').replace('{n}', String(max))}</span> : null}
+ </span>
+ {value.length > 0 && (
+ <button type="button" onClick={() => set([])} className="text-[12px] text-[var(--text-muted)] transition hover:text-[var(--text)]">
+ {t('exportCenter.moments.clear')}
+ </button>
+ )}
+ </div>
+ <p className="-mt-1.5 text-[11.5px] leading-relaxed text-[var(--text-faint)]">
+ {t(value.length ? 'exportCenter.moments.selectHint' : 'exportCenter.moments.none')}
+ </p>
+ <div className="grid gap-2.5" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(136px, 1fr))' }}>
+ {value.map((ms, i) => {
+ const on = selected != null && sameFrame(ms, selected, fps);
+ return (
+ <div key={ms} className="group relative flex min-w-0 flex-col gap-1">
+ <button
+ type="button"
+ onClick={() => {
+ /* a click selects it, its dot on the strip, the large picture at it; a second click lets it go */
+ if (on) setSelected(null);
+ else { setSelected(ms); goTo(ms); }
+ focus();
+ }}
+ aria-pressed={on}
+ aria-label={formatTimecode(ms, { fps })}
+ className={`relative overflow-hidden border-2 transition ${on ? 'border-[var(--accent)]' : 'border-transparent hover:border-[var(--border)]'}`}
+ >
+ <Framed box={box} src={frames.get(url(ms))} />
+ </button>
+ <div className="flex min-w-0 items-center gap-1.5 text-[11px] tabular-nums">
+ <span className={`min-w-5 shrink-0 rounded-md px-1 py-0.5 text-center text-[10px] font-medium ${on ? 'bg-[var(--accent)] text-white' : 'bg-[var(--bg-hover)] text-[var(--text-muted)]'}`}>
+ {i + 1}
+ </span>
+ <span className={`min-w-0 truncate ${on ? 'text-[var(--text)]' : 'text-[var(--text-muted)]'}`}>{formatTimecode(ms, { fps })}</span>
+ <button
+ type="button"
+ onClick={() => remove(ms)}
+ aria-label={t('exportCenter.moments.remove')}
+ className="ml-auto flex h-5 w-5 shrink-0 items-center justify-center rounded text-[var(--text-muted)] opacity-0 transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:opacity-100 group-hover:opacity-100"
+ >
+ <X size={13} />
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ {!picked && !full && (
+ <button
+ type="button"
+ onClick={() => add(cursor)}
+ aria-label={t('exportCenter.moments.add')}
+ className="flex items-center justify-center self-start border border-dashed border-[var(--border)] text-[var(--text-faint)] transition hover:border-[var(--text-faint)] hover:text-[var(--text)]"
+ style={{ aspectRatio: `${box.w} / ${box.h}` }}
+ >
+ <Plus size={18} />
+ </button>
+ )}
+ </div>
+
+ {everyMenu && (
+ <ContextMenu x={everyMenu.x} y={everyMenu.y} flipTo={everyMenu.top} dense trigger={everyRef} items={everyItems} onClose={() => setEveryMenu(null)} />
+ )}
+ </div>
+ );
+}
+
+/** The frames drawn so far, by address (as pictures held in this page). */
+interface Frames { get: (url: string) => string | undefined }
+
+/**
+ * Frames from the server, one at a time, the first of `wanted` not drawn yet first: a frame no longer wanted (a moment
+ * scrubbed past) is never asked for. Each is kept as a picture in this page while the picker is open, so showing it
+ * again asks the server nothing.
+ */
+function useFrames(wanted: readonly string[]): Frames {
+ const [, drawn] = React.useReducer((n: number) => n + 1, 0);
+ const state = React.useRef({ done: new Map<string, string>(), failed: new Set<string>(), busy: false, alive: true, wanted });
+ state.current.wanted = wanted;
+ const next = React.useCallback(() => {
+ const s = state.current;
+ if (s.busy || !s.alive) return;
+ const url = s.wanted.find((u) => !s.done.has(u) && !s.failed.has(u));
+ if (!url) return;
+ s.busy = true;
+ void fetch(url)
+ .then((r) => (r.ok ? r.blob() : Promise.reject(new Error(String(r.status)))))
+ .then((blob) => { if (s.alive) s.done.set(url, URL.createObjectURL(blob)); }, () => { s.failed.add(url); })
+ .finally(() => {
+ s.busy = false;
+ if (!s.alive) return;
+ drawn();
+ next();
+ });
+ }, []);
+ React.useEffect(() => next(), [wanted.join('\n'), next]);
+ React.useEffect(() => {
+ const s = state.current;
+ s.alive = true;
+ return () => {
+ s.alive = false;
+ for (const u of s.done.values()) URL.revokeObjectURL(u);
+ s.done.clear();
+ };
+ }, []);
+ return { get: (url) => state.current.done.get(url) };
+}
+
+/** The film in the export's frame: bars where the film does not reach it, cut where it overflows. */
+function Framed({ box, src, children }: { box: FilmFrameBox; src: string | undefined; children?: React.ReactNode }) {
+ return (
+ <div className="relative w-full overflow-hidden bg-black" style={{ aspectRatio: `${box.w} / ${box.h}` }}>
+ {src ? (
+ <img
+ src={src}
+ alt=""
+ draggable={false}
+ className="absolute max-w-none select-none"
+ style={{
+ left: `${(box.inner.left / box.w) * 100}%`,
+ top: `${(box.inner.top / box.h) * 100}%`,
+ width: `${(box.inner.w / box.w) * 100}%`,
+ height: `${(box.inner.h / box.h) * 100}%`,
+ }}
+ />
+ ) : null}
+ {children}
+ </div>
+ );
+}
+
+/** The large picture of one moment: until it is drawn, the last one drawn stays up, with a spinner. */
+function Preview({ frames, url, box, ms, fps, children }: {
+ frames: Frames; url: string; box: FilmFrameBox; ms: number; fps: number; children?: React.ReactNode;
+}) {
+ const src = frames.get(url);
+ const last = React.useRef<string | undefined>(undefined);
+ if (src) last.current = src;
+ return (
+ /* Grow with the export window; leave room for its controls on shorter displays. */
+ <div className="flex min-w-0 flex-col items-center gap-2">
+ <div
+ className="w-full overflow-hidden border border-[var(--border)]"
+ style={{ maxWidth: `calc(min(56dvh, 620px, max(180px, 100dvh - 380px)) * ${box.w / box.h})` }}
+ >
+ <Framed box={box} src={src ?? last.current}>
+ {src ? null : <Loader2 size={16} className="absolute right-3 top-3 animate-spin text-white/80" />}
+ </Framed>
+ </div>
+ <div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-2">
+ <span className="font-mono text-[12px] tabular-nums text-[var(--text-muted)]">
+ {formatTimecode(ms, { fps })}
+ </span>
+ {children}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The film as a row of pictures under a ruler, the part in sight of `view`. Pressed or dragged, it moves the moment
+ * shown, including double clicks. Items are selected or added with the controls below the strip.
+ * The frame selected below shows its dot above it, dragged to move it;
+ * the film's markers are under it. Zoomed in, a bar under it shows and moves what is in sight.
+ */
+function Strip({ stripRef, stripW, view, setView, msPerPx, cells, cellStep, totalMs, fps, cursor, selected, markers, onCursor, onDragSelected, onMoveSelected, label, overlay }: {
+ stripRef: React.RefObject<HTMLDivElement | null>;
+ stripW: number;
+ view: StripView;
+ setView: (v: StripView) => void;
+ msPerPx: number;
+ /** the cells in sight: where each starts (ms), the moment it shows, its picture once drawn */
+ cells: readonly { at: number; ms: number; src: string | undefined }[];
+ cellStep: number;
+ totalMs: number;
+ fps: number;
+ cursor: number;
+ selected: number | null;
+ markers: readonly number[];
+ onCursor: (ms: number) => void;
+ onDragSelected: (ms: number) => void;
+ onMoveSelected: (to: number) => void;
+ label: string;
+ /** Range selection shares this filmstrip, drawing its trim handles over the same frames. */
+ overlay?: React.ReactNode;
+}) {
+ const x = (ms: number) => (ms - view.start) / msPerPx;
+ const at = (clientX: number) => {
+ const r = stripRef.current!.getBoundingClientRect();
+ return momentAt(view.start + (clientX - r.left) * msPerPx, totalMs, fps);
+ };
+ const [hover, setHover] = React.useState<number | null>(null);
+ /* the selected frame's dot being dragged: where it is now */
+ const [drag, setDrag] = React.useState<number | null>(null);
+ const pin = drag ?? selected;
+
+ /* Ctrl/⌘ + wheel (and a pinch) zooms around the pointer, a sideways swipe or Shift + wheel scrolls, as on the
+ timeline. A native listener: React's onWheel is passive and cannot stop the browser's page zoom. */
+ const latest = React.useRef({ view, msPerPx, setView, totalMs });
+ latest.current = { view, msPerPx, setView, totalMs };
+ React.useEffect(() => {
+ const el = stripRef.current?.parentElement;
+ if (!el) return undefined;
+ let factor = 1;
+ let anchor = 0;
+ let raf = 0;
+ const flush = () => {
+ raf = 0;
+ const { view: v, setView: set, totalMs: total } = latest.current;
+ const f = factor;
+ factor = 1;
+ if (f !== 1) set(zoomView(v, f, anchor, total));
+ };
+ const pixels = (e: WheelEvent, d: number) => (e.deltaMode === 1 ? d * 16 : e.deltaMode === 2 ? d * 400 : d);
+ const onWheel = (e: WheelEvent) => {
+ const r = stripRef.current!.getBoundingClientRect();
+ if (e.ctrlKey || e.metaKey) {
+ e.preventDefault();
+ factor *= Math.exp(-pixels(e, e.deltaY) / 180);
+ anchor = Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width)));
+ if (!raf) raf = requestAnimationFrame(flush);
+ return;
+ }
+ const dx = pixels(e, e.deltaX || (e.shiftKey ? e.deltaY : 0));
+ if (!dx || latest.current.view.zoom <= 1) return;
+ e.preventDefault();
+ const { view: v, msPerPx: k, setView: set } = latest.current;
+ set({ ...v, start: v.start + dx * k });
+ };
+ el.addEventListener('wheel', onWheel, { passive: false });
+ return () => {
+ el.removeEventListener('wheel', onWheel);
+ if (raf) cancelAnimationFrame(raf);
+ };
+ }, [stripRef]);
+
+ /* the ruler: labels at least TICK_PX apart, on whole steps of the clock */
+ const tickStep = stepFor(msPerPx, TICK_PX, TICK_STEPS);
+ const ticks: number[] = [];
+ if (stripW > 0) for (let ms = Math.ceil(view.start / tickStep) * tickStep; ms <= view.start + stripW * msPerPx; ms += tickStep) ticks.push(ms);
+ const inSight = (ms: number) => ms >= view.start - msPerPx && ms <= view.start + stripW * msPerPx + msPerPx;
+
+ return (
+ <div className="relative select-none">
+ {/* the ruler, and the selected frame's dot */}
+ <div className="relative h-5 overflow-hidden text-[10.5px] tabular-nums text-[var(--text-faint)]">
+ {ticks.map((ms) => (
+ <span key={ms} className="absolute bottom-0 flex items-end" style={{ left: x(ms) }}>
+ <span className="h-1.5 w-px bg-[var(--border-strong,var(--border))]" />
+ <span className="ml-1 leading-none">{formatRulerLabel(ms, fps)}</span>
+ </span>
+ ))}
+ {pin != null && inSight(pin) && (
+ <span
+ role="button"
+ aria-label={formatTimecode(pin, { fps })}
+ className="absolute bottom-0 z-10 h-3.5 w-3.5 -translate-x-1/2 cursor-ew-resize rounded-full border-2 border-[var(--surface)] bg-[var(--accent)] shadow-[var(--shadow-sm)]"
+ style={{ left: x(pin) }}
+ onPointerDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ setDrag(pin);
+ }}
+ onPointerMove={(e) => {
+ if (drag == null) return;
+ const to = at(e.clientX);
+ if (!sameFrame(to, drag, fps)) { setDrag(to); onDragSelected(to); }
+ }}
+ onPointerUp={() => {
+ if (drag == null) return;
+ if (selected != null && !sameFrame(drag, selected, fps)) onMoveSelected(drag);
+ setDrag(null);
+ }}
+ onPointerCancel={() => setDrag(null)}
+ />
+ )}
+ </div>
+ <div
+ ref={stripRef}
+ role={overlay ? 'group' : 'slider'}
+ aria-label={label}
+ aria-valuemin={overlay ? undefined : 0}
+ aria-valuemax={overlay ? undefined : Math.round(totalMs)}
+ aria-valuenow={overlay ? undefined : Math.round(cursor)}
+ aria-valuetext={overlay ? undefined : formatTimecode(cursor, { fps })}
+ className="relative cursor-pointer overflow-hidden bg-black"
+ style={{ height: STRIP_H }}
+ onPointerDown={(e) => {
+ if (e.button !== 0) return;
+ e.preventDefault();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ onCursor(at(e.clientX));
+ }}
+ onPointerMove={(e) => {
+ if (e.currentTarget.hasPointerCapture(e.pointerId)) onCursor(at(e.clientX));
+ else setHover(at(e.clientX));
+ }}
+ onPointerLeave={() => setHover(null)}
+ >
+ {cells.map((c) => (
+ <span
+ key={c.at}
+ className="absolute inset-y-0 overflow-hidden border-r border-black/50"
+ style={{ left: x(c.at), width: cellStep / msPerPx }}
+ >
+ {c.src ? <img src={c.src} alt="" draggable={false} className="h-full w-full object-cover" /> : null}
+ </span>
+ ))}
+ {/* past the film's end */}
+ {x(totalMs) < stripW && <span className="absolute inset-y-0 right-0 bg-[var(--surface-2)]" style={{ left: x(totalMs) }} />}
+ {overlay}
+ {pin != null && inSight(pin) && (
+ <span className="pointer-events-none absolute inset-y-0 w-0.5 -translate-x-1/2 bg-[var(--accent)]" style={{ left: x(pin) }} />
+ )}
+ {hover != null && (
+ <span className="pointer-events-none absolute inset-y-0 w-px bg-white/45" style={{ left: x(hover) }}>
+ <span className="absolute left-1 top-1 whitespace-nowrap rounded bg-black/75 px-1 py-px font-mono text-[10.5px] tabular-nums text-white">
+ {formatTimecode(hover, { fps })}
+ </span>
+ </span>
+ )}
+ {inSight(cursor) && (
+ <span className="pointer-events-none absolute inset-y-0 w-0.5 -translate-x-1/2 bg-white shadow-[0_0_0_1px_rgba(0,0,0,0.35)]" style={{ left: x(cursor) }} />
+ )}
+ </div>
+ {/* the film's markers */}
+ <div className="relative h-2.5 overflow-hidden">
+ {markers.filter(inSight).map((ms) => (
+ <button
+ key={ms}
+ type="button"
+ tabIndex={-1}
+ aria-label={formatTimecode(ms, { fps })}
+ onClick={() => onCursor(ms)}
+ className="absolute top-0.5 h-0 w-0 -translate-x-1/2 border-x-[4px] border-b-[6px] border-x-transparent border-b-[var(--warn)]"
+ style={{ left: x(ms) }}
+ />
+ ))}
+ </div>
+ {/* zoomed in: what is in sight of the whole film, dragged to scroll */}
+ {view.zoom > 1 && (
+ <div
+ className="relative mt-0.5 h-1.5 rounded-full bg-[var(--bg-hover)]"
+ onPointerDown={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ const span = totalMs / view.zoom;
+ const grab = view.start + span / 2;
+ const onTrack = (clientX: number) => ((clientX - r.left) / Math.max(1, r.width)) * totalMs;
+ /* a press on the bar's thumb drags it from where it was held; elsewhere, centers it there */
+ const offset = Math.abs(onTrack(e.clientX) - grab) <= span / 2 ? onTrack(e.clientX) - view.start : span / 2;
+ setView({ ...view, start: onTrack(e.clientX) - offset });
+ const move = (ev: PointerEvent) => setView({ ...view, start: onTrack(ev.clientX) - offset });
+ const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }}
+ >
+ <span
+ className="absolute inset-y-0 cursor-grab rounded-full bg-[var(--text-faint)]"
+ style={{ left: `${(view.start / totalMs) * 100}%`, width: `${100 / view.zoom}%` }}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
+
+/**
+ * Zoom out, a bar from the whole film to a second across, zoom in, and the whole film again. They zoom around `anchor`
+ * (0 to 1 across the strip): the moment shown, while it is in sight.
+ */
+function ZoomControls({ view, totalMs, setView, anchor, t }: {
+ view: StripView; totalMs: number; setView: (v: StripView) => void; anchor: number; t: (k: string) => string;
+}) {
+ const most = stripZoomMax(totalMs);
+ /* the bar is even in the log of the zoom: each step doubles it alike */
+ const level = Math.log(view.zoom) / Math.log(most);
+ const zoomTo = (zoom: number) => setView(zoomView(view, zoom / view.zoom, anchor, totalMs));
+ const button = 'flex h-7 w-7 items-center justify-center rounded-md text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-40';
+ return (
+ <div className="flex shrink-0 items-center gap-1">
+ <button type="button" className={button} onClick={() => zoomTo(view.zoom / 2)} disabled={view.zoom <= 1} aria-label={t('exportCenter.moments.zoomOut')} title={t('exportCenter.moments.zoomOut')}>
+ <ZoomOut size={15} />
+ </button>
+ <input
+ type="range"
+ min={0}
+ max={1}
+ step={0.001}
+ value={level}
+ onChange={(e) => zoomTo(most ** Number(e.target.value))}
+ aria-label={t('exportCenter.moments.zoom')}
+ className="w-24 accent-[var(--text)]"
+ />
+ <button type="button" className={button} onClick={() => zoomTo(view.zoom * 2)} disabled={view.zoom >= most} aria-label={t('exportCenter.moments.zoomIn')} title={t('exportCenter.moments.zoomIn')}>
+ <ZoomIn size={15} />
+ </button>
+ <button type="button" className={button} onClick={() => setView(STRIP_WHOLE)} disabled={view.zoom <= 1} aria-label={t('exportCenter.moments.zoomFit')} title={t('exportCenter.moments.zoomFit')}>
+ <MoveHorizontal size={15} />
+ </button>
+ </div>
+ );
+}
+
+export { Strip as Filmstrip, ZoomControls as FilmstripZoom, useFrames as useFilmFrames };
diff --git a/packages/openfilm/studio/ui/src/components/export/RangePicker.tsx b/packages/openfilm/studio/ui/src/components/export/RangePicker.tsx
new file mode 100644
index 0000000..d8bd383
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/export/RangePicker.tsx
@@ -0,0 +1,325 @@
+import React from 'react';
+import { ChevronLeft, ChevronRight, Loader2, Pause, Play, Plus, Volume2, VolumeX, X } from 'lucide-react';
+import { api } from '@/api';
+import { Preview, type FilmInfo, type PreviewHandle } from '@/editor/Preview';
+import { Player } from '@/editor/player';
+import { useT } from '@/i18n';
+import { clampView, filmFrameUrl, momentAt, stepFor, STRIP_WHOLE, stripZoomMax, viewShowing, type StripView } from '@/lib/export-moments';
+import { EXPORT_RANGE_MAX, parseExportTime, readExportRange, type ExportRangeDraft, type RangeDelivery } from '@/lib/export-range';
+import { formatTimecode, frameMs, snapToFrame, stepFrames } from '@/lib/timecode';
+import { ExportTimeInput } from './ExportTimeInput';
+import { Filmstrip, FilmstripZoom, useFilmFrames } from './MomentPicker';
+
+const CELL_STEPS = [100, 200, 500, 1000, 2000, 5000, 10_000, 15_000, 30_000, 60_000, 120_000, 300_000, 600_000, 1_800_000];
+
+/** The film playing beside an ordered list of in/out selections; its controls never cover the picture. */
+export function RangePicker({ projectId, totalMs, fps, stage, boundaries, value, onChange, delivery, onDelivery, error }: {
+ projectId: string;
+ totalMs: number;
+ fps: number;
+ stage: { w: number; h: number };
+ boundaries: { starts: { ms: number; title: string }[]; ends: { ms: number; title: string }[] };
+ value: ExportRangeDraft[];
+ onChange: (parts: ExportRangeDraft[]) => void;
+ delivery: RangeDelivery;
+ onDelivery: (delivery: RangeDelivery) => void;
+ error: string | null;
+}) {
+ const t = useT();
+ const [folder, setFolder] = React.useState<string | null>(null);
+ const [failed, setFailed] = React.useState(false);
+ const [ready, setReady] = React.useState(false);
+ const [attempt, setAttempt] = React.useState(0);
+ const [activeId, setActiveId] = React.useState(value[0]?.id ?? '');
+ const active = value.find((part) => part.id === activeId) ?? value[0];
+ const activeRange = active ? readExportRange(active.from, active.to, totalMs, fps) : null;
+ const preview = React.useRef<PreviewHandle>(null);
+ const [player] = React.useState(() => new Player());
+ const [cursor, setCursor] = React.useState(0);
+ const cursorRef = React.useRef(0);
+ const [playing, setPlaying] = React.useState(false);
+ const [muted, setMuted] = React.useState(false);
+ const sequence = React.useRef(0);
+ const root = React.useRef<HTMLDivElement>(null);
+ const stripRef = React.useRef<HTMLDivElement>(null);
+ const [stripW, setStripW] = React.useState(0);
+ const [view, setViewRaw] = React.useState<StripView>(STRIP_WHOLE);
+ const setView = React.useCallback((next: StripView) => setViewRaw(clampView(next, totalMs)), [totalMs]);
+ React.useLayoutEffect(() => {
+ const el = stripRef.current;
+ if (!el) return;
+ const observer = new ResizeObserver(() => setStripW(el.clientWidth));
+ observer.observe(el);
+ setStripW(el.clientWidth);
+ return () => observer.disconnect();
+ }, []);
+ const span = totalMs / view.zoom;
+ const msPerPx = stripW > 0 ? span / stripW : 1;
+ const cellStep = stepFor(msPerPx, 56 * stage.w / Math.max(1, stage.h), CELL_STEPS);
+ const cells = React.useMemo(() => {
+ const list: { at: number; ms: number }[] = [];
+ if (stripW > 0) for (let k = Math.floor(view.start / cellStep); k * cellStep < Math.min(totalMs, view.start + span); k++) {
+ list.push({ at: k * cellStep, ms: momentAt(k * cellStep + cellStep / 2, totalMs, fps) });
+ }
+ return list;
+ }, [stripW, view.start, span, cellStep, totalMs, fps]);
+ const picks = value.map((part) => ({ ...part, read: readExportRange(part.from, part.to, totalMs, fps) }));
+ const url = (ms: number) => filmFrameUrl(projectId, ms, 480);
+ const frames = useFilmFrames([
+ ...(activeRange ? [url(activeRange.fromMs)] : []),
+ ...[...cells].sort((a, b) => Math.abs(a.ms - cursor) - Math.abs(b.ms - cursor)).map((cell) => url(cell.ms)),
+ ...picks.flatMap((part) => part.read ? [url(part.read.fromMs)] : []),
+ ]);
+ const now = React.useCallback(() => player.time(), [player]);
+ const seek = React.useCallback((at: number) => {
+ const ms = Math.max(0, Math.min(totalMs, at));
+ player.pause();
+ player.seek(ms / 1000);
+ preview.current?.seek(Math.min(ms, Math.max(0, totalMs - 0.001)) / 1000);
+ cursorRef.current = ms;
+ setCursor(ms);
+ setPlaying(false);
+ setViewRaw((current) => viewShowing(current, ms, totalMs));
+ }, [player, totalMs]);
+
+ React.useEffect(() => {
+ let live = true;
+ setFolder(null);
+ setReady(false);
+ setFailed(false);
+ void api.film(projectId).then((film) => { if (live) setFolder(film.folder); }, () => { if (live) setFailed(true); });
+ return () => { live = false; };
+ }, [projectId, attempt]);
+ React.useEffect(() => {
+ player.onAnchor = (anchor) => preview.current?.play?.(anchor);
+ return () => { player.onAnchor = null; player.close(); };
+ }, [player]);
+ React.useEffect(() => {
+ const from = active ? parseExportTime(active.from, fps) : 0;
+ seek(from ?? 0);
+ // Selecting a different range starts its preview at that range's first frame.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [active?.id, seek]);
+ React.useEffect(() => {
+ if (!playing) return;
+ let frame = 0;
+ const end = activeRange?.toMs ?? totalMs;
+ const tick = () => {
+ const ms = player.time() * 1000;
+ if (ms >= end) { seek(end); return; }
+ cursorRef.current = ms;
+ setCursor(ms);
+ frame = requestAnimationFrame(tick);
+ };
+ frame = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(frame);
+ }, [playing, player, activeRange?.toMs, totalMs, seek]);
+ React.useEffect(() => { if (failed) seek(cursorRef.current); }, [failed, seek]);
+ const onInfo = React.useCallback((info: FilmInfo) => {
+ if (!folder) return;
+ player.load(folder, info.sounds, info.duration);
+ player.seek(cursorRef.current / 1000);
+ setReady(true);
+ }, [folder, player]);
+ const togglePlay = () => {
+ if (playing) { seek(player.time() * 1000); return; }
+ const from = activeRange?.fromMs ?? 0, to = activeRange?.toMs ?? totalMs;
+ if (cursor < from || cursor >= to) seek(from);
+ player.play();
+ setPlaying(true);
+ };
+ const patch = (change: Partial<ExportRangeDraft>) => {
+ if (active) onChange(value.map((part) => part.id === active.id ? { ...part, ...change } : part));
+ };
+ const setEdge = (edge: 'from' | 'to', at: number) => {
+ const step = frameMs(1, fps);
+ if (edge === 'from') {
+ const from = Math.max(0, Math.min(at, totalMs - step));
+ const to = Math.min(totalMs, Math.max(parseExportTime(active?.to ?? '', fps) ?? totalMs, from + step));
+ patch({ from: String(from / 1000), to: String(to / 1000) });
+ } else {
+ const to = Math.min(totalMs, Math.max(step, at));
+ const from = Math.max(0, Math.min(parseExportTime(active?.from ?? '', fps) ?? 0, to - step));
+ patch({ from: String(from / 1000), to: String(to / 1000) });
+ }
+ };
+ const typeEdge = (edge: 'from' | 'to', text: string) => {
+ patch({ [edge]: text });
+ const at = parseExportTime(text, fps);
+ if (at != null && at <= totalMs) seek(at);
+ };
+ const add = () => {
+ if (value.length >= EXPORT_RANGE_MAX) return;
+ const next = activeRange && cursor >= activeRange.fromMs && cursor < activeRange.toMs ? activeRange.toMs : cursor;
+ const from = Math.max(0, snapToFrame(next < totalMs - frameMs(1, fps) ? next : 0, fps));
+ const part = { id: `range-${Date.now()}-${++sequence.current}`, from: String(from / 1000), to: String(Math.min(totalMs, from + 3000) / 1000) };
+ onChange([...value, part]);
+ setActiveId(part.id);
+ };
+ const focus = () => root.current?.focus({ preventScroll: true });
+ const atPointer = (clientX: number) => {
+ const rect = stripRef.current!.getBoundingClientRect();
+ return Math.max(0, Math.min(totalMs, snapToFrame(view.start + (clientX - rect.left) * msPerPx, fps)));
+ };
+ const onKey = (event: React.KeyboardEvent) => {
+ if ((event.target as HTMLElement).closest('input, button, [role="slider"]')) return;
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
+ const direction = event.key === 'ArrowLeft' ? -1 : 1;
+ seek(event.shiftKey ? cursor + direction * 1000 : stepFrames(cursor, direction, fps));
+ } else if (event.key === ' ' && ready && !failed) togglePlay();
+ else return;
+ event.preventDefault();
+ event.stopPropagation();
+ };
+ const iconButton = 'flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-40';
+ const activeIndex = active ? value.findIndex((part) => part.id === active.id) : -1;
+ const full = value.length >= EXPORT_RANGE_MAX;
+ // Existing ranges are selected through their cards. The strip seeks freely, even where ranges overlap.
+ const selectionOverlay = activeRange ? (
+ <div className="pointer-events-none absolute inset-y-0 z-10 border-y-2 border-[var(--accent)] bg-[color-mix(in_srgb,var(--accent)_12%,transparent)]"
+ style={{ left: (activeRange.fromMs - view.start) / msPerPx, width: (activeRange.toMs - activeRange.fromMs) / msPerPx }}>
+ {(['from', 'to'] as const).map((edge) => {
+ const ms = edge === 'from' ? activeRange.fromMs : activeRange.toMs;
+ return <button
+ key={edge}
+ type="button"
+ role="slider"
+ aria-label={t(edge === 'from' ? 'exportCenter.rangeDragStart' : 'exportCenter.rangeDragEnd')}
+ aria-valuemin={0}
+ aria-valuemax={Math.round(totalMs)}
+ aria-valuenow={Math.round(ms)}
+ aria-valuetext={formatTimecode(ms, { fps })}
+ className={`pointer-events-auto absolute -inset-y-0.5 z-20 flex w-3 cursor-ew-resize items-center justify-center bg-[var(--accent)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--text)] ${edge === 'from' ? '-left-1.5' : '-right-1.5'}`}
+ onPointerDown={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ seek(ms);
+ }}
+ onPointerMove={(event) => {
+ if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
+ const at = atPointer(event.clientX);
+ setEdge(edge, at);
+ seek(at);
+ }}
+ onKeyDown={(event) => {
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
+ event.preventDefault();
+ event.stopPropagation();
+ const at = stepFrames(ms, event.key === 'ArrowLeft' ? -1 : 1, fps);
+ setEdge(edge, at);
+ seek(at);
+ }}
+ ><span className="h-4 w-px bg-white/80" /></button>;
+ })}
+ </div>
+ ) : null;
+
+ return (
+ <div ref={root} tabIndex={0} onKeyDown={onKey} className="mt-2 grid min-w-0 gap-6 outline-none lg:grid-cols-[minmax(0,1fr)_272px]">
+ <div className="flex min-w-0 flex-col gap-3">
+ <div className="flex min-w-0 flex-col items-center gap-2">
+ <div className="relative w-full overflow-hidden border border-[var(--border)] bg-black" aria-label={t('exportCenter.rangePreview')}
+ style={{ aspectRatio: `${stage.w} / ${stage.h}`, maxWidth: `calc(min(56dvh, 620px, max(180px, 100dvh - 380px)) * ${stage.w / stage.h})` }}>
+ {folder && !failed ? <Preview ref={preview} folder={folder} stage={stage} time={now} fps={fps} onInfo={onInfo} onError={(message) => { if (message) setFailed(true); }} /> : null}
+ {!folder && !failed && <div className="absolute inset-0 flex items-center justify-center"><Loader2 size={20} className="animate-spin text-white/60" /></div>}
+ {failed && <div role="alert" className="absolute inset-0 flex flex-col items-center justify-center gap-2 p-3 text-center text-[12px] text-white/70">
+ {t('exportCenter.rangePreviewFailed')}
+ <button type="button" onClick={() => setAttempt((n) => n + 1)} className="rounded-lg border border-white/30 px-3 py-1">{t('exportCenter.rangeRetry')}</button>
+ </div>}
+ </div>
+ <div className="flex flex-wrap items-center justify-center gap-1.5">
+ <button type="button" className={iconButton} disabled={!ready || failed} onClick={togglePlay} aria-label={t(playing ? 'exportCenter.rangePause' : 'exportCenter.rangePlay')}>
+ {playing ? <Pause size={15} /> : <Play size={15} />}
+ </button>
+ <button type="button" className={iconButton} disabled={!ready || failed} onClick={() => seek(stepFrames(cursor, -1, fps))} aria-label={t('exportCenter.rangePreviousFrame')}><ChevronLeft size={15} /></button>
+ <span className="px-1 font-mono text-[12px] tabular-nums text-[var(--text-muted)]">{formatTimecode(cursor, { fps })}</span>
+ <button type="button" className={iconButton} disabled={!ready || failed} onClick={() => seek(stepFrames(cursor, 1, fps))} aria-label={t('exportCenter.rangeNextFrame')}><ChevronRight size={15} /></button>
+ <button type="button" className={iconButton} onClick={() => { player.setMuted(!muted); setMuted(!muted); }} aria-label={t(muted ? 'exportCenter.rangeUnmute' : 'exportCenter.rangeMute')}>
+ {muted ? <VolumeX size={15} /> : <Volume2 size={15} />}
+ </button>
+ <button type="button" onClick={() => add()} disabled={full}
+ className="ml-2 flex h-8 items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 text-[12.5px] font-medium text-[var(--text)] transition hover:bg-[var(--bg-hover)] disabled:opacity-50">
+ <Plus size={14} />{t('exportCenter.rangeAdd')}
+ </button>
+ </div>
+ </div>
+
+ <Filmstrip
+ stripRef={stripRef}
+ stripW={stripW}
+ view={view}
+ setView={setView}
+ msPerPx={msPerPx}
+ cells={cells.map((cell) => ({ ...cell, src: frames.get(url(cell.ms)) }))}
+ cellStep={cellStep}
+ totalMs={totalMs}
+ fps={fps}
+ cursor={cursor}
+ selected={null}
+ markers={[]}
+ onCursor={(at) => { seek(at); focus(); }}
+ onDragSelected={seek}
+ onMoveSelected={seek}
+ label={t('exportCenter.rangeSeek')}
+ overlay={selectionOverlay}
+ />
+ <div className="-mt-1 flex flex-wrap items-start justify-between gap-x-4 gap-y-2">
+ <p className="min-w-0 flex-1 basis-[260px] text-[11.5px] leading-relaxed text-[var(--text-faint)]">{t('exportCenter.rangeStripHint')}</p>
+ {stripZoomMax(totalMs) > 1 && <FilmstripZoom view={view} totalMs={totalMs} setView={setView} anchor={cursor >= view.start && cursor <= view.start + span ? (cursor - view.start) / span : 0.5} t={t} />}
+ </div>
+ <div className="flex items-center justify-between gap-3 pt-1">
+ <span className="text-[11.5px] font-medium uppercase tracking-wide text-[var(--text-faint)]">{t('exportCenter.rangeCount').replace('{n}', String(value.length))}</span>
+ {value.length > 0 && <button type="button" onClick={() => onChange([])} className="text-[12px] text-[var(--text-muted)] transition hover:text-[var(--text)]">{t('exportCenter.moments.clear')}</button>}
+ </div>
+ <p className="-mt-1.5 text-[11.5px] leading-relaxed text-[var(--text-faint)]">{t('exportCenter.rangeCardsHint')}</p>
+ <div className="grid gap-2.5" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(136px, 1fr))' }}>
+ {picks.map((part, index) => {
+ const selected = active?.id === part.id;
+ const src = part.read ? frames.get(url(part.read.fromMs)) : undefined;
+ return <div key={part.id} className="group relative flex min-w-0 flex-col gap-1">
+ <button type="button" aria-pressed={selected} onClick={() => { setActiveId(part.id); seek(part.read?.fromMs ?? 0); focus(); }} aria-label={t('exportCenter.rangeSegment').replace('{n}', String(index + 1))}
+ className={`relative overflow-hidden border-2 bg-black transition ${selected ? 'border-[var(--accent)]' : 'border-transparent hover:border-[var(--border)]'}`} style={{ aspectRatio: `${stage.w} / ${stage.h}` }}>
+ {src && <img src={src} alt="" draggable={false} className="h-full w-full object-contain" />}
+ </button>
+ <div className="flex min-w-0 items-start gap-1.5 text-[11px] tabular-nums">
+ <span className={`min-w-5 shrink-0 rounded-md px-1 py-0.5 text-center text-[10px] font-medium ${selected ? 'bg-[var(--accent)] text-white' : 'bg-[var(--bg-hover)] text-[var(--text-muted)]'}`}>{index + 1}</span>
+ <span className={`min-w-0 flex-1 leading-5 ${selected ? 'text-[var(--text)]' : 'text-[var(--text-muted)]'}`}>
+ {part.read ? <><span className="block truncate">{formatTimecode(part.read.fromMs, { fps })}</span><span className="block truncate text-[var(--text-faint)]">{formatTimecode(part.read.toMs, { fps })}</span></> : t('exportCenter.rangeInvalidSegment')}
+ </span>
+ <button type="button" className="ml-auto flex h-5 w-5 shrink-0 items-center justify-center rounded text-[var(--text-muted)] opacity-0 transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:opacity-100 group-hover:opacity-100" aria-label={t('exportCenter.rangeRemove').replace('{n}', String(index + 1))} onClick={() => onChange(value.filter((other) => other.id !== part.id))}><X size={13} /></button>
+ </div>
+ </div>;
+ })}
+ {!full && <button type="button" onClick={() => add()} aria-label={t('exportCenter.rangeAdd')} className="flex items-center justify-center self-start border border-dashed border-[var(--border)] text-[var(--text-faint)] transition hover:border-[var(--text-faint)] hover:text-[var(--text)]" style={{ aspectRatio: `${stage.w} / ${stage.h}` }}><Plus size={18} /></button>}
+ </div>
+ </div>
+
+ <aside className="flex min-w-0 flex-col gap-5">
+ {active && <div className="flex flex-col gap-3">
+ <span className="text-[11.5px] font-medium uppercase tracking-wide text-[var(--text-faint)]">{t('exportCenter.rangeSegment').replace('{n}', String(activeIndex + 1))}</span>
+ <div className="flex flex-col gap-1.5">
+ <ExportTimeInput compact label={t('exportCenter.rangeFrom')} boundaryLabel={t('exportCenter.rangeBoundary')} value={active.from} fps={fps} marks={boundaries.starts} invalid={!activeRange} onChange={(from) => typeEdge('from', from)} />
+ <button type="button" onClick={() => setEdge('from', snapToFrame(cursor, fps))} className="self-start text-[11.5px] text-[var(--text-muted)] transition hover:text-[var(--text)]">{t('exportCenter.rangeSetStart')}</button>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <ExportTimeInput compact label={t('exportCenter.rangeTo')} boundaryLabel={t('exportCenter.rangeBoundary')} value={active.to} fps={fps} marks={boundaries.ends} invalid={!activeRange} onChange={(to) => typeEdge('to', to)} />
+ <button type="button" onClick={() => setEdge('to', Math.min(snapToFrame(cursor, fps), totalMs))} className="self-start text-[11.5px] text-[var(--text-muted)] transition hover:text-[var(--text)]">{t('exportCenter.rangeSetEnd')}</button>
+ </div>
+ <p className="text-[11.5px] leading-relaxed text-[var(--text-faint)]">{t('exportCenter.rangeHint')}</p>
+ </div>}
+ {error && <p role="alert" className="text-[12px] text-[var(--warn)]">{error}</p>}
+ <div className="flex flex-col gap-2">
+ <span className="text-[11.5px] font-medium uppercase tracking-wide text-[var(--text-faint)]">{t('exportCenter.rangeDelivery')}</span>
+ <div className="grid gap-2" role="group" aria-label={t('exportCenter.rangeDelivery')}>
+ {(['separate', 'merged'] as const).map((mode) => <button key={mode} type="button" aria-pressed={delivery === mode} onClick={() => onDelivery(mode)}
+ className={`flex flex-col items-start gap-0.5 rounded-xl border px-3 py-2.5 text-left transition ${delivery === mode ? 'border-[var(--text)] bg-[var(--bg-hover)]' : 'border-[var(--border)] hover:border-[var(--text-faint)]'}`}>
+ <span className="text-[12.5px] font-medium text-[var(--text)]">{t(mode === 'separate' ? 'exportCenter.rangeSeparate' : 'exportCenter.rangeMerged')}</span>
+ <span className="text-[11px] leading-snug text-[var(--text-faint)]">{t(mode === 'separate' ? 'exportCenter.rangeSeparateHint' : 'exportCenter.rangeMergedHint')}</span>
+ </button>)}
+ </div>
+ </div>
+ </aside>
+ </div>
+ );
+}
diff --git a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx
index fb44d65..3ac5b62 100644
--- a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx
+++ b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx
@@ -59,7 +59,7 @@ const SECTION_WORDS: Record<SettingsSection, string | string[]> = {
models: 'settings.models',
developer: ['settings.developer', 'settings.report'],
shortcuts: 'settings.shortcuts',
- advanced: ['settings.advanced', 'settings.playback'],
+ advanced: ['settings.advanced', 'settings.versions', 'settings.playback'],
};
export interface SettingsModalProps {
@@ -299,11 +299,37 @@ function PlaybackGroup() {
);
}
-/** What is already set for the best experience, for whoever wants it otherwise: how the preview plays (PlaybackGroup). */
+/**
+ * Versions saved on their own (studio/server/auto-versions.mjs): whether open projects save them while they are worked
+ * on. Showing these versions is controlled by the type filter in Version history.
+ */
+function VersionsGroup() {
+ const t = useT();
+ const [prefs, setPrefs] = React.useState<StudioPrefs | null>(null);
+ React.useEffect(() => { void api.prefs().then(setPrefs).catch(() => {}); }, []);
+ if (!prefs) return null;
+ const change = (patch: { autoVersions?: boolean }) => {
+ setPrefs({ ...prefs, ...patch });
+ void api.setPrefs(patch).then(setPrefs).catch(() => setPrefs(prefs));
+ };
+ return (
+ <SettingsGroup title={t('settings.versions.group')}>
+ <SettingsItem
+ title={t('settings.versions.auto')}
+ description={t('settings.versions.autoHint')}
+ control={<SettingsSwitch checked={prefs.autoVersions === true} onChange={(on) => change({ autoVersions: on })} label={t('settings.versions.auto')} />}
+ />
+ </SettingsGroup>
+ );
+}
+
+/** What is already set for the best experience, for whoever wants it otherwise: versions saved on their own
+ * (VersionsGroup), how the preview plays (PlaybackGroup). */
function AdvancedSection() {
const t = useT();
return (
<SettingsPage note={t('settings.advanced.intro')}>
+ <VersionsGroup />
<PlaybackGroup />
</SettingsPage>
);
diff --git a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx
index a768b4d..c981460 100644
--- a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx
+++ b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx
@@ -7,7 +7,7 @@
import * as React from 'react';
import { AudioLines, HardDriveUpload, Replace, Snowflake } from 'lucide-react';
-import { api, type Clip, type Film, type Op, type ProjectSettings } from '@/api';
+import { api, projectEvents, type Clip, type Film, type Op, type ProjectSettings } from '@/api';
import { useT } from '@/i18n';
import { canReplace, familyOfClip, replaceClip, type ReplaceFamily, type ReplaceFile } from '@/lib/clip-replace';
import { freezeSourceMs, planFreeze } from '@/lib/freeze-frame';
@@ -16,6 +16,7 @@ import {
addMarker, changeMarker, markerClip, nextMarker, parseMarkers, placeMarkers, removeMarker, type Marker, type PlacedMarker,
} from '@/lib/markers';
import type { ClipEdit } from '@/lib/film-clip-edits';
+import { historyMoved } from '@/lib/project-history';
import { heardClips, toggleSolo } from '@/lib/solo';
import type { EditModel } from '@/lib/timeline-edit';
import { readTimelinePrefs, switchesOf } from '@/lib/timeline-prefs';
@@ -80,8 +81,8 @@ export function useEditorTools({
const filmRef = React.useRef(film);
filmRef.current = film;
- /* ── markers: read once per project, written whole on each change (one at a time, in order), each change a step
- of the history (⌘Z puts the list back as it was) ── */
+ /* ── markers: read once per project and again when a version is restored, written whole on each change (one at a
+ time, in order), each change a step of the history (⌘Z puts the list back as it was) ── */
const [markers, setMarkers] = React.useState<Marker[]>([]);
const markersRef = React.useRef(markers);
markersRef.current = markers;
@@ -89,8 +90,10 @@ export function useEditorTools({
React.useEffect(() => {
let live = true;
setMarkers([]);
- void api.markers(projectId).then((raw) => { if (live) setMarkers(parseMarkers(raw)); }, () => {});
- return () => { live = false; };
+ const load = () => { void api.markers(projectId).then((raw) => { if (live) setMarkers(parseMarkers(raw)); }, () => {}); };
+ load();
+ const stop = projectEvents(projectId, (event) => { if (historyMoved(event)) load(); });
+ return () => { live = false; stop(); };
}, [projectId]);
const writeMarkers = React.useCallback((next: Marker[]): Promise<string | null> => {
setMarkers(next);
diff --git a/packages/openfilm/studio/ui/src/components/use-project-history.ts b/packages/openfilm/studio/ui/src/components/use-project-history.ts
index ae25fd5..37481e7 100644
--- a/packages/openfilm/studio/ui/src/components/use-project-history.ts
+++ b/packages/openfilm/studio/ui/src/components/use-project-history.ts
@@ -1,68 +1,75 @@
/**
* A project's version history and the actions on it, for the Version history panel.
*
- * const history = useProjectHistory(projectId, { onError: toast.showError, onMoved: reloadFilm });
+ * const history = useProjectHistory(projectId, { onError: toast.showError, beforeChange: film.settled });
* // on the project's `{ type: 'history' }` event: history.refresh()
- * <ProjectHistoryControls history={history} open={open} anchor={anchor} onClose={…} />
+ * <ProjectHistoryControls history={history} open={open} onClose={…} />
*
* It loads on mount (and when the project changes), after each of its own actions, and when `refresh()` is called.
- * An action answers with its outcome: refusals the panel asks about (uncommitted changes, a merge that collides, a
- * branch with commits on no other) come back to it; any other failure is said through `onError`.
+ * A failed action is said through `onError`, but a checkout refused for changes ('dirty'), which the panel asks about.
+ * A checkout or a discard tells every page of the project (`{ type: 'history', moved }`), which reads the film and
+ * Studio's state of it again (ProjectView).
*/
import React from 'react';
import { projectEvents } from '@/api';
import { useT } from '@/i18n';
import { historyApi, historyErrorKey, historyProgressOf, type HistoryProgress, type HistoryResult, type HistoryState } from '@/lib/project-history';
+/** How many versions the list asks for at a time. */
+const PAGE = 50;
+
export interface ProjectHistory {
/** null: not loaded yet. */
state: HistoryState | null;
+ /** The history could not be read (and none was shown yet): the panel says so and offers to try again. */
+ failed: boolean;
/** An action on its way: the panel waits. */
busy: string | null;
/** How far the action on its way is (or the history being loaded, when an older one is brought up to date). */
progress: HistoryProgress | null;
refresh: () => Promise<void>;
- commit: (message: string) => Promise<boolean>;
+ /** Older versions too, PAGE more. */
+ showMore: () => Promise<void>;
+ save: (message: string) => Promise<boolean>;
discard: () => Promise<boolean>;
- restore: (commit: string) => Promise<HistoryResult>;
- checkout: (o: { branch: string; create?: boolean; from?: string; carry?: 'leave' | 'bring' }) => Promise<HistoryResult<{ parkedBack?: boolean }>>;
- rename: (from: string, name: string) => Promise<boolean>;
- remove: (name: string, force?: boolean) => Promise<HistoryResult>;
- merge: (o: { branch: string; message: string; prefer?: 'ours' | 'theirs' }) => Promise<HistoryResult<{ merged?: boolean }>>;
+ checkout: (commit: string, discard?: boolean) => Promise<HistoryResult<{ commit: string; missing?: string[] }>>;
+ copy: (commit: string, name: string) => Promise<HistoryResult<{ project: { id: string; name: string }; missing?: string[] }>>;
+ delete: (commits: string[]) => Promise<boolean>;
+ recover: (commits: string[]) => Promise<boolean>;
}
-/** Refusals the panel asks the person about instead of saying them. */
-const ASKED = new Set(['dirty', 'conflict', 'unmerged']);
-
export function useProjectHistory(projectId: string, {
onError,
- onMoved,
- beforeCommit,
+ beforeChange,
}: {
/** A failed action, in a sentence for the person (show it as an error toast). */
onError: (message: string) => void;
- /** The folder now holds other files (gone back, switched, merged, discarded): reload the film. */
- onMoved?: () => void;
- /** Runs before committing: flush edits still waiting to be written, so the commit holds what the person sees. */
- beforeCommit?: () => Promise<unknown>;
+ /** Runs before committing, discarding or checking out: edits still waiting to be written land first, so the
+ * version holds what the person sees and a checkout is not undone by them. */
+ beforeChange?: () => Promise<unknown>;
}): ProjectHistory {
const t = useT();
const [state, setState] = React.useState<HistoryState | null>(null);
+ const [failed, setFailed] = React.useState(false);
const [busy, setBusy] = React.useState<string | null>(null);
const [progress, setProgress] = React.useState<HistoryProgress | null>(null);
/* a ref as well as state: a second click lands before React re-renders */
const inFlight = React.useRef(false);
+ const limit = React.useRef(PAGE);
const refresh = React.useCallback(async () => {
- const fresh = await historyApi.load(projectId);
+ const fresh = await historyApi.load(projectId, limit.current);
/* not loaded: keep what is shown; one hiccup should not empty the panel */
if (fresh) setState(fresh);
+ setFailed(!fresh);
/* loading may have brought an older history up to date, with progress of its own */
if (!inFlight.current) setProgress(null);
}, [projectId]);
React.useEffect(() => {
setState(null);
+ setFailed(false);
+ limit.current = PAGE;
void refresh();
}, [refresh]);
@@ -76,18 +83,14 @@ export function useProjectHistory(projectId: string, {
});
}, [projectId]);
- /**
- * Run one action at a time. `moves`: it changes the folder's files when it goes through. A refusal the panel asks
- * about comes back to it; any other is said.
- */
- const act = React.useCallback(async <T,>(name: string, run: () => Promise<HistoryResult<T>>, moves: boolean, asked = ASKED): Promise<HistoryResult<T>> => {
+ /** Run one action at a time; a refusal is said, except `quiet` codes the panel answers itself. */
+ const act = React.useCallback(async <T,>(name: string, run: () => Promise<HistoryResult<T>>, quiet: string[] = []): Promise<HistoryResult<T>> => {
if (inFlight.current) return { ok: false, status: 429, code: 'busy' };
inFlight.current = true;
setBusy(name);
try {
const result = await run();
- if (result.ok && moves) onMoved?.();
- if (!result.ok && !(result.code && asked.has(result.code))) onError(t(historyErrorKey(result)));
+ if (!result.ok && !(result.code && quiet.includes(result.code))) onError(t(historyErrorKey(result)));
await refresh();
return result;
} finally {
@@ -95,19 +98,20 @@ export function useProjectHistory(projectId: string, {
setBusy(null);
setProgress(null);
}
- }, [onMoved, onError, refresh, t]);
+ }, [onError, refresh, t]);
return {
state,
+ failed,
busy,
progress,
refresh,
- commit: async (message) => (await act('commit', async () => { await beforeCommit?.(); return historyApi.commit(projectId, message); }, false, new Set())).ok,
- discard: async () => (await act('discard', () => historyApi.discard(projectId), true, new Set())).ok,
- restore: (commit) => act('restore', () => historyApi.restore(projectId, commit), true),
- checkout: (o) => act('checkout', () => historyApi.checkout(projectId, o), true),
- rename: async (from, name) => (await act('rename', () => historyApi.rename(projectId, from, name), false, new Set())).ok,
- remove: (name, force) => act('remove', () => historyApi.remove(projectId, name, force), false),
- merge: (o) => act('merge', () => historyApi.merge(projectId, o), true),
+ showMore: async () => { limit.current += PAGE; await refresh(); },
+ save: async (message) => (await act('save', async () => { await beforeChange?.(); return historyApi.save(projectId, message); })).ok,
+ discard: async () => (await act('discard', async () => { await beforeChange?.(); return historyApi.discard(projectId); })).ok,
+ checkout: (commit, discard = false) => act('checkout', async () => { await beforeChange?.(); return historyApi.checkout(projectId, commit, discard); }, ['dirty']),
+ copy: (commit, name) => act('copy', () => historyApi.copy(projectId, commit, name)),
+ delete: async (commits) => (await act('delete', () => historyApi.delete(projectId, commits))).ok,
+ recover: async (commits) => (await act('recover', () => historyApi.recover(projectId, commits))).ok,
};
}
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index bd6a48d..ee7393e 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -97,7 +97,8 @@ export const en = {
eyebrow: 'Updated',
title: 'What’s new in OpenFilm {version}',
close: 'Close',
- changelog: 'Full changelog',
+ changelog: 'Releases on GitHub',
+ earlier: 'Earlier versions',
ok: 'Got it',
kind: {
new: 'New',
@@ -324,6 +325,12 @@ export const en = {
close: 'Close',
},
exportCenter: {
+ videoPreset: 'Preset',
+ presetDefault: 'Default',
+ platformPresets: 'Social media presets',
+ presetCustom: 'Custom',
+ presetDefaultHint: 'Uses the current frame and standard video settings.',
+ presetCustomHint: 'Settings adjusted. Keep editing or choose another preset.',
fpsProject: "project",
title: 'Export',
dest: {
@@ -333,7 +340,6 @@ export const en = {
audio: 'Audio',
subtitles: 'Subtitles',
images: 'Images',
- slides: 'Slides & PDF',
project: 'Project',
alpha: 'Transparent assets',
nle: 'Editing project',
@@ -344,20 +350,18 @@ export const en = {
gif: 'For docs, email, READMEs',
audio: 'Mix or separate stems',
subtitles: 'SRT, WebVTT, transcript',
- images: 'Poster and shot stills',
- slides: 'One slide per shot',
+ images: "Images, ZIP, PDF or PPTX",
project: 'The whole project, to hand on',
alpha: 'Alpha for AE, Final Cut, web',
nle: '{app}, Final Cut Pro, Premiere Pro, DaVinci Resolve',
},
destDesc: {
social: 'Pick one or more platforms. Each gets the right shape, size and frame rate, and they export in one go.',
- video: 'A single video with full control over codec, frame, resolution and quality.',
+ video: 'Start with Default or a social media preset, then adjust codec, frame, resolution and quality.',
gif: 'A looping animated image. Keep it short and small — GIFs grow fast.',
audio: 'The mixed soundtrack, or voice, music and effects as separate files for your own mix.',
subtitles: 'Caption files for YouTube, players and translators, or a plain transcript.',
- images: 'The poster, or one still per shot for thumbnails and social posts.',
- slides: 'A deck or PDF with one slide per shot — ready to present or print.',
+ images: "Pick frames from the film and save them as individual images, a ZIP, a PDF or a PowerPoint deck.",
project: 'The project itself — its film, pages and media, and the parts you choose — as a zip or a folder that opens in OpenFilm.',
alpha: 'Video with a transparent background — the whole film or a single element — to layer into your own edits, apps and websites.',
nle: 'The timeline itself, ready to keep cutting: a {app} draft or an XML your editor imports, each page as a clip with alpha, your footage and sounds on their own tracks.',
@@ -403,6 +407,12 @@ export const en = {
gifWidth: 'Size',
gifHint: 'Tip: pick a range of a few seconds. A 10-second GIF at 640px is usually a few MB.',
format: 'Format',
+ imageOutput: "Export type",
+ imageFormat: "Image format",
+ imageFiles: "Image files",
+ imageFilesHint: "One image file for each selected frame",
+ imageZipHint: "The selected images in one ZIP",
+ imagePageLimit: "PDF and PPTX support up to {n} frames. Select fewer frames.",
audioHint: {
wav: 'Lossless, for editing',
m4a: 'Small, high quality',
@@ -425,12 +435,6 @@ export const en = {
txt: 'Plain text for docs and translation',
},
captionCount: '{n} subtitle lines in this film.',
- poster: 'Poster',
- posterAt: 'Export the frame at {time}',
- posterMiddle: 'Export the frame from the middle',
- sceneStills: 'Shot stills',
- sceneStillsDesc: 'One image from the middle of each shot ({n} shots), zipped.',
- stills: 'Shot stills',
sequence: 'sequence',
slidesHint: {
pptx: 'Opens in PowerPoint, Keynote and Google Slides',
@@ -441,6 +445,37 @@ export const en = {
rangePart: 'A part',
rangeFrom: 'From',
rangeTo: 'To',
+ rangeBoundary: 'Choose a clip boundary',
+ rangeHint: 'Enter seconds (2.5), M:SS (00:02.500), H:MM:SS or a frame timecode (00:00:02:15).',
+ rangeInvalid: 'Enter valid times between 0 and {end} seconds, with the end after the start.',
+ rangeDelivery: "Delivery",
+ rangeSeparate: "Export each separately",
+ rangeMerged: "Merge into one file",
+ rangeSeparateHint: "Save each selected range as a separate file.",
+ rangeMergedHint: "Join in the list order below, keeping picture, sound and subtitles together.",
+ rangePreview: "Video range preview",
+ rangePreviewFailed: "The video preview could not load. You can still enter times to select ranges.",
+ rangeRetry: "Retry",
+ rangePause: "Pause preview",
+ rangePlay: "Play this range",
+ rangePreviousFrame: "Previous frame",
+ rangeNextFrame: "Next frame",
+ rangeUnmute: "Unmute",
+ rangeMute: "Mute",
+ rangeSetStart: "Set start here",
+ rangeSetEnd: "Set end here",
+ rangeSeek: "Seek preview",
+ rangeSelected: "Selected ranges",
+ rangeSegment: "Range {n}",
+ rangeDragStart: "Drag start",
+ rangeDragEnd: "Drag end",
+ rangeCount: "{n} ranges selected · up to 100",
+ rangeAdd: "Add range",
+ rangeInvalidSegment: "Adjust the start and end",
+ rangeRemove: "Remove range {n}",
+ rangePickOne: "Add at least one export range.",
+ rangeStripHint: "The strip seeks without switching the selected range. Drag the current range’s edges to trim; ⌘/Ctrl + wheel zooms, swipe sideways to pan.",
+ rangeCardsHint: "Click a selected clip to preview and edit it. Exports follow the list order.",
saveTo: 'Save to',
fileName: 'Name',
change: 'Change…',
@@ -451,6 +486,35 @@ export const en = {
emptyFilm: 'The film is empty — add a clip first.',
missingMedia: '{n} media file(s) missing: {files}. Relink them first: right-click the red clip on the timeline.',
pickPreset: 'Pick at least one platform.',
+ summaryImage: '1 image',
+ summaryImages: '{n} images',
+ summaryImagesZip: '{n} images, in a zip',
+ summarySlide: '1 slide',
+ summarySlides: '{n} slides',
+ pickMoments: 'Pick at least one frame.',
+ moments: {
+ added: 'Added',
+ quick: 'Quick pick',
+ playhead: 'Playhead',
+ scenes: 'Middle of each shot',
+ markers: 'Each marker',
+ every: 'Every few seconds',
+ everyN: 'Every {s} s · {n} frames',
+ strip: 'The film',
+ hint: 'Click or drag to preview. Use “Add this frame” or Return to add it. Ctrl/⌘ + wheel or a pinch zooms; swipe sideways to scroll. ← → step a frame, Shift + ← → a second.',
+ add: 'Add this frame',
+ remove: 'Remove this frame',
+ picked: 'Picked · {n}',
+ clear: 'Clear',
+ none: 'No frames yet: preview a moment, then use “Add this frame” or Return.',
+ limit: 'At most {n}.',
+ noSubtitles: 'The pictures here leave out the burned-in subtitles; the exported files have them.',
+ selectHint: 'Click a frame to select it: its dot shows on the strip, to drag, or Alt + ← → moves it a frame. Click again to let it go.',
+ zoom: 'Zoom',
+ zoomIn: 'Zoom in',
+ zoomOut: 'Zoom out',
+ zoomFit: 'Show the whole film',
+ },
noCaptions: 'This film has no subtitles.',
noAudio: 'This film has no sound.',
noFolder: 'Choose where to save first.',
@@ -638,98 +702,122 @@ export const en = {
daysAgo: '{n}d ago',
},
versions: {
+ savedVersions: "Saved versions",
+ deletedVersions: "Deleted",
+ selectVersions: "Select versions",
+ cancelSelection: "Cancel selection",
+ selectVersion: "Select version: {name}",
+ selectVisible: "Select listed",
+ clearSelection: "Clear selection",
+ selectionCount: "{n} selected",
+ deleteSelected: "Delete selected",
+ deleteVersion: "Delete version",
+ deleteTitle: "Delete {n} version(s)?",
+ deleteBody: "Selected versions move to Deleted and can be recovered later. Your current film, unsaved edits, media and other versions stay unchanged.",
+ deleteConfirm: "Move to Deleted",
+ deletedRecords: "Moved {n} version(s) to Deleted.",
+ recoverRecords: "Recover records",
+ recoveredRecords: "Recovered {n} version(s) to the history list.",
+ noDeletedVersions: "No deleted versions.",
+ deletedPreviewHint: "These records were removed from the history list. Snapshots are retained for recovery. Recover a record to preview or use it again.",
+ errorDeleteCurrent: "The version currently in use cannot be deleted.",
+ errorDeleted: "This version was deleted. Recover its record from Deleted first.",
+ search: 'Search versions',
+ filterVersions: 'Filter versions',
+ versionTypes: 'Version types',
+ typeManual: 'Manual save',
+ typeAuto: 'Auto-saved',
+ typeRestore: 'Restore',
+ typeOther: 'Other records',
+ namedOnly: 'Named versions only',
+ showAllTypes: 'Show all types',
+ matchesSaved: 'Matches the last saved version',
+ inUse: 'In use',
+ noMatchingVersions: 'No matching versions',
+ resetFilters: 'Clear search and filters',
+ previewFailed: 'This version could not be previewed. Try again.',
+ previewLoading: 'Loading this version…',
+ previewMissing: '{n} media files are missing from this version. The rest can still be previewed.',
+ videoPreview: 'Version video preview',
+ play: 'Play',
+ pause: 'Pause',
+ seek: 'Playback position',
+ mute: 'Mute',
+ unmute: 'Unmute',
+ today: 'Today',
+ yesterday: 'Yesterday',
+ workingCopy: 'Current edits',
+ workingCopyHint: 'Your current work. Save a version to return to it later.',
+ unsavedFiles: 'Changed files: {n}',
+ lastSaved: 'Last saved',
+ restored: 'Version restored.',
+ saveVersion: 'Save version',
+ saveTitle: 'Save this version',
+ saveBody: 'Add a name to help you find this point later. The name is optional.',
+ restore: 'Restore this version',
+ restoreTitle: 'Restore “{name}”?',
+ restoreBody: 'The project will return to this version. Your other saved versions will remain available.',
+ saveRestoreBody: 'Your current edits will be saved as a version first, so you can return to them later.',
+ saveAndRestore: 'Save current edits and restore',
+ namePlaceholder: 'Version name (optional)',
+ allVersions: 'All versions',
+ namedVersions: 'Named',
+ fileChanges: 'File changes',
+ sinceSaved: 'Since the last saved version',
+ sincePrevious: 'Compared with its previous version',
+ filesFailed: 'File changes could not be loaded.',
+ previewHint: 'Previewing this version leaves your current edits unchanged.',
+ fileAdded: 'Added',
+ fileModified: 'Modified',
+ fileDeleted: 'Deleted',
title: 'Version history',
close: 'Close',
working: 'Working…',
- branchOf: 'Branch: {branch}',
- branches: 'Branches',
- branchCount: '{n} branches',
- branchCountOne: '1 branch',
- newBranch: 'New branch',
- newBranchTitle: 'New branch',
- newBranchBody: 'Starts from where “{branch}” is now. Your uncommitted changes come along.',
- newBranchBodyClean: 'Starts from where “{branch}” is now.',
- newBranchFromTitle: 'New branch from “{name}”',
- newBranchFromBody: 'Starts from this version; “{branch}” stays as it is.',
- branchName: 'Branch name',
- create: 'Create',
- switchTitle: 'Switch to “{name}”?',
- switchBody: 'You have uncommitted changes on “{branch}”.',
- leaveChanges: 'Leave them on {branch}',
- bringChanges: 'Bring them to {name}',
- cancel: 'Cancel',
- rename: 'Rename',
- renameTitle: 'Rename “{name}”',
- save: 'Save',
- delete: 'Delete',
- deleteTitle: 'Delete branch “{name}”?',
- deleteBody: 'The branch goes. Its versions stay on every other branch that has them.',
- deleteForceTitle: 'Delete “{name}” and its versions?',
- deleteForceBody: '{n} versions on “{name}” are on no other branch. Deleting it loses them for good.',
- deleteForceBodyOne: '1 version on “{name}” is on no other branch. Deleting it loses it for good.',
- deleteForce: 'Delete anyway',
- mergeInto: 'Merge into {branch}',
- mergeTitle: 'Merge “{name}” into “{branch}”',
- mergeBody: 'What was done on “{name}” comes into “{branch}”.',
- mergeMessage: 'Merge {name}',
- mergeConfirm: 'Merge',
- mergeConflictTitle: '“{name}” and “{branch}” changed the same thing',
- mergeConflictBody: 'Choose whose version wins where they differ. Everything else from both is kept.',
- keepOurs: 'Keep {branch}’s',
- keepTheirs: 'Use {name}’s',
- nothingToMerge: '“{branch}” already has everything on “{name}”.',
- current: 'Current',
- parked: 'changes left here',
- parkedStuck: 'The changes left on this branch collide with it now, so they are still put away.',
- changesTitle: 'Uncommitted changes',
- noChanges: 'Everything is committed',
- firstCommitHint: 'Nothing is committed yet. A commit keeps the film as it is now, so you can always come back to it.',
- messagePlaceholder: 'Describe this version (required)',
+ messagePlaceholder: 'Message (⌘↵ to commit)',
commit: 'Commit',
- discard: 'Discard changes',
- discardTitle: 'Discard all uncommitted changes?',
- discardBody: `The film goes back to its last commit. Files added since move to ${TRASH}.`,
- historyOf: 'History · {branch}',
- restore: 'Restore this version',
- restoreTitle: 'Restore “{name}”?',
- restoreBody: 'The film becomes this version, as uncommitted changes: commit them to keep it, or discard them to come back.',
- restoreDirtyBody: `You have uncommitted changes. Restoring discards them first (files added since move to ${TRASH}).`,
- restoreDiscard: 'Discard and restore',
- restoreConfirm: 'Restore',
- restoredMessage: 'Back to “{name}”',
- branchFrom: 'New branch from here',
+ changes: 'Changes',
+ discardAll: 'Discard all changes',
+ noChanges: 'No changes',
+ moreFiles: 'and {n} more',
+ graph: 'Graph',
+ noVersions: 'No saved versions yet',
+ current: 'Current',
+ checkout: 'Checkout',
+ copy: 'Save as new project',
moreActions: 'More',
- scenesAdded: '{n} scenes added',
- scenesAddedOne: '1 scene added',
- scenesEdited: '{n} scenes edited',
- scenesEditedOne: '1 scene edited',
- scenesRemoved: '{n} scenes removed',
- scenesRemovedOne: '1 scene removed',
- soundsAdded: '{n} sounds added',
- soundsAddedOne: '1 sound added',
- soundsEdited: '{n} sounds edited',
- soundsEditedOne: '1 sound edited',
- soundsRemoved: '{n} sounds removed',
- soundsRemovedOne: '1 sound removed',
- look: 'Look changed',
- same: 'No change to the film',
- errorDirty: 'Commit or discard the uncommitted changes first.',
- errorNothing: 'There is nothing to commit.',
- errorCarry: 'Your changes collide with what that branch holds. Leave them on this branch instead.',
- errorExists: 'A branch with that name exists already.',
- errorName: 'That can’t be a branch name.',
- errorMessage: 'Describe the version first.',
- errorCurrent: 'That’s the branch you’re on.',
+ showMore: 'Show older versions',
+ dirtyTitle: 'You have uncommitted changes',
+ dirtyBody: 'Commit them first, or discard them and check out “{name}”.',
+ discardAndCheckout: 'Discard and check out',
+ discardTitle: 'Discard all changes?',
+ discardBody: `The film returns to the last saved version. Files added since move to ${TRASH}.`,
+ discardConfirm: 'Discard all changes',
+ copyTitle: 'Make a copy of “{name}”',
+ copyBody: 'A new project starts from this version. This project stays as it is.',
+ copyName: 'Project name',
+ copyDefault: '{project} – {name}',
+ copyConfirm: 'Create project',
+ cancel: 'Cancel',
+ missing: 'Restored, but some media of that version could not be found; those files were left as they are.',
+ kindSaved: 'Saved version',
+ kindAuto: 'Auto-saved',
+ kindAgent: 'Before agent’s turn',
+ kindBeforeRestore: 'Before restoring',
+ kindRestore: 'Restored “{name}”',
+ kindRestoreAt: 'Restored the version from {time}',
+ kindRestoreOlder: 'Restored an earlier version',
+ kindUpgrade: 'Kept all the project’s files',
+ kindParked: 'Changes left on “{name}”',
+ loadFailed: 'Version history couldn’t be read. Try again; if it keeps failing, restart OpenFilm.',
+ retry: 'Try again',
+ errorNothing: 'There are no changes to save.',
+ errorDirty: 'Commit or discard the changes first.',
errorUnavailable: 'Version history is unavailable right now. Please try again later.',
errorGeneric: 'That did not go through. Please try again.',
progressScan: 'Reading the film’s files… {done} of {total}',
progressStore: 'Keeping media… {done} of {total}',
progressWrite: 'Writing files… {done} of {total}',
progressMigrate: 'Updating this project’s history… {done} of {total}',
- heldFiles: 'In history: {n} files the film uses',
- heldFilesOne: 'In history: 1 file the film uses',
- ignoredFiles: 'Not in history: {n} files not used by the film',
- ignoredFilesOne: 'Not in history: 1 file not used by the film',
},
stageMenu: {
align: "Align",
@@ -1551,6 +1639,11 @@ export const en = {
proxySize: "Proxy size",
proxySizeHint: "Smaller plays more smoothly; larger looks sharper in the viewer.",
},
+ versions: {
+ group: 'Versions',
+ auto: 'Auto versions',
+ autoHint: 'Commit a version on its own while you work: before and after an agent’s turn, and when the film rests for a couple of minutes. Only when the film changed.',
+ },
advanced: {
intro: "These are set for the best experience. You don’t need to change them.",
fitPages: "Draw pages at the viewer’s size",
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index da260cb..27382e0 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -96,7 +96,8 @@ export const es: Words = {
eyebrow: 'Actualizado',
title: 'Novedades de OpenFilm {version}',
close: 'Cerrar',
- changelog: 'Registro completo de cambios',
+ changelog: 'Versiones en GitHub',
+ earlier: 'Versiones anteriores',
ok: 'Entendido',
kind: {
new: 'Nuevo',
@@ -323,6 +324,12 @@ export const es: Words = {
close: 'Cerrar',
},
exportCenter: {
+ videoPreset: 'Preajuste',
+ presetDefault: 'Predeterminado',
+ platformPresets: 'Preajustes de redes sociales',
+ presetCustom: 'Personalizado',
+ presetDefaultHint: 'Usa el encuadre actual y los ajustes de vídeo estándar.',
+ presetCustomHint: 'Ajustes modificados. Puedes seguir editando o elegir otro preajuste.',
fpsProject: "proyecto",
title: 'Exportar',
dest: {
@@ -332,7 +339,6 @@ export const es: Words = {
audio: 'Audio',
subtitles: 'Subtítulos',
images: 'Imágenes',
- slides: 'Diapositivas y PDF',
project: 'Proyecto',
alpha: 'Recursos con transparencia',
nle: 'Proyecto de edición',
@@ -343,8 +349,7 @@ export const es: Words = {
gif: 'Para documentos, correo, READMEs',
audio: 'Mezcla o stems por separado',
subtitles: 'SRT, WebVTT, transcripción',
- images: 'Póster y fotogramas de cada plano',
- slides: 'Una diapositiva por plano',
+ images: "Imágenes, ZIP, PDF o PPTX",
project: 'El proyecto entero, para pasarlo',
alpha: 'Alfa para AE, Final Cut, web',
nle: '{app}, Final Cut Pro, Premiere Pro, DaVinci Resolve',
@@ -355,8 +360,7 @@ export const es: Words = {
gif: 'Una imagen animada en bucle. Mantenlo corto y pequeño: los GIF crecen rápido.',
audio: 'La banda sonora mezclada, o la voz, la música y los efectos como archivos separados para tu propia mezcla.',
subtitles: 'Archivos de subtítulos para YouTube, reproductores y traductores, o una transcripción en texto plano.',
- images: 'El póster, o un fotograma por plano para miniaturas y publicaciones en redes.',
- slides: 'Una presentación o PDF con una diapositiva por plano, lista para presentar o imprimir.',
+ images: "Elige fotogramas de la película y guárdalos como imágenes individuales, un ZIP, un PDF o una presentación de PowerPoint.",
project: 'El proyecto en sí —su película, páginas y medios, y las partes que elijas— como un zip o una carpeta que se abre en OpenFilm.',
alpha: 'Video con fondo transparente (la película entera o un solo elemento) para superponerlo en tus propias ediciones, apps y sitios web.',
nle: 'La propia línea de tiempo, lista para seguir editando: un borrador de {app} o un XML que importa tu editor, cada página como un clip con alfa, y tu metraje y sonidos en sus propias pistas.',
@@ -402,6 +406,12 @@ export const es: Words = {
gifWidth: 'Tamaño',
gifHint: 'Consejo: elige un intervalo de pocos segundos. Un GIF de 10 segundos a 640 px suele ocupar unos pocos MB.',
format: 'Formato',
+ imageOutput: "Tipo de exportación",
+ imageFormat: "Formato de imagen",
+ imageFiles: "Imágenes",
+ imageFilesHint: "Un archivo de imagen por fotograma elegido",
+ imageZipHint: "Las imágenes elegidas en un ZIP",
+ imagePageLimit: "PDF y PPTX admiten hasta {n} fotogramas. Selecciona menos.",
audioHint: {
wav: 'Sin pérdida, para editar',
m4a: 'Pequeño y de alta calidad',
@@ -424,12 +434,6 @@ export const es: Words = {
txt: 'Texto plano para documentos y traducción',
},
captionCount: '{n} líneas de subtítulos en esta película.',
- poster: 'Póster',
- posterAt: 'Exportar el fotograma en {time}',
- posterMiddle: 'Exportar el fotograma central',
- sceneStills: 'Fotogramas de los planos',
- sceneStillsDesc: 'Una imagen del centro de cada plano ({n} planos), en un ZIP.',
- stills: 'Fotogramas de los planos',
sequence: 'secuencia',
slidesHint: {
pptx: 'Se abre en PowerPoint, Keynote y Google Slides',
@@ -440,6 +444,37 @@ export const es: Words = {
rangePart: 'Una parte',
rangeFrom: 'Desde',
rangeTo: 'Hasta',
+ rangeBoundary: 'Elegir un límite de clip',
+ rangeHint: 'Introduce segundos (2.5), M:SS (00:02.500), H:MM:SS o un código de tiempo por fotogramas (00:00:02:15).',
+ rangeInvalid: 'Introduce tiempos válidos entre 0 y {end} segundos, con el final después del inicio.',
+ rangeDelivery: "Entrega",
+ rangeSeparate: "Exportar por separado",
+ rangeMerged: "Unir en un archivo",
+ rangeSeparateHint: "Guarda cada intervalo seleccionado en un archivo independiente.",
+ rangeMergedHint: "Une los intervalos en el orden de la lista, con imagen, sonido y subtítulos.",
+ rangePreview: "Vista previa del intervalo",
+ rangePreviewFailed: "No se pudo cargar la vista previa. Puedes introducir los tiempos para seleccionar intervalos.",
+ rangeRetry: "Reintentar",
+ rangePause: "Pausar vista previa",
+ rangePlay: "Reproducir este intervalo",
+ rangePreviousFrame: "Fotograma anterior",
+ rangeNextFrame: "Fotograma siguiente",
+ rangeUnmute: "Activar sonido",
+ rangeMute: "Silenciar",
+ rangeSetStart: "Fijar inicio aquí",
+ rangeSetEnd: "Fijar final aquí",
+ rangeSeek: "Posición de vista previa",
+ rangeSelected: "Intervalos seleccionados",
+ rangeSegment: "Intervalo {n}",
+ rangeDragStart: "Arrastrar inicio",
+ rangeDragEnd: "Arrastrar final",
+ rangeCount: "{n} intervalos seleccionados · máximo 100",
+ rangeAdd: "Añadir intervalo",
+ rangeInvalidSegment: "Ajusta el inicio y el final",
+ rangeRemove: "Quitar intervalo {n}",
+ rangePickOne: "Añade al menos un intervalo de exportación.",
+ rangeStripHint: "La tira mueve la vista previa sin cambiar el intervalo seleccionado. Arrastra los extremos del intervalo actual para recortar; ⌘/Ctrl + rueda amplía, desliza lateralmente para desplazar.",
+ rangeCardsHint: "Haz clic en un clip para previsualizarlo y editarlo. Se exportan en el orden de la lista.",
saveTo: 'Guardar en',
fileName: 'Nombre',
change: 'Cambiar…',
@@ -450,6 +485,35 @@ export const es: Words = {
emptyFilm: 'La película está vacía: añade primero un clip.',
missingMedia: 'Faltan {n} archivos de medios: {files}. Vuelve a vincularlos primero: clic derecho en el clip rojo de la línea de tiempo.',
pickPreset: 'Elige al menos una plataforma.',
+ summaryImage: '1 imagen',
+ summaryImages: '{n} imágenes',
+ summaryImagesZip: '{n} imágenes, en un ZIP',
+ summarySlide: '1 diapositiva',
+ summarySlides: '{n} diapositivas',
+ pickMoments: 'Elige al menos un fotograma.',
+ moments: {
+ added: 'Añadido',
+ quick: 'Selección rápida',
+ playhead: 'Cabezal',
+ scenes: 'Centro de cada plano',
+ markers: 'Cada marcador',
+ every: 'Cada pocos segundos',
+ everyN: 'Cada {s} s · {n} fotogramas',
+ strip: 'La película',
+ hint: 'Haz clic o arrastra para previsualizar. Usa «Añadir este fotograma» o Intro para añadirlo. Ctrl/⌘ + rueda o pellizcar hace zoom; desliza de lado para desplazarte. ← → avanzan un fotograma, Mayús + ← → un segundo.',
+ add: 'Añadir este fotograma',
+ remove: 'Quitar este fotograma',
+ picked: 'Elegidos · {n}',
+ clear: 'Borrar todo',
+ none: 'Aún no hay fotogramas: previsualiza y usa el botón de añadir o Intro.',
+ limit: 'Como máximo {n}.',
+ noSubtitles: 'Estas imágenes no muestran los subtítulos incrustados; los archivos exportados sí los llevan.',
+ selectHint: 'Haz clic en un fotograma para seleccionarlo: su punto aparece en la tira para arrastrarlo, o Alt + ← → lo mueve un fotograma. Otro clic lo suelta.',
+ zoom: 'Zoom',
+ zoomIn: 'Acercar',
+ zoomOut: 'Alejar',
+ zoomFit: 'Ver toda la película',
+ },
noCaptions: 'Esta película no tiene subtítulos.',
noAudio: 'Esta película no tiene sonido.',
noFolder: 'Elige primero dónde guardar.',
@@ -637,98 +701,122 @@ export const es: Words = {
daysAgo: 'hace {n} d',
},
versions: {
+ previewFailed: "No se pudo previsualizar esta versión. Inténtalo de nuevo.",
+ previewLoading: "Cargando esta versión…",
+ previewMissing: "Faltan {n} archivos multimedia en esta versión. El resto se puede previsualizar.",
+ videoPreview: "Vista previa del vídeo de la versión",
+ play: "Reproducir",
+ pause: "Pausa",
+ seek: "Posición de reproducción",
+ mute: "Silenciar",
+ unmute: "Activar sonido",
+ today: "Hoy",
+ yesterday: "Ayer",
+ workingCopy: "Edición actual",
+ workingCopyHint: "Tu trabajo actual. Guarda una versión para volver a él más adelante.",
+ unsavedFiles: "Archivos cambiados: {n}",
+ lastSaved: "Guardada por última vez",
+ restored: "Versión restaurada.",
+ saveVersion: "Guardar versión",
+ saveTitle: "Guardar esta versión",
+ saveBody: "Ponle un nombre para encontrar este punto más adelante. El nombre es opcional.",
+ restore: "Restaurar esta versión",
+ restoreTitle: "¿Restaurar «{name}»?",
+ restoreBody: "El proyecto volverá a esta versión. Tus otras versiones guardadas seguirán disponibles.",
+ saveRestoreBody: "Primero se guardará tu edición actual como una versión, para que puedas volver a ella más adelante.",
+ saveAndRestore: "Guardar la edición actual y restaurar",
+ namePlaceholder: "Nombre de la versión (opcional)",
+ allVersions: "Todas las versiones",
+ namedVersions: "Con nombre",
+ fileChanges: "Cambios de archivos",
+ sinceSaved: "Desde la última versión guardada",
+ sincePrevious: "Comparada con la versión anterior",
+ filesFailed: "No se pudieron cargar los cambios de archivos.",
+ previewHint: "Previsualizar esta versión no cambia tu edición actual.",
+ fileAdded: "Añadido",
+ fileModified: "Modificado",
+ fileDeleted: "Eliminado",
+ savedVersions: "Versiones guardadas",
+ deletedVersions: "Eliminadas",
+ selectVersions: "Seleccionar versiones",
+ cancelSelection: "Cancelar selección",
+ selectVersion: "Seleccionar versión: {name}",
+ selectVisible: "Seleccionar lista",
+ clearSelection: "Quitar selección",
+ selectionCount: "{n} seleccionadas",
+ deleteSelected: "Eliminar selección",
+ deleteVersion: "Eliminar versión",
+ deleteTitle: "¿Eliminar {n} versiones?",
+ deleteBody: "Las versiones seleccionadas pasan a Eliminadas y se pueden recuperar después. Tu película actual, los cambios sin guardar, los medios y las demás versiones no cambian.",
+ deleteConfirm: "Mover a Eliminadas",
+ deletedRecords: "Se movieron {n} versiones a Eliminadas.",
+ recoverRecords: "Recuperar registros",
+ recoveredRecords: "Se recuperaron {n} versiones en la lista.",
+ noDeletedVersions: "No hay versiones eliminadas.",
+ deletedPreviewHint: "Los registros se quitaron de la lista. Las instantáneas se conservan para recuperarlas. Recupera un registro para previsualizarlo o volver a usarlo.",
+ errorDeleteCurrent: "La versión en uso no se puede eliminar.",
+ errorDeleted: "Esta versión fue eliminada. Recupera primero su registro desde Eliminadas.",
+ search: 'Buscar versiones',
+ filterVersions: 'Filtrar versiones',
+ versionTypes: 'Tipos de versión',
+ typeManual: 'Guardado manual',
+ typeAuto: 'Guardado automático',
+ typeRestore: 'Restauración',
+ typeOther: 'Otros registros',
+ namedOnly: 'Solo versiones con nombre',
+ showAllTypes: 'Mostrar todos los tipos',
+ matchesSaved: 'Sin cambios desde el último guardado',
+ inUse: 'En uso',
+ noMatchingVersions: 'No hay versiones coincidentes',
+ resetFilters: 'Borrar búsqueda y filtros',
title: 'Historial de versiones',
close: 'Cerrar',
working: 'Trabajando…',
- branchOf: 'Rama: {branch}',
- branches: 'Ramas',
- branchCount: '{n} ramas',
- branchCountOne: '1 rama',
- newBranch: 'Nueva rama',
- newBranchTitle: 'Nueva rama',
- newBranchBody: 'Empieza donde está “{branch}” ahora. Tus cambios sin confirmar vienen con ella.',
- newBranchBodyClean: 'Empieza donde está “{branch}” ahora.',
- newBranchFromTitle: 'Nueva rama desde “{name}”',
- newBranchFromBody: 'Empieza en esta versión; “{branch}” queda como está.',
- branchName: 'Nombre de la rama',
- create: 'Crear',
- switchTitle: '¿Cambiar a “{name}”?',
- switchBody: 'Tienes cambios sin confirmar en “{branch}”.',
- leaveChanges: 'Dejarlos en {branch}',
- bringChanges: 'Llevarlos a {name}',
- cancel: 'Cancelar',
- rename: 'Renombrar',
- renameTitle: 'Renombrar “{name}”',
- save: 'Guardar',
- delete: 'Eliminar',
- deleteTitle: '¿Eliminar la rama “{name}”?',
- deleteBody: 'La rama se va. Sus versiones siguen en cada otra rama que las tenga.',
- deleteForceTitle: '¿Eliminar “{name}” y sus versiones?',
- deleteForceBody: '{n} versiones de “{name}” no están en ninguna otra rama. Si la eliminas, se pierden para siempre.',
- deleteForceBodyOne: '1 versión de “{name}” no está en ninguna otra rama. Si la eliminas, se pierde para siempre.',
- deleteForce: 'Eliminar igualmente',
- mergeInto: 'Fusionar en {branch}',
- mergeTitle: 'Fusionar “{name}” en “{branch}”',
- mergeBody: 'Lo hecho en “{name}” entra en “{branch}”.',
- mergeMessage: 'Fusionar {name}',
- mergeConfirm: 'Fusionar',
- mergeConflictTitle: '“{name}” y “{branch}” cambiaron lo mismo',
- mergeConflictBody: 'Elige qué versión gana donde difieren. Todo lo demás de ambas se conserva.',
- keepOurs: 'Quedarse con {branch}',
- keepTheirs: 'Usar {name}',
- nothingToMerge: '“{branch}” ya tiene todo lo de “{name}”.',
- current: 'Actual',
- parked: 'cambios guardados aquí',
- parkedStuck: 'Los cambios guardados en esta rama chocan ahora con ella, así que siguen apartados.',
- changesTitle: 'Cambios sin confirmar',
- noChanges: 'Todo está confirmado',
- firstCommitHint: 'Aún no hay nada confirmado. Una confirmación guarda la película tal como está, para que siempre puedas volver.',
- messagePlaceholder: 'Describe esta versión (obligatorio)',
+ messagePlaceholder: 'Mensaje (⌘↵ para confirmar)',
commit: 'Confirmar',
- discard: 'Descartar cambios',
- discardTitle: '¿Descartar todos los cambios sin confirmar?',
- discardBody: `La película vuelve a su última confirmación. Los archivos añadidos desde entonces van a ${TRASH}.`,
- historyOf: 'Historial · {branch}',
- restore: 'Restaurar esta versión',
- restoreTitle: '¿Restaurar “{name}”?',
- restoreBody: 'La película pasa a ser esta versión, como cambios sin confirmar: confírmalos para quedártela o descártalos para volver.',
- restoreDirtyBody: `Tienes cambios sin confirmar. Restaurar los descarta primero (los archivos añadidos van a ${TRASH}).`,
- restoreDiscard: 'Descartar y restaurar',
- restoreConfirm: 'Restaurar',
- restoredMessage: 'Vuelta a “{name}”',
- branchFrom: 'Nueva rama desde aquí',
+ changes: 'Cambios',
+ discardAll: 'Descartar todos los cambios',
+ noChanges: 'No hay cambios',
+ moreFiles: 'y {n} más',
+ graph: 'Gráfico',
+ noVersions: 'Aún no hay confirmaciones',
+ current: 'Actual',
+ checkout: 'Desproteger',
+ copy: 'Hacer una copia',
moreActions: 'Más',
- scenesAdded: '{n} escenas añadidas',
- scenesAddedOne: '1 escena añadida',
- scenesEdited: '{n} escenas editadas',
- scenesEditedOne: '1 escena editada',
- scenesRemoved: '{n} escenas quitadas',
- scenesRemovedOne: '1 escena quitada',
- soundsAdded: '{n} sonidos añadidos',
- soundsAddedOne: '1 sonido añadido',
- soundsEdited: '{n} sonidos editados',
- soundsEditedOne: '1 sonido editado',
- soundsRemoved: '{n} sonidos quitados',
- soundsRemovedOne: '1 sonido quitado',
- look: 'Cambió el aspecto',
- same: 'Sin cambios en la película',
- errorDirty: 'Primero confirma o descarta los cambios sin confirmar.',
- errorNothing: 'No hay nada que confirmar.',
- errorCarry: 'Tus cambios chocan con lo que tiene esa rama. Mejor déjalos en esta rama.',
- errorExists: 'Ya existe una rama con ese nombre.',
- errorName: 'Ese nombre no sirve para una rama.',
- errorMessage: 'Primero describe la versión.',
- errorCurrent: 'Ya estás en esa rama.',
+ showMore: 'Mostrar versiones anteriores',
+ dirtyTitle: 'Tienes cambios sin confirmar',
+ dirtyBody: 'Confírmalos primero, o descártalos y desprotege «{name}».',
+ discardAndCheckout: 'Descartar y desproteger',
+ discardTitle: '¿Descartar todos los cambios?',
+ discardBody: `La película vuelve a la versión desprotegida. Los archivos añadidos después se mueven a ${TRASH}.`,
+ discardConfirm: 'Descartar todos los cambios',
+ copyTitle: 'Hacer una copia de «{name}»',
+ copyBody: 'Un proyecto nuevo empieza desde esta versión. Este proyecto queda como está.',
+ copyName: 'Nombre del proyecto',
+ copyDefault: '{project} – {name}',
+ copyConfirm: 'Hacer una copia',
+ cancel: 'Cancelar',
+ missing: 'Se restauró, pero no se encontraron algunos medios de esa versión; esos archivos se dejaron como estaban.',
+ kindSaved: 'Versión guardada',
+ kindAuto: 'Guardada automáticamente',
+ kindAgent: 'Antes del turno del agente',
+ kindBeforeRestore: 'Antes de restaurar',
+ kindRestore: 'Restaurada «{name}»',
+ kindRestoreAt: 'Restaurada la versión de las {time}',
+ kindRestoreOlder: 'Restaurada una versión anterior',
+ kindUpgrade: 'Se guardan todos los archivos del proyecto',
+ kindParked: 'Cambios dejados en «{name}»',
+ loadFailed: 'No se pudo leer el historial de versiones. Inténtalo de nuevo; si sigue fallando, reinicia OpenFilm.',
+ retry: 'Reintentar',
+ errorNothing: 'No hay cambios que confirmar.',
+ errorDirty: 'Confirma o descarta los cambios primero.',
errorUnavailable: 'El historial de versiones no está disponible ahora. Inténtalo más tarde.',
errorGeneric: 'No se pudo hacer. Inténtalo de nuevo.',
progressScan: 'Leyendo los archivos de la película… {done} de {total}',
progressStore: 'Guardando los medios… {done} de {total}',
progressWrite: 'Escribiendo archivos… {done} de {total}',
progressMigrate: 'Actualizando el historial del proyecto… {done} de {total}',
- heldFiles: 'En el historial: {n} archivos que usa la película',
- heldFilesOne: 'En el historial: 1 archivo que usa la película',
- ignoredFiles: 'Fuera del historial: {n} archivos que la película no usa',
- ignoredFilesOne: 'Fuera del historial: 1 archivo que la película no usa',
},
stageMenu: {
align: 'Alinear',
@@ -1550,6 +1638,11 @@ export const es: Words = {
proxySize: "Tamaño del proxy",
proxySizeHint: "Más pequeño se reproduce con más fluidez; más grande se ve más nítido en el visor.",
},
+ versions: {
+ group: 'Versiones',
+ auto: 'Versiones automáticas',
+ autoHint: 'Confirma una versión por sí sola mientras trabajas: antes y después del turno de un agente, y cuando la película pasa un par de minutos sin cambios. Solo si la película cambió.',
+ },
advanced: {
intro: "Ya están ajustados para la mejor experiencia. Normalmente no hace falta cambiarlos.",
fitPages: "Dibujar las páginas al tamaño del visor",
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index 277ab71..1ce1fd8 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -96,7 +96,8 @@ export const ja: Words = {
eyebrow: 'アップデート済み',
title: 'OpenFilm {version} の新機能',
close: '閉じる',
- changelog: 'すべての変更履歴',
+ changelog: 'GitHub のリリース',
+ earlier: '以前のバージョン',
ok: 'OK',
kind: {
new: '新機能',
@@ -323,6 +324,12 @@ export const ja: Words = {
close: '閉じる',
},
exportCenter: {
+ videoPreset: 'プリセット',
+ presetDefault: 'デフォルト',
+ platformPresets: 'SNS プリセット',
+ presetCustom: 'カスタム',
+ presetDefaultHint: '現在のフレームと標準の動画設定を使います。',
+ presetCustomHint: '設定を調整済みです。続けて編集するか、別のプリセットを選べます。',
fpsProject: "プロジェクト",
title: '書き出し',
dest: {
@@ -332,7 +339,6 @@ export const ja: Words = {
audio: 'オーディオ',
subtitles: '字幕',
images: '画像',
- slides: 'スライド・PDF',
project: 'プロジェクト',
alpha: '透過素材',
nle: '編集プロジェクト',
@@ -343,8 +349,7 @@ export const ja: Words = {
gif: 'ドキュメント、メール、README 用',
audio: 'ミックスまたはステム別',
subtitles: 'SRT、WebVTT、書き起こし',
- images: 'ポスターとショットの静止画',
- slides: '1 ショット 1 スライド',
+ images: "画像・ZIP・PDF・PPTX",
project: 'プロジェクト全体を渡す',
alpha: 'AE、Final Cut、Web 用のアルファ付き',
nle: '{app}、Final Cut Pro、Premiere Pro、DaVinci Resolve',
@@ -355,8 +360,7 @@ export const ja: Words = {
gif: 'ループするアニメーション画像です。短く小さめに — GIF はすぐに大きくなります。',
audio: 'ミックス済みのサウンドトラック、または自分でミックスできるよう声・音楽・効果音を別ファイルで書き出します。',
subtitles: 'YouTube、プレーヤー、翻訳者向けの字幕ファイル、またはプレーンテキストの書き起こしです。',
- images: 'ポスター、またはサムネイルや SNS 投稿用にショットごとの静止画を 1 枚ずつ。',
- slides: '1 ショット 1 スライドのデッキまたは PDF — そのままプレゼンや印刷に使えます。',
+ images: "作品からフレームを選び、個別の画像、ZIP、PDF、PowerPoint として保存します。",
project: 'プロジェクトそのもの(フィルム、ページ、素材、選んだ部分)を、OpenFilm で開ける zip またはフォルダーとして書き出します。',
alpha: '背景が透明なビデオ — 映像全体または単一の要素 — を、自分の編集、アプリ、Web サイトに重ねて使えます。',
nle: 'タイムラインそのものを、編集を続けられる形で書き出します。{app} の下書き、または編集ソフトで読み込める XML。ページはそれぞれアルファ付きクリップとして、映像素材やサウンドは個別のトラックに配置されます。',
@@ -402,6 +406,12 @@ export const ja: Words = {
gifWidth: 'サイズ',
gifHint: 'ヒント:数秒の範囲を選んでください。640px で 10 秒の GIF は通常数 MB になります。',
format: 'フォーマット',
+ imageOutput: "書き出し形式",
+ imageFormat: "画像形式",
+ imageFiles: "画像ファイル",
+ imageFilesHint: "選んだフレームごとに画像を保存",
+ imageZipHint: "選んだ画像を 1 つの ZIP にまとめる",
+ imagePageLimit: "PDF と PPTX は最大 {n} フレームです。選択するフレームを減らしてください。",
audioHint: {
wav: 'ロスレス、編集向け',
m4a: '小さく高音質',
@@ -424,12 +434,6 @@ export const ja: Words = {
txt: 'ドキュメントや翻訳用のプレーンテキスト',
},
captionCount: 'この映像には {n} 行の字幕があります。',
- poster: 'ポスター',
- posterAt: '{time} のフレームを書き出す',
- posterMiddle: '中間のフレームを書き出す',
- sceneStills: 'ショットの静止画',
- sceneStillsDesc: '各ショットの中間から 1 枚ずつ({n} ショット)、ZIP にまとめます。',
- stills: 'ショットの静止画',
sequence: '連番',
slidesHint: {
pptx: 'PowerPoint、Keynote、Google スライドで開けます',
@@ -440,6 +444,37 @@ export const ja: Words = {
rangePart: '一部',
rangeFrom: '開始',
rangeTo: '終了',
+ rangeBoundary: 'クリップの境界を選択',
+ rangeHint: '秒数(2.5)、分:秒(00:02.500)、時:分:秒、フレームタイムコード(00:00:02:15)を入力できます。',
+ rangeInvalid: '0〜{end} 秒の有効な時刻を入力し、終了を開始より後にしてください。',
+ rangeDelivery: "書き出し方法",
+ rangeSeparate: "範囲ごとに書き出す",
+ rangeMerged: "1つのファイルに結合",
+ rangeSeparateHint: "選択した各範囲を個別のファイルに保存します。",
+ rangeMergedHint: "下のリスト順に映像・音声・字幕をつなぎ合わせます。",
+ rangePreview: "範囲の動画プレビュー",
+ rangePreviewFailed: "動画プレビューを読み込めません。時刻を入力して範囲を選択できます。",
+ rangeRetry: "再試行",
+ rangePause: "プレビューを一時停止",
+ rangePlay: "この範囲を再生",
+ rangePreviousFrame: "前のフレーム",
+ rangeNextFrame: "次のフレーム",
+ rangeUnmute: "ミュート解除",
+ rangeMute: "ミュート",
+ rangeSetStart: "ここを開始に設定",
+ rangeSetEnd: "ここを終了に設定",
+ rangeSeek: "プレビュー位置",
+ rangeSelected: "選択した範囲",
+ rangeSegment: "範囲 {n}",
+ rangeDragStart: "開始をドラッグ",
+ rangeDragEnd: "終了をドラッグ",
+ rangeCount: "{n} 範囲を選択 · 最大100",
+ rangeAdd: "範囲を追加",
+ rangeInvalidSegment: "開始と終了を調整してください",
+ rangeRemove: "範囲 {n} を削除",
+ rangePickOne: "書き出す範囲を1つ以上追加してください。",
+ rangeStripHint: "縮略条はプレビュー位置の移動のみで、選択範囲は切り替わりません。現在の範囲の両端をドラッグして調整。⌘/Ctrl + ホイールで拡大縮小、横スワイプで移動します。",
+ rangeCardsHint: "下のクリップをクリックしてプレビュー・編集します。リスト順に書き出します。",
saveTo: '保存先',
fileName: '名前',
change: '変更…',
@@ -450,6 +485,35 @@ export const ja: Words = {
emptyFilm: '映像が空です — 先にクリップを追加してください。',
missingMedia: 'メディアファイルが {n} 個見つかりません:{files}。先にタイムラインの赤いクリップを右クリックして再リンクしてください。',
pickPreset: 'プラットフォームを 1 つ以上選んでください。',
+ summaryImage: '画像 1 枚',
+ summaryImages: '画像 {n} 枚',
+ summaryImagesZip: '画像 {n} 枚(ZIP)',
+ summarySlide: '1 スライド',
+ summarySlides: '{n} スライド',
+ pickMoments: 'フレームを 1 つ以上選んでください。',
+ moments: {
+ added: '追加済み',
+ quick: 'クイック選択',
+ playhead: '再生ヘッド',
+ scenes: '各ショットの中間',
+ markers: '各マーカー',
+ every: '数秒ごと',
+ everyN: '{s} 秒ごと · {n} 枚',
+ strip: '作品',
+ hint: 'クリックやドラッグはプレビューのみです。「このフレームを追加」または Return で追加。Ctrl/⌘ + ホイールかピンチで拡大縮小、横スワイプでスクロール。← → で 1 フレーム、Shift + ← → で 1 秒。',
+ add: 'このフレームを追加',
+ remove: 'このフレームを削除',
+ picked: '選択中 · {n}',
+ clear: 'クリア',
+ none: 'まだフレームがありません。プレビューしてから追加ボタンか Return で追加してください。',
+ limit: '最大 {n} 枚です。',
+ noSubtitles: 'ここに表示される画像には焼き込み字幕が入りませんが、書き出したファイルには入ります。',
+ selectHint: 'フレームをクリックすると選択され、ストリップに点が出ます。ドラッグするか Alt + ← → で 1 フレームずつ動かせます。もう一度クリックで選択解除。',
+ zoom: 'ズーム',
+ zoomIn: '拡大',
+ zoomOut: '縮小',
+ zoomFit: '作品全体を表示',
+ },
noCaptions: 'この映像には字幕がありません。',
noAudio: 'この映像にはサウンドがありません。',
noFolder: '先に保存先を選んでください。',
@@ -637,98 +701,122 @@ export const ja: Words = {
daysAgo: '{n} 日前',
},
versions: {
+ previewFailed: "このバージョンをプレビューできませんでした。もう一度お試しください。",
+ previewLoading: "このバージョンを読み込んでいます…",
+ previewMissing: "このバージョンではメディアファイルが {n} 個見つかりません。残りはプレビューできます。",
+ videoPreview: "バージョンの動画プレビュー",
+ play: "再生",
+ pause: "一時停止",
+ seek: "再生位置",
+ mute: "ミュート",
+ unmute: "ミュート解除",
+ today: "今日",
+ yesterday: "昨日",
+ workingCopy: "現在の編集",
+ workingCopyHint: "今の作業内容です。バージョンとして保存すると、あとでいつでも戻れます。",
+ unsavedFiles: "変更されたファイル: {n}",
+ lastSaved: "最終保存",
+ restored: "バージョンを復元しました。",
+ saveVersion: "バージョンを保存",
+ saveTitle: "このバージョンを保存",
+ saveBody: "あとで見つけやすいように名前を付けられます。名前は省略できます。",
+ restore: "このバージョンを復元",
+ restoreTitle: "「{name}」を復元しますか?",
+ restoreBody: "プロジェクトはこのバージョンに戻ります。ほかの保存済みバージョンはそのまま残ります。",
+ saveRestoreBody: "まず現在の編集をバージョンとして保存するので、あとで戻れます。",
+ saveAndRestore: "現在の編集を保存して復元",
+ namePlaceholder: "バージョン名(任意)",
+ allVersions: "すべてのバージョン",
+ namedVersions: "名前付き",
+ fileChanges: "ファイルの変更",
+ sinceSaved: "最後に保存したバージョン以降",
+ sincePrevious: "ひとつ前のバージョンとの比較",
+ filesFailed: "ファイルの変更を読み込めませんでした。",
+ previewHint: "このバージョンをプレビューしても、現在の編集は変わりません。",
+ fileAdded: "追加",
+ fileModified: "変更",
+ fileDeleted: "削除",
+ savedVersions: "保存したバージョン",
+ deletedVersions: "削除済み",
+ selectVersions: "バージョンを選択",
+ cancelSelection: "選択を終了",
+ selectVersion: "バージョンを選択:{name}",
+ selectVisible: "一覧を全選択",
+ clearSelection: "選択を解除",
+ selectionCount: "{n} 件選択",
+ deleteSelected: "選択を削除",
+ deleteVersion: "このバージョンを削除",
+ deleteTitle: "{n} 件のバージョンを削除しますか?",
+ deleteBody: "選択したバージョンは「削除済み」に移動し、後で復元できます。現在の動画、未保存の変更、素材、他のバージョンは変わりません。",
+ deleteConfirm: "削除済みに移動",
+ deletedRecords: "{n} 件を「削除済み」に移動しました。",
+ recoverRecords: "記録を復元",
+ recoveredRecords: "{n} 件を履歴一覧に戻しました。",
+ noDeletedVersions: "削除済みのバージョンはありません。",
+ deletedPreviewHint: "記録は履歴一覧から削除されました。スナップショットは復元用に保持されます。復元すると再びプレビューや使用ができます。",
+ errorDeleteCurrent: "現在使用中のバージョンは削除できません。",
+ errorDeleted: "このバージョンは削除済みです。先に記録を復元してください。",
+ search: 'バージョンを検索',
+ filterVersions: 'バージョンを絞り込む',
+ versionTypes: 'バージョンの種類',
+ typeManual: '手動保存',
+ typeAuto: '自動保存',
+ typeRestore: '復元',
+ typeOther: 'その他',
+ namedOnly: '名前付きのみ',
+ showAllTypes: 'すべての種類を表示',
+ matchesSaved: '前回の保存内容と同じ',
+ inUse: '使用中',
+ noMatchingVersions: '該当するバージョンはありません',
+ resetFilters: '検索と絞り込みをクリア',
title: 'バージョン履歴',
close: '閉じる',
working: '処理中…',
- branchOf: 'ブランチ: {branch}',
- branches: 'ブランチ',
- branchCount: '{n} 個のブランチ',
- branchCountOne: '1 個のブランチ',
- newBranch: '新しいブランチ',
- newBranchTitle: '新しいブランチ',
- newBranchBody: '「{branch}」の現在の位置から始めます。コミットしていない変更も一緒に移ります。',
- newBranchBodyClean: '「{branch}」の現在の位置から始めます。',
- newBranchFromTitle: '「{name}」から新しいブランチ',
- newBranchFromBody: 'このバージョンから始めます。「{branch}」はそのままです。',
- branchName: 'ブランチ名',
- create: '作成',
- switchTitle: '「{name}」に切り替えますか?',
- switchBody: '「{branch}」にコミットしていない変更があります。',
- leaveChanges: '{branch} に残す',
- bringChanges: '{name} に持っていく',
- cancel: 'キャンセル',
- rename: '名前を変更',
- renameTitle: '「{name}」の名前を変更',
- save: '保存',
- delete: '削除',
- deleteTitle: 'ブランチ「{name}」を削除しますか?',
- deleteBody: 'ブランチは削除されます。ほかのブランチにあるバージョンはそのまま残ります。',
- deleteForceTitle: '「{name}」とそのバージョンを削除しますか?',
- deleteForceBody: '「{name}」の {n} 個のバージョンはほかのどのブランチにもありません。削除すると元に戻せません。',
- deleteForceBodyOne: '「{name}」の 1 個のバージョンはほかのどのブランチにもありません。削除すると元に戻せません。',
- deleteForce: '削除する',
- mergeInto: '{branch} にマージ',
- mergeTitle: '「{name}」を「{branch}」にマージ',
- mergeBody: '「{name}」での変更が「{branch}」に取り込まれます。',
- mergeMessage: '{name} をマージ',
- mergeConfirm: 'マージ',
- mergeConflictTitle: '「{name}」と「{branch}」が同じところを変更しています',
- mergeConflictBody: '違うところでどちらを残すか選んでください。それ以外は両方の変更を残します。',
- keepOurs: '{branch} のほうを残す',
- keepTheirs: '{name} のほうを使う',
- nothingToMerge: '「{branch}」には「{name}」の内容がすべて入っています。',
- current: '現在',
- parked: 'ここに残した変更あり',
- parkedStuck: 'このブランチに残した変更が今の内容と衝突するため、しまったままです。',
- changesTitle: 'コミットしていない変更',
- noChanges: 'すべてコミット済み',
- firstCommitHint: 'まだコミットがありません。コミットすると今の映像がバージョンとして残り、いつでも戻れます。',
- messagePlaceholder: 'このバージョンの説明(必須)',
+ messagePlaceholder: 'メッセージ(⌘↵ でコミット)',
commit: 'コミット',
- discard: '変更を破棄',
- discardTitle: 'コミットしていない変更をすべて破棄しますか?',
- discardBody: `映像は最後のコミットに戻ります。その後に追加したファイルは${TRASH}に移ります。`,
- historyOf: '履歴 · {branch}',
- restore: 'このバージョンに戻す',
- restoreTitle: '「{name}」に戻しますか?',
- restoreBody: '映像がこのバージョンになり、コミットしていない変更として表示されます。コミットすれば残り、破棄すれば今に戻ります。',
- restoreDirtyBody: `コミットしていない変更があります。戻す前にそれらを破棄します(追加したファイルは${TRASH}に移ります)。`,
- restoreDiscard: '破棄して戻す',
- restoreConfirm: '戻す',
- restoredMessage: '「{name}」に戻した',
- branchFrom: 'ここから新しいブランチ',
+ changes: '変更',
+ discardAll: 'すべての変更を破棄',
+ noChanges: '変更はありません',
+ moreFiles: 'ほか {n} 件',
+ graph: 'グラフ',
+ noVersions: 'まだコミットはありません',
+ current: '現在',
+ checkout: 'チェックアウト',
+ copy: 'コピーを作成',
moreActions: 'その他',
- scenesAdded: '{n} 個のシーンを追加',
- scenesAddedOne: '1 個のシーンを追加',
- scenesEdited: '{n} 個のシーンを編集',
- scenesEditedOne: '1 個のシーンを編集',
- scenesRemoved: '{n} 個のシーンを削除',
- scenesRemovedOne: '1 個のシーンを削除',
- soundsAdded: '{n} 個のサウンドを追加',
- soundsAddedOne: '1 個のサウンドを追加',
- soundsEdited: '{n} 個のサウンドを編集',
- soundsEditedOne: '1 個のサウンドを編集',
- soundsRemoved: '{n} 個のサウンドを削除',
- soundsRemovedOne: '1 個のサウンドを削除',
- look: '見た目を変更',
- same: '映像に変更なし',
- errorDirty: '先にコミットするか、コミットしていない変更を破棄してください。',
- errorNothing: 'コミットする変更がありません。',
- errorCarry: '変更がそのブランチの内容と衝突します。このブランチに残してください。',
- errorExists: '同じ名前のブランチがすでにあります。',
- errorName: 'その名前はブランチ名に使えません。',
- errorMessage: '先にバージョンの説明を入力してください。',
- errorCurrent: 'いまそのブランチにいます。',
+ showMore: '以前のバージョンを表示',
+ dirtyTitle: 'コミットしていない変更があります',
+ dirtyBody: '先にコミットするか、変更を破棄して「{name}」をチェックアウトしてください。',
+ discardAndCheckout: '破棄してチェックアウト',
+ discardTitle: 'すべての変更を破棄しますか?',
+ discardBody: `作品はチェックアウト中のバージョンに戻ります。あとから追加したファイルは${TRASH}に移動します。`,
+ discardConfirm: 'すべての変更を破棄',
+ copyTitle: '「{name}」のコピーを作成',
+ copyBody: 'このバージョンから新しいプロジェクトを始めます。このプロジェクトはそのままです。',
+ copyName: 'プロジェクト名',
+ copyDefault: '{project} – {name}',
+ copyConfirm: 'コピーを作成',
+ cancel: 'キャンセル',
+ missing: '復元しましたが、このバージョンの素材の一部が見つかりませんでした。それらのファイルはそのままです。',
+ kindSaved: '保存したバージョン',
+ kindAuto: '自動保存',
+ kindAgent: 'エージェントの作業前',
+ kindBeforeRestore: '復元する前',
+ kindRestore: '「{name}」を復元',
+ kindRestoreAt: '{time} のバージョンを復元',
+ kindRestoreOlder: '以前のバージョンを復元',
+ kindUpgrade: 'プロジェクトの全ファイルを保存',
+ kindParked: '「{name}」に残された変更',
+ loadFailed: 'バージョン履歴を読み込めませんでした。もう一度お試しください。続く場合は OpenFilm を再起動してください。',
+ retry: '再試行',
+ errorNothing: 'コミットする変更はありません。',
+ errorDirty: '先に変更をコミットするか破棄してください。',
errorUnavailable: 'バージョン履歴は現在利用できません。しばらくしてからもう一度お試しください。',
errorGeneric: 'うまくいきませんでした。もう一度お試しください。',
progressScan: '映像のファイルを読み込み中… {done}/{total}',
progressStore: 'メディアを保存中… {done}/{total}',
progressWrite: 'ファイルを書き込み中… {done}/{total}',
progressMigrate: 'このプロジェクトの履歴を更新中… {done}/{total}',
- heldFiles: '履歴に保存:映像が使う {n} 個のファイル',
- heldFilesOne: '履歴に保存:映像が使う 1 個のファイル',
- ignoredFiles: '履歴の対象外:映像が使わない {n} 個のファイル',
- ignoredFilesOne: '履歴の対象外:映像が使わない 1 個のファイル',
},
stageMenu: {
align: '整列',
@@ -1550,6 +1638,11 @@ export const ja: Words = {
proxySize: "プロキシのサイズ",
proxySizeHint: "小さいほど滑らかに再生でき、大きいほどビューアで鮮明に見えます。",
},
+ versions: {
+ group: 'バージョン',
+ auto: '自動バージョン',
+ autoHint: '作業中にバージョンを自動でコミットします。エージェントの作業の前後と、作品が数分変わらないとき。作品が変わったときだけです。',
+ },
advanced: {
intro: "最適な設定になっています。通常は変更する必要はありません。",
fitPages: "Web ページをビューアのサイズで描画",
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 07bb099..983be6d 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -93,7 +93,8 @@ export const ko: Words = {
eyebrow: '업데이트됨',
title: 'OpenFilm {version}의 새로운 기능',
close: '닫기',
- changelog: '전체 변경 내역',
+ changelog: 'GitHub 릴리스',
+ earlier: '이전 버전',
ok: '확인',
kind: {
new: '새 기능',
@@ -320,6 +321,12 @@ export const ko: Words = {
close: '닫기',
},
exportCenter: {
+ videoPreset: '프리셋',
+ presetDefault: '기본',
+ platformPresets: '소셜 미디어 프리셋',
+ presetCustom: '사용자 지정',
+ presetDefaultHint: '현재 화면 비율과 기본 동영상 설정을 사용합니다.',
+ presetCustomHint: '설정이 변경되었습니다. 계속 수정하거나 다른 프리셋을 선택하세요.',
fpsProject: "프로젝트",
title: '내보내기',
dest: {
@@ -329,7 +336,6 @@ export const ko: Words = {
audio: '오디오',
subtitles: '자막',
images: '이미지',
- slides: '슬라이드 및 PDF',
project: '프로젝트',
alpha: '투명 에셋',
nle: '편집 프로젝트',
@@ -340,8 +346,7 @@ export const ko: Words = {
gif: '문서, 이메일, README용',
audio: '믹스 또는 개별 스템',
subtitles: 'SRT, WebVTT, 대본',
- images: '포스터 및 샷 스틸',
- slides: '샷마다 슬라이드 1장',
+ images: "이미지, ZIP, PDF, PPTX",
project: '프로젝트 전체를 전달',
alpha: 'AE, Final Cut, 웹용 알파',
nle: '{app}, Final Cut Pro, Premiere Pro, DaVinci Resolve',
@@ -352,8 +357,7 @@ export const ko: Words = {
gif: '반복 재생되는 움직이는 이미지. 짧고 작게 유지하세요. GIF는 용량이 금방 커집니다.',
audio: '믹스된 사운드트랙, 또는 직접 믹스할 수 있도록 음성, 음악, 효과음을 개별 파일로.',
subtitles: 'YouTube, 플레이어, 번역가를 위한 자막 파일, 또는 일반 텍스트 대본.',
- images: '포스터, 또는 썸네일과 소셜 게시물용으로 샷마다 스틸 1장.',
- slides: '샷마다 슬라이드 1장으로 된 프레젠테이션 또는 PDF. 바로 발표하거나 인쇄할 수 있습니다.',
+ images: "영상에서 프레임을 골라 개별 이미지, ZIP, PDF 또는 PowerPoint로 저장합니다.",
project: '프로젝트 자체(영상, 페이지, 미디어, 선택한 부분)를 OpenFilm에서 바로 열 수 있는 zip 또는 폴더로 내보냅니다.',
alpha: '배경이 투명한 비디오(영상 전체 또는 요소 하나). 내 편집, 앱, 웹사이트에 레이어로 겹쳐 쓸 수 있습니다.',
nle: '계속 편집할 수 있는 타임라인 그 자체: {app} 초안 또는 편집 프로그램에서 가져올 수 있는 XML, 알파가 포함된 클립으로 된 각 페이지, 개별 트랙에 놓인 영상과 사운드.',
@@ -399,6 +403,12 @@ export const ko: Words = {
gifWidth: '크기',
gifHint: '팁: 몇 초 정도의 구간을 선택하세요. 640px의 10초 GIF는 보통 몇 MB입니다.',
format: '형식',
+ imageOutput: "내보내기 유형",
+ imageFormat: "이미지 형식",
+ imageFiles: "이미지 파일",
+ imageFilesHint: "선택한 프레임마다 이미지 파일로 저장",
+ imageZipHint: "선택한 이미지를 하나의 ZIP으로 묶기",
+ imagePageLimit: "PDF와 PPTX는 최대 {n}개 프레임을 지원합니다. 선택한 프레임 수를 줄여 주세요.",
audioHint: {
wav: '무손실, 편집용',
m4a: '작은 용량, 고품질',
@@ -421,12 +431,6 @@ export const ko: Words = {
txt: '문서 및 번역용 일반 텍스트',
},
captionCount: '이 영상에 자막 {n}줄이 있습니다.',
- poster: '포스터',
- posterAt: '{time} 프레임 내보내기',
- posterMiddle: '중간 프레임 내보내기',
- sceneStills: '샷 스틸',
- sceneStillsDesc: '각 샷의 중간에서 이미지 1장씩({n}개 샷), ZIP으로 압축.',
- stills: '샷 스틸',
sequence: '시퀀스',
slidesHint: {
pptx: 'PowerPoint, Keynote, Google Slides에서 열림',
@@ -437,6 +441,37 @@ export const ko: Words = {
rangePart: '일부 구간',
rangeFrom: '시작',
rangeTo: '끝',
+ rangeBoundary: '클립 경계 선택',
+ rangeHint: '초(2.5), 분:초(00:02.500), 시:분:초 또는 프레임 타임코드(00:00:02:15)를 입력하세요.',
+ rangeInvalid: '0~{end}초 사이의 유효한 시간을 입력하세요. 종료 시간은 시작 시간보다 뒤여야 합니다.',
+ rangeDelivery: "내보내기 방식",
+ rangeSeparate: "구간별로 내보내기",
+ rangeMerged: "하나의 파일로 합치기",
+ rangeSeparateHint: "선택한 각 구간을 개별 파일로 저장합니다.",
+ rangeMergedHint: "아래 목록 순서대로 영상, 소리, 자막을 함께 이어 붙입니다.",
+ rangePreview: "구간 영상 미리보기",
+ rangePreviewFailed: "영상 미리보기를 불러올 수 없습니다. 시간을 입력해 구간을 선택할 수 있습니다.",
+ rangeRetry: "다시 시도",
+ rangePause: "미리보기 일시 정지",
+ rangePlay: "이 구간 재생",
+ rangePreviousFrame: "이전 프레임",
+ rangeNextFrame: "다음 프레임",
+ rangeUnmute: "음소거 해제",
+ rangeMute: "음소거",
+ rangeSetStart: "여기를 시작으로",
+ rangeSetEnd: "여기를 끝으로",
+ rangeSeek: "미리보기 위치",
+ rangeSelected: "선택한 구간",
+ rangeSegment: "구간 {n}",
+ rangeDragStart: "시작점 드래그",
+ rangeDragEnd: "끝점 드래그",
+ rangeCount: "{n}개 구간 선택 · 최대 100개",
+ rangeAdd: "구간 추가",
+ rangeInvalidSegment: "시작과 끝을 조정하세요",
+ rangeRemove: "구간 {n} 삭제",
+ rangePickOne: "내보낼 구간을 하나 이상 추가하세요.",
+ rangeStripHint: "썸네일은 미리보기 위치만 이동하며 선택 구간을 바꾸지 않습니다. 현재 구간 양끝을 드래그해 조정하세요. ⌘/Ctrl + 휠로 확대하고 가로로 스와이프해 이동합니다.",
+ rangeCardsHint: "아래 클립을 클릭해 미리 보고 편집하세요. 목록 순서대로 내보냅니다.",
saveTo: '저장 위치',
fileName: '이름',
change: '변경…',
@@ -447,6 +482,35 @@ export const ko: Words = {
emptyFilm: '영상이 비어 있습니다. 먼저 클립을 추가하세요.',
missingMedia: '미디어 파일 {n}개가 없습니다: {files}. 먼저 타임라인의 빨간 클립을 오른쪽 클릭해 다시 연결하세요.',
pickPreset: '플랫폼을 하나 이상 선택하세요.',
+ summaryImage: '이미지 1장',
+ summaryImages: '이미지 {n}장',
+ summaryImagesZip: '이미지 {n}장, ZIP으로',
+ summarySlide: '슬라이드 1장',
+ summarySlides: '슬라이드 {n}장',
+ pickMoments: '프레임을 하나 이상 선택하세요.',
+ moments: {
+ added: '추가됨',
+ quick: '빠른 선택',
+ playhead: '재생 헤드',
+ scenes: '샷마다 중간',
+ markers: '마커마다',
+ every: '몇 초마다',
+ everyN: '{s}초마다 · {n}장',
+ strip: '영상',
+ hint: '클릭이나 드래그는 미리보기만 이동합니다. 프레임 추가 버튼이나 Enter로 추가하세요. Ctrl/⌘ + 휠이나 핀치로 확대·축소, 옆으로 쓸어 스크롤합니다. ← →는 한 프레임, Shift + ← →는 1초입니다.',
+ add: '이 프레임 추가',
+ remove: '이 프레임 제거',
+ picked: '선택됨 · {n}',
+ clear: '모두 지우기',
+ none: '아직 프레임이 없습니다. 미리 본 뒤 추가 버튼이나 Enter로 추가하세요.',
+ limit: '최대 {n}장입니다.',
+ noSubtitles: '여기 보이는 이미지에는 번인 자막이 없지만, 내보낸 파일에는 들어갑니다.',
+ selectHint: '프레임을 클릭하면 선택되고 스트립에 점이 나타납니다. 끌거나 Alt + ← →로 한 프레임씩 옮길 수 있습니다. 다시 클릭하면 선택이 풀립니다.',
+ zoom: '확대/축소',
+ zoomIn: '확대',
+ zoomOut: '축소',
+ zoomFit: '영상 전체 보기',
+ },
noCaptions: '이 영상에는 자막이 없습니다.',
noAudio: '이 영상에는 사운드가 없습니다.',
noFolder: '먼저 저장 위치를 선택하세요.',
@@ -634,98 +698,122 @@ export const ko: Words = {
daysAgo: '{n}일 전',
},
versions: {
+ previewFailed: "이 버전을 미리 볼 수 없습니다. 다시 시도하세요.",
+ previewLoading: "이 버전을 불러오는 중…",
+ previewMissing: "이 버전에서 미디어 파일 {n}개가 없습니다. 나머지는 미리 볼 수 있습니다.",
+ videoPreview: "버전 동영상 미리보기",
+ play: "재생",
+ pause: "일시정지",
+ seek: "재생 위치",
+ mute: "음소거",
+ unmute: "음소거 해제",
+ today: "오늘",
+ yesterday: "어제",
+ workingCopy: "현재 편집",
+ workingCopyHint: "지금 작업 중인 내용입니다. 버전으로 저장하면 나중에 다시 돌아올 수 있습니다.",
+ unsavedFiles: "변경된 파일: {n}개",
+ lastSaved: "마지막 저장",
+ restored: "버전을 복원했습니다.",
+ saveVersion: "버전 저장",
+ saveTitle: "이 버전 저장",
+ saveBody: "나중에 찾기 쉽도록 이름을 붙일 수 있습니다. 이름은 선택 사항입니다.",
+ restore: "이 버전 복원",
+ restoreTitle: "“{name}”을(를) 복원할까요?",
+ restoreBody: "프로젝트가 이 버전으로 돌아갑니다. 저장된 다른 버전은 그대로 남습니다.",
+ saveRestoreBody: "현재 편집을 먼저 버전으로 저장하므로 나중에 다시 돌아올 수 있습니다.",
+ saveAndRestore: "현재 편집 저장 후 복원",
+ namePlaceholder: "버전 이름 (선택)",
+ allVersions: "모든 버전",
+ namedVersions: "이름 있음",
+ fileChanges: "파일 변경",
+ sinceSaved: "마지막으로 저장한 버전 이후",
+ sincePrevious: "이전 버전과 비교",
+ filesFailed: "파일 변경 사항을 불러오지 못했습니다.",
+ previewHint: "이 버전을 미리 봐도 현재 편집은 바뀌지 않습니다.",
+ fileAdded: "추가됨",
+ fileModified: "수정됨",
+ fileDeleted: "삭제됨",
+ savedVersions: "저장된 버전",
+ deletedVersions: "삭제됨",
+ selectVersions: "버전 선택",
+ cancelSelection: "선택 취소",
+ selectVersion: "버전 선택: {name}",
+ selectVisible: "목록 전체 선택",
+ clearSelection: "선택 해제",
+ selectionCount: "{n}개 선택",
+ deleteSelected: "선택 삭제",
+ deleteVersion: "이 버전 삭제",
+ deleteTitle: "버전 {n}개를 삭제할까요?",
+ deleteBody: "선택한 버전은 삭제됨으로 이동하며 나중에 복구할 수 있습니다. 현재 영상, 저장하지 않은 수정, 미디어와 다른 버전은 변경되지 않습니다.",
+ deleteConfirm: "삭제됨으로 이동",
+ deletedRecords: "버전 {n}개를 삭제됨으로 이동했습니다.",
+ recoverRecords: "기록 복구",
+ recoveredRecords: "버전 {n}개를 기록 목록에 복구했습니다.",
+ noDeletedVersions: "삭제된 버전이 없습니다.",
+ deletedPreviewHint: "기록이 목록에서 제거되었습니다. 복구를 위해 스냅샷은 보관됩니다. 기록을 복구하면 다시 미리 보고 사용할 수 있습니다.",
+ errorDeleteCurrent: "현재 사용 중인 버전은 삭제할 수 없습니다.",
+ errorDeleted: "삭제된 버전입니다. 삭제됨에서 기록을 먼저 복구하세요.",
+ search: '버전 검색',
+ filterVersions: '버전 필터',
+ versionTypes: '버전 유형',
+ typeManual: '수동 저장',
+ typeAuto: '자동 저장',
+ typeRestore: '복원 기록',
+ typeOther: '기타 기록',
+ namedOnly: '이름이 있는 버전만',
+ showAllTypes: '모든 유형 표시',
+ matchesSaved: '마지막 저장 내용과 같음',
+ inUse: '사용 중',
+ noMatchingVersions: '일치하는 버전이 없습니다',
+ resetFilters: '검색 및 필터 초기화',
title: '버전 기록',
close: '닫기',
working: '처리 중…',
- branchOf: '브랜치: {branch}',
- branches: '브랜치',
- branchCount: '브랜치 {n}개',
- branchCountOne: '브랜치 1개',
- newBranch: '새 브랜치',
- newBranchTitle: '새 브랜치',
- newBranchBody: '“{branch}”의 지금 위치에서 시작합니다. 커밋하지 않은 변경도 함께 옮겨집니다.',
- newBranchBodyClean: '“{branch}”의 지금 위치에서 시작합니다.',
- newBranchFromTitle: '“{name}”에서 새 브랜치',
- newBranchFromBody: '이 버전에서 시작합니다. “{branch}”는 그대로 둡니다.',
- branchName: '브랜치 이름',
- create: '만들기',
- switchTitle: '“{name}”(으)로 전환할까요?',
- switchBody: '“{branch}”에 커밋하지 않은 변경이 있습니다.',
- leaveChanges: '{branch}에 두기',
- bringChanges: '{name}(으)로 가져가기',
- cancel: '취소',
- rename: '이름 바꾸기',
- renameTitle: '“{name}” 이름 바꾸기',
- save: '저장',
- delete: '삭제',
- deleteTitle: '브랜치 “{name}”을(를) 삭제할까요?',
- deleteBody: '브랜치가 삭제됩니다. 다른 브랜치에 있는 버전은 그대로 남습니다.',
- deleteForceTitle: '“{name}”과(와) 그 버전을 삭제할까요?',
- deleteForceBody: '“{name}”의 버전 {n}개는 다른 어떤 브랜치에도 없습니다. 삭제하면 되돌릴 수 없습니다.',
- deleteForceBodyOne: '“{name}”의 버전 1개는 다른 어떤 브랜치에도 없습니다. 삭제하면 되돌릴 수 없습니다.',
- deleteForce: '그래도 삭제',
- mergeInto: '{branch}에 병합',
- mergeTitle: '“{name}”을(를) “{branch}”에 병합',
- mergeBody: '“{name}”에서 한 작업이 “{branch}”에 들어옵니다.',
- mergeMessage: '{name} 병합',
- mergeConfirm: '병합',
- mergeConflictTitle: '“{name}”과(와) “{branch}”가 같은 부분을 바꿨습니다',
- mergeConflictBody: '서로 다른 부분에서 어느 쪽을 남길지 고르세요. 나머지는 양쪽 모두 유지됩니다.',
- keepOurs: '{branch} 쪽 유지',
- keepTheirs: '{name} 쪽 사용',
- nothingToMerge: '“{branch}”에 “{name}”의 내용이 이미 모두 있습니다.',
- current: '현재',
- parked: '여기 남겨 둔 변경 있음',
- parkedStuck: '이 브랜치에 남겨 둔 변경이 지금 내용과 충돌해 아직 보관 중입니다.',
- changesTitle: '커밋하지 않은 변경',
- noChanges: '모두 커밋됨',
- firstCommitHint: '아직 커밋이 없습니다. 커밋하면 지금 영상이 버전으로 남아 언제든 돌아올 수 있습니다.',
- messagePlaceholder: '이 버전 설명 (필수)',
+ messagePlaceholder: '메시지 (⌘↵로 커밋)',
commit: '커밋',
- discard: '변경 버리기',
- discardTitle: '커밋하지 않은 변경을 모두 버릴까요?',
- discardBody: '영상이 마지막 커밋으로 돌아갑니다. 그 뒤에 추가한 파일은 휴지통으로 이동합니다.',
- historyOf: '기록 · {branch}',
- restore: '이 버전으로 되돌리기',
- restoreTitle: '“{name}”(으)로 되돌릴까요?',
- restoreBody: '영상이 이 버전이 되고, 커밋하지 않은 변경으로 표시됩니다. 커밋하면 남고, 버리면 지금으로 돌아옵니다.',
- restoreDirtyBody: '커밋하지 않은 변경이 있습니다. 되돌리기 전에 먼저 버립니다 (추가한 파일은 휴지통으로 이동).',
- restoreDiscard: '버리고 되돌리기',
- restoreConfirm: '되돌리기',
- restoredMessage: '“{name}”(으)로 되돌림',
- branchFrom: '여기서 새 브랜치',
+ changes: '변경 사항',
+ discardAll: '모든 변경 사항 취소',
+ noChanges: '변경 사항 없음',
+ moreFiles: '외 {n}개',
+ graph: '그래프',
+ noVersions: '아직 커밋이 없습니다',
+ current: '현재',
+ checkout: '체크아웃',
+ copy: '사본 만들기',
moreActions: '더 보기',
- scenesAdded: '장면 {n}개 추가',
- scenesAddedOne: '장면 1개 추가',
- scenesEdited: '장면 {n}개 수정',
- scenesEditedOne: '장면 1개 수정',
- scenesRemoved: '장면 {n}개 삭제',
- scenesRemovedOne: '장면 1개 삭제',
- soundsAdded: '소리 {n}개 추가',
- soundsAddedOne: '소리 1개 추가',
- soundsEdited: '소리 {n}개 수정',
- soundsEditedOne: '소리 1개 수정',
- soundsRemoved: '소리 {n}개 삭제',
- soundsRemovedOne: '소리 1개 삭제',
- look: '화면이 바뀜',
- same: '영상 변경 없음',
- errorDirty: '먼저 커밋하지 않은 변경을 커밋하거나 버리세요.',
- errorNothing: '커밋할 변경이 없습니다.',
- errorCarry: '변경이 그 브랜치 내용과 충돌합니다. 이 브랜치에 남겨 두세요.',
- errorExists: '같은 이름의 브랜치가 이미 있습니다.',
- errorName: '브랜치 이름으로 쓸 수 없습니다.',
- errorMessage: '먼저 버전을 설명하세요.',
- errorCurrent: '지금 그 브랜치에 있습니다.',
+ showMore: '이전 버전 보기',
+ dirtyTitle: '커밋하지 않은 변경 사항이 있습니다',
+ dirtyBody: '먼저 커밋하거나, 변경 사항을 취소하고 “{name}”을(를) 체크아웃하세요.',
+ discardAndCheckout: '취소하고 체크아웃',
+ discardTitle: '모든 변경 사항을 취소할까요?',
+ discardBody: '영상이 체크아웃한 버전으로 돌아갑니다. 그 뒤에 추가한 파일은 휴지통으로 옮겨집니다.',
+ discardConfirm: '모든 변경 사항 취소',
+ copyTitle: '“{name}”의 사본 만들기',
+ copyBody: '이 버전에서 새 프로젝트를 시작합니다. 이 프로젝트는 그대로입니다.',
+ copyName: '프로젝트 이름',
+ copyDefault: '{project} – {name}',
+ copyConfirm: '사본 만들기',
+ cancel: '취소',
+ missing: '복원했지만 이 버전의 일부 미디어를 찾을 수 없어 해당 파일은 그대로 두었습니다.',
+ kindSaved: '저장한 버전',
+ kindAuto: '자동 저장',
+ kindAgent: '에이전트 작업 전',
+ kindBeforeRestore: '복원하기 전',
+ kindRestore: '“{name}” 복원함',
+ kindRestoreAt: '{time} 버전 복원함',
+ kindRestoreOlder: '이전 버전 복원함',
+ kindUpgrade: '프로젝트의 모든 파일 저장',
+ kindParked: '“{name}”에 남겨 둔 변경',
+ loadFailed: '버전 기록을 읽지 못했습니다. 다시 시도하고, 계속 실패하면 OpenFilm을 다시 시작하세요.',
+ retry: '다시 시도',
+ errorNothing: '커밋할 변경 사항이 없습니다.',
+ errorDirty: '먼저 변경 사항을 커밋하거나 취소하세요.',
errorUnavailable: '지금은 버전 기록을 사용할 수 없습니다. 잠시 후 다시 시도하세요.',
errorGeneric: '완료하지 못했습니다. 다시 시도하세요.',
progressScan: '영상의 파일을 읽는 중… {done}/{total}',
progressStore: '미디어를 보관하는 중… {done}/{total}',
progressWrite: '파일을 쓰는 중… {done}/{total}',
progressMigrate: '이 프로젝트의 기록을 업데이트하는 중… {done}/{total}',
- heldFiles: '기록에 포함: 영상이 쓰는 파일 {n}개',
- heldFilesOne: '기록에 포함: 영상이 쓰는 파일 1개',
- ignoredFiles: '기록에 없음: 영상이 쓰지 않는 파일 {n}개',
- ignoredFilesOne: '기록에 없음: 영상이 쓰지 않는 파일 1개',
},
stageMenu: {
align: '정렬',
@@ -1546,6 +1634,11 @@ export const ko: Words = {
proxySize: "프록시 크기",
proxySizeHint: "작을수록 더 부드럽게 재생되고, 클수록 뷰어에서 더 선명합니다.",
},
+ versions: {
+ group: '버전',
+ auto: '자동 버전',
+ autoHint: '작업하는 동안 버전을 자동으로 커밋합니다. 에이전트 작업 전후, 그리고 영상이 몇 분 동안 바뀌지 않을 때. 영상이 바뀐 경우에만 저장합니다.',
+ },
advanced: {
intro: "최적의 환경으로 설정되어 있어 보통은 바꿀 필요가 없습니다.",
fitPages: "웹 페이지를 뷰어 크기로 그리기",
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index bc55471..1f50301 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -97,7 +97,8 @@ export const zhCN: Words = {
eyebrow: '已更新',
title: 'OpenFilm {version} 有哪些新内容',
close: '关闭',
- changelog: '完整更新日志',
+ changelog: 'GitHub 上的发布记录',
+ earlier: '更早的版本',
ok: '知道了',
kind: {
new: '新功能',
@@ -324,6 +325,12 @@ export const zhCN: Words = {
close: '关闭',
},
exportCenter: {
+ videoPreset: '预设',
+ presetDefault: '默认',
+ platformPresets: '社媒预设',
+ presetCustom: '自定义',
+ presetDefaultHint: '跟随当前画幅,使用通用视频设置。',
+ presetCustomHint: '已调整参数,可以继续修改或重新选择预设。',
fpsProject: "项目",
title: '导出',
dest: {
@@ -333,7 +340,6 @@ export const zhCN: Words = {
audio: '音频',
subtitles: '字幕',
images: '图片',
- slides: '幻灯片与 PDF',
project: '项目',
alpha: '透明素材',
nle: '剪辑工程',
@@ -344,20 +350,18 @@ export const zhCN: Words = {
gif: '用于文档、邮件、README',
audio: '混音或分轨',
subtitles: 'SRT、WebVTT、文字稿',
- images: '封面与镜头静帧',
- slides: '每个镜头一页',
+ images: "纯图片、ZIP、PDF、PPTX",
project: '整个项目,方便传给别人',
alpha: '带 Alpha 通道,用于 AE、Final Cut、网页',
nle: '{app}、Final Cut Pro、Premiere Pro、DaVinci Resolve',
},
destDesc: {
social: '选择一个或多个平台。每个平台都会得到合适的画幅、尺寸和帧率,一次全部导出。',
- video: '单个视频,可完全控制编码、画幅、分辨率和画质。',
+ video: '从默认或社媒预设开始,也可以自由调整编码、画幅、分辨率和画质。',
gif: '循环播放的动图。尽量短小——GIF 的体积增长很快。',
audio: '混合好的音轨,或将人声、音乐和音效分别导出为独立文件,供你自行混音。',
subtitles: '用于 YouTube、播放器和译者的字幕文件,或纯文本文字稿。',
- images: '封面图,或每个镜头一张静帧,用作缩略图和社交平台配图。',
- slides: '每个镜头一页的演示文稿或 PDF——可直接演示或打印。',
+ images: "选择影片中的画面,保存为独立图片、ZIP 压缩包、PDF 或 PPTX 演示文稿。",
project: '项目本身——成片、页面、素材,以及你选择的部分——导出为 zip 或文件夹,可以直接用 OpenFilm 打开。',
alpha: '透明背景的视频——整部影片或单个元素——可叠加到你自己的剪辑、应用和网站中。',
nle: '时间轴本身,可以接着剪:{app}草稿,或剪辑软件可导入的 XML。每个页面导出为带 Alpha 通道的片段,你的视频素材和声音各占独立的轨道。',
@@ -403,6 +407,12 @@ export const zhCN: Words = {
gifWidth: '尺寸',
gifHint: '提示:选取几秒钟的范围即可。一段 10 秒、640px 的 GIF 通常只有几 MB。',
format: '格式',
+ imageOutput: "导出类型",
+ imageFormat: "图片格式",
+ imageFiles: "纯图片",
+ imageFilesHint: "每个选中的画面保存为一个图片文件",
+ imageZipHint: "将选中的图片打包为一个 ZIP",
+ imagePageLimit: "PDF 和 PPTX 最多支持 {n} 个画面,请减少选中的画面。",
audioHint: {
wav: '无损,适合剪辑',
m4a: '体积小,音质高',
@@ -425,12 +435,6 @@ export const zhCN: Words = {
txt: '纯文本,用于文档和翻译',
},
captionCount: '本片共有 {n} 行字幕。',
- poster: '封面',
- posterAt: '导出 {time} 处的画面',
- posterMiddle: '导出中间的画面',
- sceneStills: '镜头静帧',
- sceneStillsDesc: '每个镜头取中间的一帧(共 {n} 个镜头),打包为 zip。',
- stills: '镜头静帧',
sequence: '序列',
slidesHint: {
pptx: '可在 PowerPoint、Keynote 和 Google Slides 中打开',
@@ -441,6 +445,37 @@ export const zhCN: Words = {
rangePart: '部分',
rangeFrom: '起点',
rangeTo: '终点',
+ rangeBoundary: '选择片段边界',
+ rangeHint: '可输入秒数(2.5)、分:秒(00:02.500)、时:分:秒或帧时间码(00:00:02:15)。',
+ rangeInvalid: '请输入 0 至 {end} 秒之间的有效时间,终点须晚于起点。',
+ rangeDelivery: "导出方式",
+ rangeSeparate: "每段分别导出",
+ rangeMerged: "合并为一个文件",
+ rangeSeparateHint: "每个选中的范围保存为一个独立文件。",
+ rangeMergedHint: "按下方列表顺序拼接,画面、声音和字幕一起衔接。",
+ rangePreview: "范围视频预览",
+ rangePreviewFailed: "无法载入视频预览,仍可输入时间选择范围。",
+ rangeRetry: "重试",
+ rangePause: "暂停预览",
+ rangePlay: "播放这一段",
+ rangePreviousFrame: "上一帧",
+ rangeNextFrame: "下一帧",
+ rangeUnmute: "取消静音",
+ rangeMute: "静音",
+ rangeSetStart: "设为起点",
+ rangeSetEnd: "设为终点",
+ rangeSeek: "定位预览时间",
+ rangeSelected: "已选范围",
+ rangeSegment: "第 {n} 段",
+ rangeDragStart: "拖动起点",
+ rangeDragEnd: "拖动终点",
+ rangeCount: "已选 {n} 段 · 最多 100 段",
+ rangeAdd: "添加一段",
+ rangeInvalidSegment: "请调整起止时间",
+ rangeRemove: "移除第 {n} 段",
+ rangePickOne: "请至少添加一段导出范围。",
+ rangeStripHint: "缩略条仅用于定位预览,不会切换所选段。拖动当前段两端调整范围;⌘/Ctrl + 滚轮缩放,左右滑动平移。",
+ rangeCardsHint: "点击下方片段切换预览与编辑,导出顺序与列表一致。",
saveTo: '保存到',
fileName: '名称',
change: '更改…',
@@ -451,6 +486,35 @@ export const zhCN: Words = {
emptyFilm: '影片是空的——请先添加一个片段。',
missingMedia: '缺少 {n} 个媒体文件:{files}。请先在时间线上右键红色片段重新链接,再导出。',
pickPreset: '请至少选择一个平台。',
+ summaryImage: '1 张图片',
+ summaryImages: '{n} 张图片',
+ summaryImagesZip: '{n} 张图片,打包为 zip',
+ summarySlide: '1 页',
+ summarySlides: '{n} 页',
+ pickMoments: '请至少选择一个画面。',
+ moments: {
+ added: '已添加',
+ quick: '一键选',
+ playhead: '播放头',
+ scenes: '每个镜头中间',
+ markers: '每个标记',
+ every: '每隔几秒',
+ everyN: '每 {s} 秒 · {n} 张',
+ strip: '影片',
+ hint: '单击或拖动只定位预览,点击「添加这一帧」或按回车才会添加。⌘/Ctrl + 滚轮或双指捏合缩放,左右滑动平移。← → 逐帧,Shift + ← → 一次 1 秒。',
+ add: '添加这一帧',
+ remove: '移除这一帧',
+ picked: '已选 {n} 个画面',
+ clear: '清空',
+ none: '还没有选画面:先预览,再点击「添加这一帧」或按回车。',
+ limit: '最多 {n} 个。',
+ noSubtitles: '这里的画面不含烧录的字幕,导出的文件里有。',
+ selectHint: '点一下画面选中它,缩略条上会出现它的圆点,可以拖动,或按 Alt + ← → 逐帧微调;再点一下取消选中。',
+ zoom: '缩放',
+ zoomIn: '放大',
+ zoomOut: '缩小',
+ zoomFit: '显示整部影片',
+ },
noCaptions: '此影片没有字幕。',
noAudio: '此影片没有声音。',
noFolder: '请先选择保存位置。',
@@ -638,98 +702,122 @@ export const zhCN: Words = {
daysAgo: '{n} 天前',
},
versions: {
+ savedVersions: "历史版本",
+ deletedVersions: "已删除",
+ selectVersions: "选择版本",
+ cancelSelection: "取消选择",
+ selectVersion: "选择版本:{name}",
+ selectVisible: "全选列表",
+ clearSelection: "取消全选",
+ selectionCount: "已选 {n} 个",
+ deleteSelected: "删除所选",
+ deleteVersion: "删除此版本",
+ deleteTitle: "删除 {n} 个版本?",
+ deleteBody: "所选版本会移到“已删除”,之后可以恢复。当前影片、未保存的修改、素材和其它版本都不会改变。",
+ deleteConfirm: "移到已删除",
+ deletedRecords: "已将 {n} 个版本移到“已删除”。",
+ recoverRecords: "恢复记录",
+ recoveredRecords: "已将 {n} 个版本恢复到历史列表。",
+ noDeletedVersions: "暂无已删除的版本。",
+ deletedPreviewHint: "版本已移出历史列表,快照保留以便恢复。恢复记录后可以继续预览和使用。",
+ errorDeleteCurrent: "当前正在使用的版本不能删除。",
+ errorDeleted: "此版本已删除,请先在“已删除”中恢复记录。",
+ search: '搜索版本',
+ filterVersions: '过滤版本',
+ versionTypes: '版本类型',
+ typeManual: '手动保存',
+ typeAuto: '自动保存',
+ typeRestore: '恢复记录',
+ typeOther: '其他记录',
+ namedOnly: '只看已命名的版本',
+ showAllTypes: '显示全部类型',
+ matchesSaved: '与上次保存一致',
+ inUse: '使用中',
+ noMatchingVersions: '没有匹配的版本',
+ resetFilters: '清除搜索和过滤',
+ previewFailed: '这个版本暂时无法预览,请重试。',
+ previewLoading: '正在加载这个版本…',
+ previewMissing: '这个版本有 {n} 个素材文件缺失,其余内容仍可预览。',
+ videoPreview: '版本视频预览',
+ play: '播放',
+ pause: '暂停',
+ seek: '播放进度',
+ mute: '静音',
+ unmute: '取消静音',
+ today: '今天',
+ yesterday: '昨天',
+ workingCopy: '当前编辑',
+ workingCopyHint: '这是当前的编辑内容,保存为版本后可以随时找回。',
+ unsavedFiles: '有 {n} 个文件发生变化',
+ lastSaved: '上次保存',
+ restored: '已恢复此版本。',
+ saveVersion: '保存版本',
+ saveTitle: '保存当前版本',
+ saveBody: '可以给这个创作节点起个名字,方便以后找到,也可以留空。',
+ restore: '恢复此版本',
+ restoreTitle: '恢复「{name}」?',
+ restoreBody: '项目将回到这个版本,其他已保存的版本仍然保留。',
+ saveRestoreBody: '会先把当前修改保存为一个版本,之后可以随时找回,再恢复所选版本。',
+ saveAndRestore: '保存当前进度并恢复',
+ namePlaceholder: '版本名称(可选)',
+ allVersions: '全部版本',
+ namedVersions: '已命名',
+ fileChanges: '文件变化',
+ sinceSaved: '自上次保存以来',
+ sincePrevious: '与上一版本相比',
+ filesFailed: '文件变化读取失败。',
+ previewHint: '正在预览历史版本,当前编辑内容保持不变。',
+ fileAdded: '新增',
+ fileModified: '修改',
+ fileDeleted: '删除',
title: '版本历史',
close: '关闭',
working: '处理中…',
- branchOf: '分支:{branch}',
- branches: '分支',
- branchCount: '{n} 个分支',
- branchCountOne: '1 个分支',
- newBranch: '新建分支',
- newBranchTitle: '新建分支',
- newBranchBody: '从「{branch}」现在的位置开始。未提交的改动会一起带过去。',
- newBranchBodyClean: '从「{branch}」现在的位置开始。',
- newBranchFromTitle: '从「{name}」新建分支',
- newBranchFromBody: '从这个版本开始;「{branch}」保持不变。',
- branchName: '分支名称',
- create: '创建',
- switchTitle: '切换到「{name}」?',
- switchBody: '「{branch}」上还有未提交的改动。',
- leaveChanges: '留在 {branch}',
- bringChanges: '带到 {name}',
- cancel: '取消',
- rename: '重命名',
- renameTitle: '重命名「{name}」',
- save: '保存',
- delete: '删除',
- deleteTitle: '删除分支「{name}」?',
- deleteBody: '分支会被删掉。它的版本在其他分支上的,都还保留着。',
- deleteForceTitle: '删除「{name}」和它的版本?',
- deleteForceBody: '「{name}」上有 {n} 个版本不在其他分支上,删除后就再也找不回了。',
- deleteForceBodyOne: '「{name}」上有 1 个版本不在其他分支上,删除后就再也找不回了。',
- deleteForce: '仍然删除',
- mergeInto: '合并到 {branch}',
- mergeTitle: '把「{name}」合并到「{branch}」',
- mergeBody: '「{name}」上做的改动会合并进「{branch}」。',
- mergeMessage: '合并 {name}',
- mergeConfirm: '合并',
- mergeConflictTitle: '「{name}」和「{branch}」改了同一处',
- mergeConflictBody: '两边不一样的地方,选择保留哪一边。其余的改动两边都会保留。',
- keepOurs: '保留 {branch} 的',
- keepTheirs: '用 {name} 的',
- nothingToMerge: '「{branch}」已经包含「{name}」的全部内容。',
- current: '当前',
- parked: '有留在这里的改动',
- parkedStuck: '留在这个分支上的改动和现在的内容冲突,所以暂时还收着。',
- changesTitle: '未提交的改动',
- noChanges: '所有改动都已提交',
- firstCommitHint: '还没有任何提交。提交会把影片此刻的样子存成一个版本,之后随时可以回来。',
- messagePlaceholder: '描述这个版本(必填)',
+ messagePlaceholder: '消息(⌘↵ 提交)',
commit: '提交',
- discard: '放弃改动',
- discardTitle: '放弃所有未提交的改动?',
- discardBody: `影片会回到最近一次提交。之后新加的文件会移到${TRASH}。`,
- historyOf: '提交记录 · {branch}',
- restore: '恢复到这个版本',
- restoreTitle: '恢复到「{name}」?',
- restoreBody: '影片会变回这个版本,作为未提交的改动出现:提交就保留下来,放弃就回到现在。',
- restoreDirtyBody: `你还有未提交的改动。恢复会先放弃它们(之后新加的文件会移到${TRASH})。`,
- restoreDiscard: '放弃并恢复',
- restoreConfirm: '恢复',
- restoredMessage: '回到「{name}」',
- branchFrom: '从这里新建分支',
+ changes: '更改',
+ discardAll: '放弃所有更改',
+ noChanges: '没有更改',
+ moreFiles: '还有 {n} 个',
+ graph: '图形',
+ noVersions: '还没有保存的版本',
+ current: '当前',
+ checkout: '签出',
+ copy: '另存为新项目',
moreActions: '更多',
- scenesAdded: '加了 {n} 个镜头',
- scenesAddedOne: '加了 1 个镜头',
- scenesEdited: '改了 {n} 个镜头',
- scenesEditedOne: '改了 1 个镜头',
- scenesRemoved: '删了 {n} 个镜头',
- scenesRemovedOne: '删了 1 个镜头',
- soundsAdded: '加了 {n} 段声音',
- soundsAddedOne: '加了 1 段声音',
- soundsEdited: '改了 {n} 段声音',
- soundsEditedOne: '改了 1 段声音',
- soundsRemoved: '删了 {n} 段声音',
- soundsRemovedOne: '删了 1 段声音',
- look: '画面细节有改动',
- same: '影片没有变化',
- errorDirty: '请先提交或放弃未提交的改动。',
- errorNothing: '没有可以提交的改动。',
- errorCarry: '你的改动和那个分支的内容冲突,改为把它们留在当前分支吧。',
- errorExists: '已经有同名的分支了。',
- errorName: '这个名称不能用作分支名。',
- errorMessage: '请先描述这个版本。',
- errorCurrent: '你现在就在这个分支上。',
+ showMore: '显示更早的版本',
+ dirtyTitle: '有未提交的更改',
+ dirtyBody: '请先提交,或放弃这些更改后签出「{name}」。',
+ discardAndCheckout: '放弃更改并签出',
+ discardTitle: '放弃所有更改?',
+ discardBody: `影片会回到上次保存的版本,之后新加的文件移到${TRASH}。`,
+ discardConfirm: '放弃所有更改',
+ copyTitle: '把「{name}」另存一份',
+ copyBody: '从这个版本开始一个新项目,当前项目保持不变。',
+ copyName: '项目名称',
+ copyDefault: '{project} – {name}',
+ copyConfirm: '创建项目',
+ cancel: '取消',
+ missing: '已恢复,但这个版本的部分素材找不到了,这些文件保持原样。',
+ kindSaved: '已保存的版本',
+ kindAuto: '自动保存',
+ kindAgent: '智能体开始前',
+ kindBeforeRestore: '恢复之前',
+ kindRestore: '恢复了「{name}」',
+ kindRestoreAt: '恢复了 {time} 的版本',
+ kindRestoreOlder: '恢复了更早的版本',
+ kindUpgrade: '开始保存项目的全部文件',
+ kindParked: '留在「{name}」上的改动',
+ loadFailed: '版本历史读取失败。请重试;如果一直失败,请重启 OpenFilm。',
+ retry: '重试',
+ errorNothing: '没有需要保存的修改。',
+ errorDirty: '请先提交或放弃更改。',
errorUnavailable: '版本历史暂时不可用,请稍后再试。',
errorGeneric: '操作没有成功,请重试。',
progressScan: '正在读取影片的文件… {done}/{total}',
progressStore: '正在保存媒体… {done}/{total}',
progressWrite: '正在写入文件… {done}/{total}',
progressMigrate: '正在更新本项目的版本历史… {done}/{total}',
- heldFiles: '已纳入历史:影片使用的 {n} 个文件',
- heldFilesOne: '已纳入历史:影片使用的 1 个文件',
- ignoredFiles: '未纳入历史:影片未使用的 {n} 个文件',
- ignoredFilesOne: '未纳入历史:影片未使用的 1 个文件',
},
stageMenu: {
align: '对齐',
@@ -1551,6 +1639,11 @@ export const zhCN: Words = {
proxySize: "代理分辨率",
proxySizeHint: "越小播放越流畅,越大预览越清晰。",
},
+ versions: {
+ group: '版本',
+ auto: '自动保存版本',
+ autoHint: '工作时自动提交版本:智能体每一轮开始前和结束后,以及影片停下几分钟没变时。只有影片变了才保存。',
+ },
advanced: {
intro: "这些已设为最佳体验,一般不用改。",
fitPages: "按查看器尺寸绘制网页",
diff --git a/packages/openfilm/studio/ui/src/lib/export-jobs.ts b/packages/openfilm/studio/ui/src/lib/export-jobs.ts
index fd7fb9b..09cc5e7 100644
--- a/packages/openfilm/studio/ui/src/lib/export-jobs.ts
+++ b/packages/openfilm/studio/ui/src/lib/export-jobs.ts
@@ -16,12 +16,12 @@ type Framing = { frame?: FilmFrameId; fill?: FilmFrameFill; burnSubtitles?: bool
*/
export type NleAlpha = 'auto' | 'png' | 'prores' | 'prores4444';
-export type ExportRequest = { range?: [number, number]; label?: string; name?: string } & (
+export type ExportRequest = { range?: [number, number]; ranges?: [number, number][]; label?: string; name?: string } & (
| (Framing & { kind: 'video'; codec: ExportVideoCodec; shortEdge?: number; fps: number; quality: ExportQuality; audio: boolean;
clip?: string; scale?: number; preset?: string; sidecar?: 'srt' | 'vtt' })
| (Framing & { kind: 'gif'; width: number; fps: number })
| { kind: 'audio'; format: 'wav' | 'm4a' | 'mp3'; mix: boolean; stems: boolean }
- | (Framing & { kind: 'stills'; format: 'png' | 'jpg'; shortEdge: number; at?: number[] })
+ | (Framing & { kind: 'stills'; as?: 'files' | 'zip'; format: 'png' | 'jpg'; shortEdge: number; at?: number[] })
| (Framing & { kind: 'poster'; format: 'png' | 'jpg'; shortEdge: number; at?: number })
| { kind: 'subtitles'; format: 'srt' | 'vtt' | 'txt' }
| (Framing & { kind: 'slides'; format: 'pptx' | 'pdf'; shortEdge: number; at?: number[] })
diff --git a/packages/openfilm/studio/ui/src/lib/export-moments.test.ts b/packages/openfilm/studio/ui/src/lib/export-moments.test.ts
new file mode 100644
index 0000000..89ec6b5
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/export-moments.test.ts
@@ -0,0 +1,114 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ STRIP_WHOLE, clampView, cleanMoments, everyCount, everyMoments, filmFrameUrl, lastFrameMs, loadMoments, loadSharedMoments, momentAt, momentSeconds, saveMoments, sceneMiddles,
+ stepFor, stripZoomMax, toggleMoment, viewShowing, zoomView,
+} from './export-moments.ts';
+
+const close = (actual: readonly number[], expected: readonly number[]) => {
+ assert.equal(actual.length, expected.length, `${actual.join(', ')} vs ${expected.join(', ')}`);
+ actual.forEach((v, i) => assert.ok(Math.abs(v - expected[i]!) < 0.01, `${v} vs ${expected[i]}`));
+};
+
+test('a moment lands on a frame inside the film', () => {
+ assert.equal(lastFrameMs(1000, 25), 960);
+ assert.equal(momentAt(5000, 1000, 25), 960);
+ assert.equal(momentAt(-20, 1000, 25), 0);
+ assert.equal(momentAt(415, 1000, 25), 400);
+ /* 29.97: frames are 33.367 ms, and the last one starts before the end */
+ assert.ok(lastFrameMs(1000, 29.97) < 1000 && lastFrameMs(1000, 29.97) > 960);
+});
+
+test('moments are kept on frames, once each, in order, up to the most', () => {
+ close(cleanMoments([500, 100, 510, 99, NaN, 9000], 1000, 25, 10), [80, 120, 520, 960]);
+ close(cleanMoments([500, 100, 300], 1000, 25, 2), [120, 320]);
+ assert.deepEqual(cleanMoments([100], 0, 25, 10), []);
+});
+
+test('toggling a frame adds it, or takes it out when it is there', () => {
+ const one = toggleMoment([], 400, 1000, 25, 10);
+ close(one, [400]);
+ close(toggleMoment(one, 790, 1000, 25, 10), [400, 800]);
+ close(toggleMoment(one, 410, 1000, 25, 10), []);
+});
+
+test('the middle of each scene, as the server picks scene stills', () => {
+ const scenes = [{ startMs: 6000, durMs: 6000 }, { startMs: 0, durMs: 6000 }, { startMs: 200, durMs: 1000 }, { startMs: 12000, durMs: 0 }];
+ close(sceneMiddles(scenes, 12000, 30), [3000, 9000]);
+ /* a scene running past the film's end is cut at it */
+ close(sceneMiddles([{ startMs: 0, durMs: 20000 }], 10000, 30), [5000]);
+ close(sceneMiddles([], 10000, 30), [5000]);
+});
+
+test('one frame every few seconds, from the middle of each stretch', () => {
+ close(everyMoments(2000, 6000, 30, 10), [1000, 3000, 5000]);
+ assert.equal(everyCount(2000, 6000), 3);
+ assert.equal(everyCount(2000, 5000), 2);
+ assert.equal(everyMoments(1000, 600_000, 30, 200).length, 200);
+ close(everyMoments(5000, 1000, 30, 10), [500]);
+});
+
+test('moments go to the server as seconds; the frame is drawn by the film page', () => {
+ assert.deepEqual(momentSeconds([1000, 33.3666]), [1, 0.033]);
+ assert.equal(filmFrameUrl('p 1', 1234.4, 320), '/api/projects/p%201/media?what=frame&path=film.html&ms=1234&w=320');
+});
+
+test('picks are kept per project and kind', () => {
+ const store = new Map<string, string>();
+ (globalThis as { localStorage?: unknown }).localStorage = {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => { store.set(k, v); },
+ };
+ try {
+ assert.equal(loadMoments('a', 'images'), null);
+ saveMoments('a', 'images', [1000, 2000]);
+ saveMoments('a', 'slides', [500]);
+ assert.deepEqual(loadMoments('a', 'images'), [1000, 2000]);
+ assert.deepEqual(loadMoments('a', 'slides'), [500]);
+ for (let i = 0; i < 60; i++) saveMoments(`p${i}`, 'images', [i]);
+ assert.equal(loadMoments('a', 'images'), null, 'the oldest project is let go');
+ assert.deepEqual(loadMoments('p59', 'images'), [59]);
+ } finally {
+ delete (globalThis as { localStorage?: unknown }).localStorage;
+ }
+});
+
+test('the strip zooms around the pointer, up to a second across, and stays inside the film', () => {
+ const total = 60_000;
+ assert.equal(stripZoomMax(total), 60);
+ assert.equal(stripZoomMax(500), 1);
+ const z = zoomView(STRIP_WHOLE, 4, 0.5, total);
+ assert.deepEqual(z, { zoom: 4, start: 22_500 }, 'the middle stays in the middle');
+ const left = zoomView(STRIP_WHOLE, 2, 0, total);
+ assert.equal(left.start, 0, 'zooming at the left edge keeps the start');
+ assert.deepEqual(zoomView(z, 1000, 0.5, total), { zoom: 60, start: 29_500 });
+ assert.deepEqual(zoomView(z, 0.01, 0.5, total), STRIP_WHOLE);
+ assert.deepEqual(clampView({ zoom: 4, start: 59_000 }, total), { zoom: 4, start: 45_000 });
+ assert.deepEqual(viewShowing({ zoom: 4, start: 0 }, 30_000, total), { zoom: 4, start: 16_500 });
+ assert.deepEqual(viewShowing({ zoom: 4, start: 0 }, 5000, total), { zoom: 4, start: 0 });
+ assert.equal(stepFor(100, 60, [1000, 5000, 10_000]), 10_000);
+ assert.equal(stepFor(10, 60, [1000, 5000]), 1000);
+ assert.equal(stepFor(1000, 60, [1000, 5000]), 5000);
+});
+
+test('the shared selection migrates old image or slide picks, then stays the same across output formats', () => {
+ const store = new Map<string, string>();
+ (globalThis as { localStorage?: unknown }).localStorage = {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => { store.set(k, v); },
+ };
+ try {
+ saveMoments('a', 'images', [1000, 2000]);
+ saveMoments('a', 'slides', [3000]);
+ assert.deepEqual(loadSharedMoments('a', 'images'), [1000, 2000]);
+ assert.deepEqual(loadSharedMoments('a', 'slides'), [3000]);
+ saveMoments('a', 'frames', [1000, 3000]);
+ assert.deepEqual(loadSharedMoments('a', 'slides'), [1000, 3000]);
+ assert.deepEqual(loadSharedMoments('a', 'images'), [1000, 3000]);
+ saveMoments('a', 'frames', []);
+ assert.deepEqual(loadSharedMoments('a', 'images'), [], 'clearing a selection does not resurrect old picks');
+ assert.equal(loadSharedMoments('unknown', 'images'), null);
+ } finally {
+ delete (globalThis as { localStorage?: unknown }).localStorage;
+ }
+});
diff --git a/packages/openfilm/studio/ui/src/lib/export-moments.ts b/packages/openfilm/studio/ui/src/lib/export-moments.ts
new file mode 100644
index 0000000..bf19627
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/export-moments.ts
@@ -0,0 +1,165 @@
+/**
+ * The moments an image or slides export takes: any frames of the film the person picks, one file or page each.
+ *
+ * A moment is film ms on the project's frame grid. The quick picks (the playhead, the middle of each scene, each
+ * marker, one every few seconds) only fill the list; the person adds, moves and removes frames from there. What was
+ * picked is kept per project in this browser, so the dialog opens on it next time.
+ */
+import { FILM_DOC_FILE } from './film.ts';
+import { frameAt, frameMs } from './timecode.ts';
+
+export type MomentsKind = 'images' | 'slides' | 'frames';
+
+/** The most each export takes (exports.mjs checks the same). */
+export const MOMENTS_MAX: Record<MomentsKind, number> = { images: 500, slides: 200, frames: 500 };
+
+/** The film drawn at `ms`, `w` px wide, as Studio's server draws it for an export (pageframes.mjs). */
+export function filmFrameUrl(projectId: string, ms: number, w: number): string {
+ return `/api/projects/${encodeURIComponent(projectId)}/media?what=frame&path=${encodeURIComponent(FILM_DOC_FILE)}&ms=${Math.round(ms)}&w=${Math.round(w)}`;
+}
+
+/** The last frame of a film `totalMs` long. */
+export function lastFrameMs(totalMs: number, fps: number): number {
+ const f = frameAt(totalMs, fps);
+ return frameMs(Math.max(0, frameMs(f, fps) >= totalMs - 1e-3 ? f - 1 : f), fps);
+}
+
+/** `ms` on the film's nearest frame, inside the film. */
+export function momentAt(ms: number, totalMs: number, fps: number): number {
+ return frameMs(Math.min(frameAt(Math.max(0, ms), fps), frameAt(lastFrameMs(totalMs, fps), fps)), fps);
+}
+
+/** The moments as kept: on frames, inside the film, each frame once, in time order, at most `max`. */
+export function cleanMoments(list: readonly number[], totalMs: number, fps: number, max: number): number[] {
+ if (!(totalMs > 0)) return [];
+ const frames = new Set<number>();
+ for (const ms of list) if (Number.isFinite(ms)) frames.add(frameAt(momentAt(ms, totalMs, fps), fps));
+ return [...frames].sort((a, b) => a - b).slice(0, max).map((f) => frameMs(f, fps));
+}
+
+/** Whether two moments are the same frame. */
+export function sameFrame(a: number, b: number, fps: number): boolean {
+ return frameAt(a, fps) === frameAt(b, fps);
+}
+
+/** The list with `ms` added, or taken out when that frame is in it already. */
+export function toggleMoment(list: readonly number[], ms: number, totalMs: number, fps: number, max: number): number[] {
+ const at = momentAt(ms, totalMs, fps);
+ return list.some((m) => sameFrame(m, at, fps))
+ ? list.filter((m) => !sameFrame(m, at, fps))
+ : cleanMoments([...list, at], totalMs, fps, max);
+}
+
+/**
+ * The middle of each picture clip, as the server picks scene stills when it is given no moments (exports.mjs
+ * stillFrames): clips starting within 0.4 s of the one before count once.
+ */
+export function sceneMiddles(scenes: readonly { startMs: number; durMs: number }[], totalMs: number, fps: number, max = 120): number[] {
+ const out: number[] = [];
+ let lastAt = -Infinity;
+ for (const sc of [...scenes].sort((a, b) => a.startMs - b.startMs)) {
+ if (!(sc.durMs > 0) || sc.startMs >= totalMs || sc.startMs - lastAt < 400) continue;
+ lastAt = sc.startMs;
+ out.push((sc.startMs + Math.min(sc.startMs + sc.durMs, totalMs)) / 2);
+ }
+ return cleanMoments(out.length ? out : [totalMs / 2], totalMs, fps, max);
+}
+
+/** One frame every `stepMs`, each from the middle of its stretch (the very first frame is often a fade from black). */
+export function everyMoments(stepMs: number, totalMs: number, fps: number, max: number): number[] {
+ if (!(stepMs > 0) || !(totalMs > 0)) return [];
+ const out: number[] = [];
+ for (let at = stepMs / 2; at < totalMs && out.length < max; at += stepMs) out.push(at);
+ return cleanMoments(out.length ? out : [totalMs / 2], totalMs, fps, max);
+}
+
+/** How many frames one every `stepMs` gives. */
+export function everyCount(stepMs: number, totalMs: number): number {
+ return stepMs > 0 && totalMs > 0 ? Math.max(1, Math.ceil((totalMs - stepMs / 2) / stepMs)) : 0;
+}
+
+/** The moments as an export asks for them: film seconds. */
+export function momentSeconds(list: readonly number[]): number[] {
+ return list.map((ms) => Math.round(ms) / 1000);
+}
+
+const STORE_KEY = 'openfilm.exportMoments.v1';
+/** The projects whose picks are kept: the latest ones. */
+const PROJECTS_KEPT = 50;
+
+type Store = Record<string, Partial<Record<MomentsKind, number[]>>>;
+
+function readStore(): Store {
+ try {
+ const raw = JSON.parse(localStorage.getItem(STORE_KEY) ?? 'null') as unknown;
+ return raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw as Store) : {};
+ } catch {
+ return {};
+ }
+}
+
+/** What was picked for this project last time (null: nothing yet). */
+export function loadMoments(projectId: string, kind: MomentsKind): number[] | null {
+ const list = readStore()[projectId]?.[kind];
+ return Array.isArray(list) ? list.filter((ms) => typeof ms === 'number' && Number.isFinite(ms)) : null;
+}
+
+/** One selection for every image delivery; migrate the previously used destination's picks on first use. */
+export function loadSharedMoments(projectId: string, previous: 'images' | 'slides'): number[] | null {
+ return loadMoments(projectId, 'frames') ?? loadMoments(projectId, previous)
+ ?? loadMoments(projectId, previous === 'images' ? 'slides' : 'images');
+}
+
+export function saveMoments(projectId: string, kind: MomentsKind, list: readonly number[]): void {
+ try {
+ const store = readStore();
+ const mine = { ...store[projectId], [kind]: [...list] };
+ delete store[projectId];
+ store[projectId] = mine;
+ const ids = Object.keys(store);
+ for (const id of ids.slice(0, Math.max(0, ids.length - PROJECTS_KEPT))) delete store[id];
+ localStorage.setItem(STORE_KEY, JSON.stringify(store));
+ } catch { /* storage off (private window) */ }
+}
+
+/**
+ * What the strip shows of the film: `zoom` times closer than the whole film across, from `start` (film ms) at its left
+ * edge. Zoomed in, it scrolls; the closest is a second across.
+ */
+export interface StripView { zoom: number; start: number }
+
+export const STRIP_WHOLE: StripView = { zoom: 1, start: 0 };
+
+/** The closest the strip zooms: a second across. */
+export function stripZoomMax(totalMs: number): number {
+ return Math.max(1, totalMs / 1000);
+}
+
+/** The view kept inside the film and its zoom between the whole film and a second. */
+export function clampView(view: StripView, totalMs: number): StripView {
+ const zoom = Math.min(stripZoomMax(totalMs), Math.max(1, view.zoom));
+ const span = totalMs / zoom;
+ return { zoom, start: Math.min(Math.max(0, totalMs - span), Math.max(0, view.start)) };
+}
+
+/** Zoomed by `factor` around `at` (0 to 1 across the strip): the moment there stays there. */
+export function zoomView(view: StripView, factor: number, at: number, totalMs: number): StripView {
+ const span = totalMs / view.zoom;
+ const anchor = view.start + at * span;
+ const zoom = Math.min(stripZoomMax(totalMs), Math.max(1, view.zoom * factor));
+ return clampView({ zoom, start: anchor - at * (totalMs / zoom) }, totalMs);
+}
+
+/** Scrolled, if need be, so `ms` is in sight, a tenth of the strip in from either edge. */
+export function viewShowing(view: StripView, ms: number, totalMs: number): StripView {
+ const span = totalMs / view.zoom;
+ const margin = span / 10;
+ if (ms < view.start + margin) return clampView({ ...view, start: ms - margin }, totalMs);
+ if (ms > view.start + span - margin) return clampView({ ...view, start: ms - span + margin }, totalMs);
+ return view;
+}
+
+/** The smallest of `steps` (ms) at least `minPx` wide when a pixel is `msPerPx`; the largest when none is. */
+export function stepFor(msPerPx: number, minPx: number, steps: readonly number[]): number {
+ return steps.find((s) => s / msPerPx >= minPx) ?? steps[steps.length - 1]!;
+}
diff --git a/packages/openfilm/studio/ui/src/lib/export-range.test.ts b/packages/openfilm/studio/ui/src/lib/export-range.test.ts
new file mode 100644
index 0000000..3b7aeb4
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/export-range.test.ts
@@ -0,0 +1,54 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { applyRangeDelivery, parseExportTime, readExportRange, readExportRanges, requestDurationMs } from './export-range.ts';
+import type { ExportRequest } from './export-jobs.ts';
+import { formatTimecode } from './timecode.ts';
+
+test('export points accept precise seconds and clock positions independent of scene boundaries', () => {
+ assert.equal(parseExportTime(' 2.525 '), 2525);
+ assert.equal(parseExportTime('.5'), 500);
+ assert.equal(parseExportTime('00:02.525'), 2525);
+ assert.equal(parseExportTime('1:02:03.125'), 3_723_125);
+ assert.equal(parseExportTime('90:00'), 5_400_000);
+ assert.deepEqual(readExportRange('2.525', '00:18.750', 23_200), { fromMs: 2525, toMs: 18750 });
+ assert.deepEqual(readExportRange('0', '23.2', 23_200), { fromMs: 0, toMs: 23_200 });
+});
+
+test('player timecodes select the same frame at integer and NTSC rates', () => {
+ for (const fps of [24, 25, 29.97, 30, 59.94, 60]) {
+ const ms = parseExportTime('00:00:17:12', fps)!;
+ assert.equal(formatTimecode(ms, { fps }), '00:00:17:12');
+ }
+ assert.equal(parseExportTime('00:00:02:15', 30), 2500);
+});
+
+test('malformed times and empty, reversed or out-of-film ranges are rejected', () => {
+ for (const raw of ['', 'abc', '-1', 'Infinity', '1e3', '1:60', '1:60:00', '1.5:20', '1::2', '00:00:01:30', '00:00:01:1.5', '0:0:0:0:0']) {
+ assert.equal(parseExportTime(raw), null, raw);
+ }
+ for (const [from, to] of [['', '4'], ['2', '2'], ['4', '2'], ['0', '23.201'], ['24', '25']]) {
+ assert.equal(readExportRange(from!, to!, 23_200), null, `${from}–${to}`);
+ }
+});
+
+test('multiple selections retain order and invalidate the whole request if any range is wrong', () => {
+ const parts = [{ id: 'later', from: '12.5', to: '15' }, { id: 'earlier', from: '2', to: '4' }];
+ assert.deepEqual(readExportRanges(parts, 23_200, 30), [[12.5, 15], [2, 4]]);
+ assert.equal(readExportRanges([...parts, { id: 'bad', from: '20', to: '15' }], 23_200, 30), null);
+ assert.equal(readExportRanges([{ id: 'tiny', from: '0', to: '.001' }], 23_200, 30), null);
+ assert.equal(readExportRanges([], 23_200, 30), null);
+});
+
+test('separate exports queue each range while merged exports queue one ordered selection, with correct estimates', () => {
+ const jobs: ExportRequest[] = [{ kind: 'video', codec: 'h264', fps: 30, quality: 'high', audio: true, label: 'H.264', sidecar: 'srt' }];
+ const ranges: [number, number][] = [[12.5, 15], [2, 4]];
+ const separate = applyRangeDelivery(jobs, ranges, 'separate');
+ assert.deepEqual(separate.map((job) => job.range), ranges);
+ assert.equal(separate[0]?.sidecar, 'srt');
+ assert.equal(separate.reduce((n, job) => n + requestDurationMs(job, 23_200), 0), 4500);
+ const merged = applyRangeDelivery(jobs, ranges, 'merged');
+ assert.equal(merged.length, 1);
+ assert.deepEqual(merged[0]?.ranges, ranges);
+ assert.equal(merged[0]?.range, undefined);
+ assert.equal(requestDurationMs(merged[0]!, 23_200), 4500);
+});
diff --git a/packages/openfilm/studio/ui/src/lib/export-range.ts b/packages/openfilm/studio/ui/src/lib/export-range.ts
new file mode 100644
index 0000000..e252969
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/export-range.ts
@@ -0,0 +1,63 @@
+import { exactRate, timecodeSeconds } from './timecode.ts';
+import type { ExportRequest } from './export-jobs.ts';
+
+export type ExportRangeDraft = { id: string; from: string; to: string };
+export type RangeDelivery = 'separate' | 'merged';
+export const EXPORT_RANGE_MAX = 100;
+
+export function readExportRanges(parts: readonly ExportRangeDraft[], totalMs: number, fps: number): [number, number][] | null {
+ if (!parts.length || parts.length > EXPORT_RANGE_MAX) return null;
+ const ranges: [number, number][] = [];
+ for (const part of parts) {
+ const value = readExportRange(part.from, part.to, totalMs, fps);
+ if (!value || Math.round(value.toMs * exactRate(fps) / 1000) <= Math.round(value.fromMs * exactRate(fps) / 1000)) return null;
+ ranges.push([value.fromMs / 1000, value.toMs / 1000]);
+ }
+ return ranges;
+}
+
+/** Each destination gets either one job per stretch or one job with an ordered selection. */
+export function applyRangeDelivery(jobs: readonly ExportRequest[], ranges: [number, number][], delivery: RangeDelivery): ExportRequest[] {
+ if (delivery === 'merged' && ranges.length > 1) return jobs.map((job) => ({ ...job, ranges }));
+ return ranges.flatMap((range, i) => jobs.map((job) => ({ ...job, range, label: [job.label, String(i + 1)].filter(Boolean).join(' · ') })));
+}
+
+export function requestDurationMs(request: ExportRequest, totalMs: number): number {
+ if (request.ranges) return request.ranges.reduce((n, [from, to]) => n + (to - from) * 1000, 0);
+ return request.range ? (request.range[1] - request.range[0]) * 1000 : totalMs;
+}
+
+/** Export points accept seconds, a clock (M:SS or H:MM:SS), or the player's H:MM:SS:FF timecode. */
+export function parseExportTime(raw: string, fps = 30): number | null {
+ const text = raw.trim();
+ if (/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(text)) {
+ const ms = Number(text) * 1000;
+ return Number.isFinite(ms) ? ms : null;
+ }
+ const parts = text.split(':');
+ if (parts.length < 2 || parts.length > 4 || parts.some((part) => !/^\d+(?:\.\d+)?$/.test(part))) return null;
+ if (parts.slice(0, -1).some((part) => !/^\d+$/.test(part))) return null;
+ const values = parts.map(Number);
+ if (values.some((part) => !Number.isFinite(part))) return null;
+ if (values.length === 4) {
+ const [hours, minutes, seconds, frames] = values as [number, number, number, number];
+ if (minutes >= 60 || seconds >= 60 || !Number.isInteger(frames) || frames >= Math.ceil(exactRate(fps))) return null;
+ const time = timecodeSeconds(hours * 3600 + minutes * 60 + seconds, frames, fps) * 1000;
+ return Number.isFinite(time) ? time : null;
+ }
+ const seconds = values.at(-1)!;
+ const minutes = values.at(-2)!;
+ if (seconds >= 60 || (values.length === 3 && minutes >= 60)) return null;
+ const time = ((values.length === 3 ? values[0]! * 3600 : 0) + minutes * 60 + seconds) * 1000;
+ return Number.isFinite(time) ? time : null;
+}
+
+/** An invalid partial export must never silently fall back to exporting the whole film. */
+export function readExportRange(from: string, to: string, totalMs: number, fps = 30): { fromMs: number; toMs: number } | null {
+ const fromMs = parseExportTime(from, fps);
+ const toMs = parseExportTime(to, fps);
+ /* Dividing an exact clip edge by 1,000 and reading it back can differ by a floating-point rounding error. */
+ if (!Number.isFinite(totalMs) || fromMs == null || toMs == null || fromMs < 0 || toMs > totalMs + 1e-6) return null;
+ const end = Math.min(toMs, totalMs);
+ return end > fromMs ? { fromMs, toMs: end } : null;
+}
diff --git a/packages/openfilm/studio/ui/src/lib/project-history.test.ts b/packages/openfilm/studio/ui/src/lib/project-history.test.ts
index 20070cd..cfdb0ec 100644
--- a/packages/openfilm/studio/ui/src/lib/project-history.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/project-history.test.ts
@@ -1,49 +1,99 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { historyAge, historyErrorKey, historyProgressOf, normalizeHistory, summaryParts, type Summary } from './project-history.ts';
+import {
+ filterHistoryVersions, graphRows, HISTORY_VERSION_TYPES, historyErrorKey, historyMoved, historyProgressOf, historyVersionType, isAutomatic, normalizeHistory, shownVersions, versionLabel,
+ type Version,
+} from './project-history.ts';
-const none = { added: 0, removed: 0, edited: 0 };
-const summary = (s: Partial<Summary>): Summary => ({ scenes: none, sounds: none, stage: false, other: false, ...s });
-
-test('what changed reads scenes before sounds, added before edited before removed', () => {
- assert.deepEqual(summaryParts(summary({ scenes: { added: 2, removed: 1, edited: 3 }, sounds: { added: 1, removed: 0, edited: 0 } })), [
- { key: 'scenesAdded', n: 2 }, { key: 'scenesEdited', n: 3 }, { key: 'scenesRemoved', n: 1 }, { key: 'soundsAdded', n: 1 },
- ]);
- assert.deepEqual(summaryParts(summary({ other: true })), [{ key: 'look', n: 0 }], 'a shared file changed: the look');
- assert.deepEqual(summaryParts(summary({})), [{ key: 'same', n: 0 }]);
-});
+const version = (v: Partial<Version>): Version => ({ commit: 'c', parents: [], at: 0, kind: 'named', name: '', restored: null, ...v });
test('the server\'s answer is checked: what cannot be read is left out, not drawn empty', () => {
assert.equal(normalizeHistory(null), null);
- assert.equal(normalizeHistory({ status: {} }), null);
+ assert.equal(normalizeHistory({ status: {} }), null, 'no versions list');
const read = normalizeHistory({
- status: { branch: 'main', head: 'abc', branches: [{ name: 'main', current: true }, { nope: 1 }], changes: { count: 2, summary: { scenes: { added: 1 } } } },
- commits: [{ commit: 'abc', message: 'One', at: 5, summary: {} }, { message: 'no id' }],
+ status: { head: 'abc', branch: 'main', changes: { count: 2, summary: { scenes: { added: 1 } }, files: [{ path: 'a.html', change: 'added' }, { path: 'b.html', change: 'odd' }, { nope: 1 }] } },
+ versions: [{ commit: 'abc', parents: ['def', 7], kind: 'auto', at: 5 }, { kind: 'named' }, { commit: 'def', kind: 'dance', name: 'Old' }],
+ more: true,
});
- assert.equal(read?.status.branches.length, 1);
- assert.deepEqual(read?.status.changes?.summary.scenes, { added: 1, removed: 0, edited: 0 });
- assert.deepEqual(read?.commits.map((c) => c.message), ['One']);
- assert.equal(normalizeHistory({ status: { branch: 'main', changes: null } })?.status.changes, null);
- assert.equal(normalizeHistory({ status: { branch: 'main' } })?.status.files, null, 'an older Studio says nothing of the files');
- assert.deepEqual(normalizeHistory({ status: { branch: 'main', files: { held: 3, heldBytes: '9', ignored: 2 } } })?.status.files, { held: 3, heldBytes: 0, ignored: 2 });
+ assert.deepEqual(read?.status.changes?.files, [{ path: 'a.html', change: 'added' }, { path: 'b.html', change: 'modified' }]);
+ assert.deepEqual(read?.versions.map((v) => [v.commit, v.kind, v.name, v.parents]), [['abc', 'auto', '', ['def']], ['def', 'named', 'Old', []]]);
+ assert.equal(read?.status.branch, 'main');
+ assert.equal(read?.more, true);
+ assert.equal(read?.deletedCount, 0, 'older servers have no deleted records');
+ assert.equal(normalizeHistory({ status: {}, versions: [], deletedCount: 3 })?.deletedCount, 3);
+ assert.equal(normalizeHistory({ status: { changes: null }, versions: [] })?.status.branch, null, 'a version checked out on its own');
});
-test('a progress event is read only when it is one', () => {
- assert.deepEqual(historyProgressOf({ type: 'history-progress', op: 'commit', phase: 'store', done: 2, total: 5 }), { op: 'commit', phase: 'store', done: 2, total: 5 });
- assert.equal(historyProgressOf({ type: 'history' }), null);
- assert.equal(historyProgressOf({ type: 'history-progress', phase: 'dance' }), null);
+test('a version is called by its message, else by what it is', () => {
+ const named = version({ commit: 'a', name: 'Rough cut', at: 100 });
+ const auto = version({ commit: 'b', kind: 'auto', at: 200 });
+ const all = [named, auto];
+ assert.deepEqual(versionLabel(named, all), { key: '', name: 'Rough cut' });
+ assert.deepEqual(versionLabel(auto, all), { key: 'versions.kindAuto' });
+ assert.deepEqual(versionLabel(version({ kind: 'restore', restored: 'a' }), all), { key: 'versions.kindRestore', name: 'Rough cut' });
+ assert.deepEqual(versionLabel(version({ kind: 'restore', restored: 'b' }), all), { key: 'versions.kindRestoreAt', at: 200 });
+ assert.deepEqual(versionLabel(version({ kind: 'parked', name: 'idea' }), all), { key: 'versions.kindParked', name: 'idea' });
+ assert.deepEqual(versionLabel(version({ kind: 'saved' }), all), { key: 'versions.kindSaved' });
+ assert.equal(isAutomatic(auto), true);
+ assert.equal(isAutomatic(named), false);
+});
+
+test('versions saved on their own are hidden unless asked for; what they came from takes their place in the graph', () => {
+ const list = [
+ version({ commit: 'd', parents: ['c'] }),
+ version({ commit: 'c', kind: 'auto', parents: ['b'] }),
+ version({ commit: 'b', kind: 'agent', parents: ['a'] }),
+ version({ commit: 'a' }),
+ ];
+ assert.deepEqual(shownVersions(list, true, 'd').map((v) => v.commit), ['d', 'c', 'b', 'a']);
+ assert.deepEqual(shownVersions(list, false, 'd').map((v) => [v.commit, v.parents]), [['d', ['a']], ['a', []]]);
+ assert.deepEqual(shownVersions(list, false, 'c').map((v) => [v.commit, v.parents]), [['d', ['c']], ['c', ['a']], ['a', []]], 'the one checked out is always shown');
});
-test('how long ago; an unreadable time says nothing', () => {
- assert.deepEqual(historyAge(1000, 30_000), { unit: 'now' });
- assert.deepEqual(historyAge(0, 120_000), null);
- assert.deepEqual(historyAge(60_000, 60_000 + 5 * 60_000), { unit: 'minute', n: 5 });
- assert.deepEqual(historyAge(1, 1 + 3 * 3_600_000), { unit: 'hour', n: 3 });
- assert.equal(historyAge(Number.NaN, 0), null);
+test('the graph: one lane for a line of versions; a second lane where a version was checked out and committed on', () => {
+ const line = graphRows([version({ commit: 'c', parents: ['b'] }), version({ commit: 'b', parents: ['a'] }), version({ commit: 'a' })]);
+ assert.deepEqual(line.map((r) => r.col), [0, 0, 0]);
+ assert.deepEqual(line[0], { col: 0, up: [], down: [{ from: 0, to: 0 }], width: 1 });
+ assert.deepEqual(line[2].down, [], 'the first version ends the line');
+ /* "Another way" committed on One after checking it out; "Two" stays on a line of its own */
+ const fork = graphRows([version({ commit: 'way', parents: ['one'] }), version({ commit: 'two', parents: ['one'] }), version({ commit: 'one' })]);
+ assert.deepEqual(fork.map((r) => r.col), [0, 1, 0]);
+ assert.deepEqual(fork[1].up, [{ from: 0, to: 0 }], 'the first line passes Two by');
+ assert.deepEqual(fork[2].up, [{ from: 0, to: 0 }, { from: 1, to: 0 }], 'both lines meet at One');
+ assert.equal(fork[0].width, 2);
+});
+
+test('history search combines names, times and type filters without forcing a hidden automatic version into the list', () => {
+ const versions = [
+ version({ commit: 'auto', kind: 'auto', name: '', at: 21 }),
+ version({ commit: 'named', kind: 'named', name: 'V2 客户确认版', at: 20 }),
+ version({ commit: 'restore', kind: 'restore', at: 19 }),
+ version({ commit: 'saved', kind: 'saved', at: 18 }),
+ ];
+ const options = { types: new Set(HISTORY_VERSION_TYPES), namedOnly: false, search: '', textOf: (v: Version) => `${v.name} ${v.at}:30 ${historyVersionType(v)}` };
+ assert.deepEqual(filterHistoryVersions(versions, options), versions);
+ assert.deepEqual(filterHistoryVersions(versions, { ...options, search: ' v2 20:30 ' }).map((v) => v.commit), ['named'], 'case, full-width characters and multiple terms are normalized');
+ assert.deepEqual(filterHistoryVersions(versions, { ...options, types: new Set(['manual', 'restore']) }).map((v) => v.commit), ['named', 'restore', 'saved']);
+ assert.deepEqual(filterHistoryVersions(versions, { ...options, namedOnly: true }).map((v) => v.commit), ['named']);
+ assert.deepEqual(filterHistoryVersions(versions, { ...options, types: new Set() }), []);
+ assert.deepEqual(filterHistoryVersions(versions, { ...options, search: 'missing' }), []);
+ assert.equal(historyVersionType(version({ kind: 'before-restore' })), 'auto');
+ assert.equal(historyVersionType(version({ kind: 'parked' })), 'other');
+});
+
+test('a progress event is read only when it is one; a checkout says the folder moved', () => {
+ assert.deepEqual(historyProgressOf({ type: 'history-progress', op: 'save', phase: 'store', done: 2, total: 5 }), { op: 'save', phase: 'store', done: 2, total: 5 });
+ assert.equal(historyProgressOf({ type: 'history' }), null);
+ assert.equal(historyProgressOf({ type: 'history-progress', phase: 'dance' }), null);
+ assert.equal(historyMoved({ type: 'history', moved: true }), true);
+ assert.equal(historyMoved({ type: 'history' }), false);
});
test('a refusal is said in our own words', () => {
+ assert.equal(historyErrorKey({ status: 409, code: 'nothing' }), 'versions.errorNothing');
assert.equal(historyErrorKey({ status: 409, code: 'dirty' }), 'versions.errorDirty');
+ assert.equal(historyErrorKey({ status: 409, code: 'current' }), 'versions.errorDeleteCurrent');
+ assert.equal(historyErrorKey({ status: 409, code: 'deleted' }), 'versions.errorDeleted');
assert.equal(historyErrorKey({ status: 501, code: null }), 'versions.errorUnavailable');
assert.equal(historyErrorKey({ status: 500, code: null }), 'versions.errorGeneric');
});
diff --git a/packages/openfilm/studio/ui/src/lib/project-history.ts b/packages/openfilm/studio/ui/src/lib/project-history.ts
index b18692d..9df4805 100644
--- a/packages/openfilm/studio/ui/src/lib/project-history.ts
+++ b/packages/openfilm/studio/ui/src/lib/project-history.ts
@@ -1,44 +1,56 @@
/**
* A project's version history as the Version history panel shows it, and the calls that change it
- * (studio/server/history.mjs): git, as a person knows it from GitHub — commits on branches, uncommitted changes,
- * switching, merging — told in the film's terms. Every commit is the person's; nothing commits on its own.
+ * (studio/server/history.mjs). The dialog lists saved versions, plays their read-only snapshots, and shows the files
+ * each changed. Restoring a version checks it out; with unsaved edits the dialog offers to save them first.
*
- * GET /api/projects/:id/history → { status, commits }
- * GET /api/projects/:id/history/files → { held, ignored }: the film's files, and the others
- * GET /api/projects/:id/history/poster/:commit the film's picture when it was committed
- * POST /api/projects/:id/history/commit { message }
+ * GET /api/projects/:id/history[?limit=n] → { status, versions, more }
+ * GET /api/projects/:id/history/versions/:commit → { files }: what that version changed
+ * GET /api/projects/:id/history/versions/:commit/preview → { folder, doc, missing }: its read-only film
+ * POST /api/projects/:id/history/save { message? }
* POST /api/projects/:id/history/discard
- * POST /api/projects/:id/history/restore { commit } the commit's files, as uncommitted changes
- * POST /api/projects/:id/history/checkout { branch, create?, from?, carry? }
- * PATCH /api/projects/:id/history/branches/:name { name }
- * DELETE /api/projects/:id/history/branches/:name[?force=1]
- * POST /api/projects/:id/history/merge { branch, message, prefer? }
+ * POST /api/projects/:id/history/checkout { commit, discard? }
+ * POST /api/projects/:id/history/copy { commit, name } → { project }
+ * POST /api/projects/:id/history/delete { commits } move records to Deleted (current version protected)
+ * POST /api/projects/:id/history/recover { commits } recover records without checking them out
*
- * While an action runs, the project's events say how far it is ({ type: 'history-progress' }: HistoryProgress).
- * A refusal comes with a `code` ('dirty', 'nothing', 'conflict', 'unmerged', 'exists', 'name', 'current', 'none'),
- * which the panel says in its own words.
+ * While an action runs, the project's events say how far it is ({ type: 'history-progress' }: HistoryProgress); when
+ * it is done, `{ type: 'history', moved? }` (`moved`: the folder's files changed). A refusal comes with a `code`
+ * ('nothing', 'dirty', 'none'), which the panel says in its own words.
*/
+import type { Film } from '@/api';
+
export interface Counts { added: number; removed: number; edited: number }
+export interface VersionPreview { folder: string; doc: Film | null; missing: string[] }
/** What changed, as the film tells it (see history.mjs Summary). */
export interface Summary { scenes: Counts; sounds: Counts; stage: boolean; other: boolean }
-export interface Branch { name: string; commit: string; at: number; message: string; current: boolean; parked: boolean }
-/** The film's files now (what a commit keeps), and how many other files the folder has (never kept). */
-export interface HistoryFiles { held: number; heldBytes: number; ignored: number }
+/** A file changed, by its path in the project, as git's status letters say it. */
+export interface Change { path: string; change: 'added' | 'modified' | 'deleted' }
export interface HistoryStatus {
- branch: string;
+ /** the version checked out; null: none yet */
head: string | null;
- branches: Branch[];
- changes: { count: number; summary: Summary } | null;
- files: HistoryFiles | null;
+ /** the branch checked out; null: a version checked out on its own (git's detached HEAD) */
+ branch: string | null;
+ /** what the folder holds that the version checked out does not; null: nothing */
+ changes: { count: number; summary: Summary; files: Change[] } | null;
}
-/** A file, by its path in the project, and its size. */
-export interface HistoryFile { path: string; size: number }
-/** How far an action is: `phase` reading the film's files, keeping media, writing files, or updating the history. */
+/** How far an action is: `phase` reading the files, keeping media, writing files, or updating the history. */
export interface HistoryProgress { op: string; phase: 'scan' | 'store' | 'write' | 'migrate'; done: number; total: number }
-export interface Commit { commit: string; parents: string[]; at: number; message: string; body: string; tags: string[]; summary: Summary }
-export interface HistoryState { status: HistoryStatus; commits: Commit[] }
+/** What a version is (history.mjs Kind). */
+export type VersionKind = 'named' | 'saved' | 'auto' | 'agent' | 'before-restore' | 'restore' | 'upgrade' | 'parked';
+export interface Version {
+ commit: string;
+ parents: string[];
+ at: number;
+ kind: VersionKind;
+ /** the person's message; '' when it has none and is told by its kind */
+ name: string;
+ /** the version a 'restore' of an earlier edition brought back */
+ restored: string | null;
+}
+export interface HistoryState { status: HistoryStatus; versions: Version[]; more: boolean; deletedCount: number }
+const KINDS = new Set<VersionKind>(['named', 'saved', 'auto', 'agent', 'before-restore', 'restore', 'upgrade', 'parked']);
const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
const counts = (raw: unknown): Counts => {
const c = (raw ?? {}) as Record<string, unknown>;
@@ -49,73 +61,149 @@ const summaryOf = (raw: unknown): Summary => {
return { scenes: counts(s.scenes), sounds: counts(s.sounds), stage: s.stage === true, other: s.other === true };
};
const text = (v: unknown) => (typeof v === 'string' ? v : '');
+const changeList = (raw: unknown): Change[] => (Array.isArray(raw) ? raw : []).flatMap((f) => {
+ const r = f as Record<string, unknown> | null;
+ if (!r || typeof r.path !== 'string') return [];
+ return [{ path: r.path, change: r.change === 'added' || r.change === 'deleted' ? r.change : 'modified' }];
+});
/** The server's answer, checked: anything unreadable is dropped rather than drawn as an empty row. */
export function normalizeHistory(raw: unknown): HistoryState | null {
- const body = raw as { status?: Record<string, unknown>; commits?: unknown } | null;
+ const body = raw as { status?: Record<string, unknown>; versions?: unknown; more?: unknown; deletedCount?: unknown } | null;
const s = body?.status;
- if (!s || typeof s.branch !== 'string') return null;
- const branches: Branch[] = (Array.isArray(s.branches) ? s.branches : []).flatMap((b) => {
- const r = b as Record<string, unknown> | null;
- return r && typeof r.name === 'string' && r.name
- ? [{ name: r.name, commit: text(r.commit), at: num(r.at), message: text(r.message), current: r.current === true, parked: r.parked === true }]
- : [];
- });
- const changes = s.changes && typeof s.changes === 'object'
- ? { count: num((s.changes as Record<string, unknown>).count), summary: summaryOf((s.changes as Record<string, unknown>).summary) }
- : null;
- const commits: Commit[] = (Array.isArray(body.commits) ? body.commits : []).flatMap((c) => {
- const r = c as Record<string, unknown> | null;
+ if (!s || typeof s !== 'object' || !Array.isArray(body.versions)) return null;
+ const c = s.changes as Record<string, unknown> | null | undefined;
+ const changes = c && typeof c === 'object' ? { count: num(c.count), summary: summaryOf(c.summary), files: changeList(c.files) } : null;
+ const versions: Version[] = body.versions.flatMap((v) => {
+ const r = v as Record<string, unknown> | null;
if (!r || typeof r.commit !== 'string' || !r.commit) return [];
return [{
commit: r.commit,
- parents: Array.isArray(r.parents) ? r.parents.filter((p): p is string => typeof p === 'string') : [],
- at: num(r.at), message: text(r.message), body: text(r.body),
- tags: Array.isArray(r.tags) ? r.tags.filter((t): t is string => typeof t === 'string' && !!t) : [],
- summary: summaryOf(r.summary),
+ parents: Array.isArray(r.parents) ? r.parents.filter((p): p is string => typeof p === 'string' && !!p) : [],
+ at: num(r.at),
+ kind: KINDS.has(r.kind as VersionKind) ? r.kind as VersionKind : 'named',
+ name: text(r.name),
+ restored: typeof r.restored === 'string' && r.restored ? r.restored : null,
}];
});
- const f = s.files as Record<string, unknown> | null | undefined;
- const files = f && typeof f === 'object' ? { held: num(f.held), heldBytes: num(f.heldBytes), ignored: num(f.ignored) } : null;
- return { status: { branch: s.branch, head: typeof s.head === 'string' ? s.head : null, branches, changes, files }, commits };
+ return {
+ status: { head: typeof s.head === 'string' ? s.head : null, branch: typeof s.branch === 'string' ? s.branch : null, changes },
+ versions,
+ more: body.more === true,
+ deletedCount: Math.max(0, num(body.deletedCount)),
+ };
}
/**
- * What changed, as the parts of a sentence, in the order a person reads them: scenes before sounds, added before
- * edited before removed. Each is a string key and its count (the sentence is the strings' job). Nothing that a scene
- * or a sound tells: 'look' (the picture's size, or a file the scenes share) when that changed, else 'same'.
+ * How a version is called, as a string key and what fills it: its message when it has one; else what kind of version
+ * it is. A restore (an earlier edition's) names the version it brought back, by its message, else by when it was
+ * saved (`at`), else (not in the list) says it was an earlier one.
*/
-export function summaryParts(summary: Summary): Array<{ key: string; n: number }> {
- const parts: Array<{ key: string; n: number }> = [];
- for (const [what, c] of [['scenes', summary.scenes], ['sounds', summary.sounds]] as const) {
- if (c.added) parts.push({ key: `${what}Added`, n: c.added });
- if (c.edited) parts.push({ key: `${what}Edited`, n: c.edited });
- if (c.removed) parts.push({ key: `${what}Removed`, n: c.removed });
+export function versionLabel(v: Version, all: readonly Version[]): { key: string; name?: string; at?: number } {
+ if (v.name && v.kind !== 'parked') return { key: '', name: v.name };
+ switch (v.kind) {
+ case 'restore': {
+ const from = all.find((x) => x.commit === v.restored);
+ if (!from) return { key: 'versions.kindRestoreOlder' };
+ return from.name && from.kind !== 'parked' ? { key: 'versions.kindRestore', name: from.name } : { key: 'versions.kindRestoreAt', at: from.at };
+ }
+ case 'parked': return { key: 'versions.kindParked', name: v.name };
+ case 'auto': return { key: 'versions.kindAuto' };
+ case 'agent': return { key: 'versions.kindAgent' };
+ case 'before-restore': return { key: 'versions.kindBeforeRestore' };
+ case 'upgrade': return { key: 'versions.kindUpgrade' };
+ default: return { key: 'versions.kindSaved' };
}
- if (!parts.length) parts.push({ key: summary.stage || summary.other ? 'look' : 'same', n: 0 });
- return parts;
}
-export type HistoryAge =
- | { unit: 'now' }
- | { unit: 'minute' | 'hour' | 'day'; n: number };
+/** Saved on its own, not by the person: listed when the history type filter includes automatic versions. */
+export const isAutomatic = (v: Version) => v.kind === 'auto' || v.kind === 'agent' || v.kind === 'before-restore' || v.kind === 'upgrade';
+
+export const HISTORY_VERSION_TYPES = ['manual', 'auto', 'restore', 'other'] as const;
+export type HistoryVersionType = typeof HISTORY_VERSION_TYPES[number];
+
+export function historyVersionType(v: Version): HistoryVersionType {
+ if (isAutomatic(v)) return 'auto';
+ if (v.kind === 'restore') return 'restore';
+ return v.kind === 'parked' ? 'other' : 'manual';
+}
+
+/** Filters affect the list only; the selected preview and the current editing entry remain independent. */
+export function filterHistoryVersions(versions: readonly Version[], {
+ types, namedOnly, search, textOf,
+}: {
+ types: ReadonlySet<HistoryVersionType>;
+ namedOnly: boolean;
+ search: string;
+ textOf: (v: Version) => string;
+}): Version[] {
+ const fold = (s: string) => s.normalize('NFKC').toLocaleLowerCase();
+ const terms = fold(search).trim().split(/\s+/).filter(Boolean);
+ return versions.filter((v) => {
+ if (!types.has(historyVersionType(v)) || (namedOnly && (!v.name || v.kind === 'parked'))) return false;
+ const text = fold(textOf(v));
+ return terms.every((term) => text.includes(term));
+ });
+}
+
+/**
+ * The versions the graph shows: all of them, or (`showAuto` false) those the person saved, and the one checked out
+ * whatever it is. A hidden version's place in the graph is taken by what it came from: each shown version's parents
+ * are its nearest shown ancestors.
+ */
+export function shownVersions(versions: readonly Version[], showAuto: boolean, head: string | null): Version[] {
+ if (showAuto) return [...versions];
+ const byId = new Map(versions.map((v) => [v.commit, v]));
+ const shown = (v: Version) => !isAutomatic(v) || v.commit === head;
+ const nearest = (id: string, seen = new Set<string>()): string[] => {
+ const v = byId.get(id);
+ if (!v) return [id];
+ if (shown(v)) return [id];
+ if (seen.has(id)) return [];
+ seen.add(id);
+ return v.parents.flatMap((p) => nearest(p, seen));
+ };
+ return versions.filter(shown).map((v) => ({ ...v, parents: [...new Set(v.parents.flatMap((p) => nearest(p)))] }));
+}
/**
- * How long ago, as a unit and a number (the sentence is the strings' job). An unreadable time gives null: no time is
- * better than "NaN minutes ago". A clock slightly ahead gives a future time; that counts as just now.
+ * The graph, as VS Code's Source Control draws it: a row per version (newest first), each in a lane (`col`), with the
+ * lanes that run through the row above and below it. `up`: lanes coming in from the row above (each with the lane it
+ * ends in at this row's dot: its own, or this row's when it reaches this version); `down`: lanes going on to the row
+ * below (each from this row's dot when it leaves for a parent of this version, else straight on).
*/
-export function historyAge(at: number, now: number): HistoryAge | null {
- if (!Number.isFinite(at) || at <= 0) return null;
- const minutes = Math.floor((now - at) / 60_000);
- if (minutes < 1) return { unit: 'now' };
- if (minutes < 60) return { unit: 'minute', n: minutes };
- const hours = Math.floor(minutes / 60);
- if (hours < 24) return { unit: 'hour', n: hours };
- return { unit: 'day', n: Math.floor(hours / 24) };
+export interface GraphRow { col: number; up: Array<{ from: number; to: number }>; down: Array<{ from: number; to: number }>; width: number }
+export function graphRows(versions: readonly Version[]): GraphRow[] {
+ let lanes: Array<string | null> = [];
+ const rows: GraphRow[] = [];
+ const free = () => { const i = lanes.indexOf(null); return i < 0 ? lanes.length : i; };
+ for (const v of versions) {
+ let col = lanes.indexOf(v.commit);
+ const up: GraphRow['up'] = [];
+ lanes.forEach((id, i) => { if (id) up.push({ from: i, to: id === v.commit ? col : i }); });
+ /* a tip: no line comes into it from above */
+ if (col < 0) { col = free(); lanes[col] = v.commit; }
+ /* this version's lanes end here, at its dot; its parents go on from it */
+ lanes = lanes.map((id) => (id === v.commit ? null : id));
+ const leaving = new Set<number>();
+ v.parents.forEach((p, n) => {
+ const at = lanes.indexOf(p);
+ if (at >= 0 && n > 0) { leaving.add(at); return; }
+ const lane = n === 0 && lanes[col] === null ? col : at >= 0 ? at : free();
+ lanes[lane] = p;
+ leaving.add(lane);
+ });
+ while (lanes.length && lanes[lanes.length - 1] === null) lanes.pop();
+ const down: GraphRow['down'] = [];
+ lanes.forEach((id, i) => { if (id) down.push({ from: leaving.has(i) ? col : i, to: i }); });
+ rows.push({ col, up, down, width: 0 });
+ }
+ const width = Math.max(1, ...rows.map((r) => Math.max(r.col, ...r.up.map((l) => l.from), ...r.down.map((l) => l.to)) + 1));
+ return rows.map((r) => ({ ...r, width }));
}
/** A history call's outcome: done (with what came back), or refused with the server's `code`. */
-export type HistoryResult<T = Record<string, unknown>> = { ok: true; body: T } | { ok: false; status: number; code: string | null; commits?: number };
+export type HistoryResult<T = Record<string, unknown>> = { ok: true; body: T } | { ok: false; status: number; code: string | null };
async function call<T = Record<string, unknown>>(projectId: string, path: string, method = 'GET', json?: unknown): Promise<HistoryResult<T>> {
try {
@@ -125,53 +213,37 @@ async function call<T = Record<string, unknown>>(projectId: string, path: string
});
const body = await res.json().catch(() => ({})) as Record<string, unknown>;
if (res.ok) return { ok: true, body: body as T };
- return { ok: false, status: res.status, code: typeof body.code === 'string' ? body.code : null, ...(typeof body.commits === 'number' ? { commits: body.commits } : {}) };
+ return { ok: false, status: res.status, code: typeof body.code === 'string' ? body.code : null };
} catch {
return { ok: false, status: 503, code: null };
}
}
-const fileList = (raw: unknown): HistoryFile[] => (Array.isArray(raw) ? raw : []).flatMap((f) => {
- const r = f as Record<string, unknown> | null;
- return r && typeof r.path === 'string' ? [{ path: r.path, size: num(r.size) }] : [];
-});
-
export const historyApi = {
- load: async (id: string) => {
- const r = await call(id, '');
+ preview: (id: string, commit: string) => call<VersionPreview>(id, `/versions/${encodeURIComponent(commit)}/preview`),
+ load: async (id: string, limit = 50, deleted = false) => {
+ const r = await call(id, `?limit=${limit}${deleted ? '&deleted=1' : ''}`);
return r.ok ? normalizeHistory(r.body) : null;
},
- files: async (id: string): Promise<{ held: HistoryFile[]; ignored: HistoryFile[] } | null> => {
- const r = await call(id, '/files');
- return r.ok ? { held: fileList(r.body.held), ignored: fileList(r.body.ignored) } : null;
+ versionFiles: async (id: string, commit: string): Promise<Change[] | null> => {
+ const r = await call(id, `/versions/${commit}`);
+ return r.ok ? changeList(r.body.files) : null;
},
- commit: (id: string, message: string) => call(id, '/commit', 'POST', { message }),
- discard: (id: string) => call(id, '/discard', 'POST', {}),
- restore: (id: string, commit: string) => call(id, '/restore', 'POST', { commit }),
- checkout: (id: string, o: { branch: string; create?: boolean; from?: string; carry?: 'leave' | 'bring' }) =>
- call<{ parkedBack?: boolean }>(id, '/checkout', 'POST', o),
- rename: (id: string, from: string, name: string) => call(id, `/branches/${encodeURIComponent(from)}`, 'PATCH', { name }),
- remove: (id: string, name: string, force = false) => call(id, `/branches/${encodeURIComponent(name)}${force ? '?force=1' : ''}`, 'DELETE'),
- merge: (id: string, o: { branch: string; message: string; prefer?: 'ours' | 'theirs' }) => call<{ merged?: boolean }>(id, '/merge', 'POST', o),
+ save: (id: string, message: string) => call<{ commit: string }>(id, '/save', 'POST', { message }),
+ discard: (id: string) => call<{ missing?: string[] }>(id, '/discard', 'POST', {}),
+ checkout: (id: string, commit: string, discard = false) => call<{ commit: string; missing?: string[] }>(id, '/checkout', 'POST', { commit, discard }),
+ copy: (id: string, commit: string, name: string) => call<{ project: { id: string; name: string }; missing?: string[] }>(id, '/copy', 'POST', { commit, name }),
+ delete: (id: string, commits: string[]) => call<{ commits: string[] }>(id, '/delete', 'POST', { commits }),
+ recover: (id: string, commits: string[]) => call<{ commits: string[] }>(id, '/recover', 'POST', { commits }),
};
-/** The picture of a commit (taken when it was committed). */
-export const commitPoster = (projectId: string, commit: string) =>
- `/api/projects/${encodeURIComponent(projectId)}/history/poster/${commit}`;
-
-/**
- * Which sentence a refusal gets: always our own words, never the server's text. Codes the panel handles with a
- * question of its own ('dirty' before going back, 'conflict' on a merge, 'unmerged' on a delete) are asked, not said.
- */
+/** Which sentence a refusal gets: always our own words, never the server's text. */
export function historyErrorKey(result: { status: number; code: string | null }): string {
switch (result.code) {
- case 'dirty': return 'versions.errorDirty';
case 'nothing': return 'versions.errorNothing';
- case 'conflict': return 'versions.errorCarry';
- case 'exists': return 'versions.errorExists';
- case 'name': return 'versions.errorName';
- case 'message': return 'versions.errorMessage';
- case 'current': return 'versions.errorCurrent';
+ case 'dirty': return 'versions.errorDirty';
+ case 'current': return 'versions.errorDeleteCurrent';
+ case 'deleted': return 'versions.errorDeleted';
default: break;
}
if (result.status === 404 || result.status === 501 || result.status === 503) return 'versions.errorUnavailable';
@@ -186,3 +258,6 @@ export function historyProgressOf(raw: unknown): HistoryProgress | null {
if (!phase) return null;
return { op: text(r.op), phase, done: num(r.done), total: num(r.total) };
}
+
+/** Whether a project event says the folder's files changed with the history (a checkout, a discard). */
+export const historyMoved = (event: { type: string; moved?: unknown }) => event.type === 'history' && event.moved === true;
diff --git a/packages/openfilm/studio/ui/src/lib/use-film-subtitles.ts b/packages/openfilm/studio/ui/src/lib/use-film-subtitles.ts
index 22e99ef..44be757 100644
--- a/packages/openfilm/studio/ui/src/lib/use-film-subtitles.ts
+++ b/packages/openfilm/studio/ui/src/lib/use-film-subtitles.ts
@@ -26,6 +26,7 @@ import {
type SubtitleTranscribeResult,
type SubtitleTranslateResult,
} from './subtitles';
+import { historyMoved } from './project-history';
import { useSubtitleStyle } from './use-subtitle-style';
/** Changes come in bursts (an agent writes several files): one request after they settle. */
@@ -69,7 +70,8 @@ export function useFilmSubtitles(projectId: string): FilmSubtitles {
void refresh();
let timer: ReturnType<typeof setTimeout> | null = null;
const stop = projectEvents(projectId, (event) => {
- if (event.type !== 'film' && event.type !== 'files') return;
+ /* a version restored may bring other corrections of the lines (Studio's own file, which no folder event tells) */
+ if (event.type !== 'film' && event.type !== 'files' && !historyMoved(event)) return;
if (timer) clearTimeout(timer);
timer = setTimeout(() => { timer = null; void refresh(); }, REFRESH_MS);
});
diff --git a/packages/openfilm/studio/ui/src/lib/use-subtitle-style.ts b/packages/openfilm/studio/ui/src/lib/use-subtitle-style.ts
index 2b53157..f68bdfb 100644
--- a/packages/openfilm/studio/ui/src/lib/use-subtitle-style.ts
+++ b/packages/openfilm/studio/ui/src/lib/use-subtitle-style.ts
@@ -4,10 +4,14 @@
* and not in film.html, so an agent rewriting the film never resets it.
*
* A project whose style was never changed starts from the look this person used last (this browser remembers it,
- * see readLastSubtitleStyle), else the default; nothing is written for it until the person changes something.
+ * see readLastSubtitleStyle), else the default; nothing is written for it until the person changes something. A
+ * version restored (the project's `{ type: 'history', moved }` event) brings its own: read again.
*/
import * as React from 'react';
+import { projectEvents } from '@/api';
+import { historyMoved } from './project-history';
+
import {
fetchSubtitleStyle,
readLastSubtitleStyle,
@@ -28,6 +32,8 @@ export function useSubtitleStyle(projectId: string): [SubtitleStyle, React.Dispa
const saved = React.useRef<string | null>(null);
const styleRef = React.useRef(style);
styleRef.current = style;
+ const [restored, setRestored] = React.useState(0);
+ React.useEffect(() => projectEvents(projectId, (event) => { if (historyMoved(event)) setRestored((n) => n + 1); }), [projectId]);
React.useEffect(() => {
saved.current = null;
@@ -45,7 +51,7 @@ export function useSubtitleStyle(projectId: string): [SubtitleStyle, React.Dispa
if (!ask.signal.aborted) saved.current = '';
});
return () => ask.abort();
- }, [projectId]);
+ }, [projectId, restored]);
React.useEffect(() => {
/* not loaded yet: writing now could overwrite the project's own style */
diff --git a/packages/openfilm/studio/ui/src/lib/video-export-preset.test.ts b/packages/openfilm/studio/ui/src/lib/video-export-preset.test.ts
new file mode 100644
index 0000000..6a432fc
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/video-export-preset.test.ts
@@ -0,0 +1,49 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ DEFAULT_VIDEO_EXPORT,
+ legacySocialVideo,
+ patchVideoExport,
+ readVideoExport,
+ videoExportPreset,
+} from './video-export-preset.ts';
+
+test('default video follows the current frame and project rate, while platform presets fill editable video settings', () => {
+ assert.deepEqual(videoExportPreset('default', 60), DEFAULT_VIDEO_EXPORT);
+ const vertical = videoExportPreset('douyin', 60);
+ assert.deepEqual(
+ [vertical.preset, vertical.frame, vertical.shortEdge, vertical.fps, vertical.codec, vertical.audio, vertical.burn],
+ ['douyin', '9:16', 1080, 30, 'h264', true, true]
+ );
+ assert.equal(videoExportPreset('youtube-4k', 23.976).fps, 23.976);
+ assert.equal(videoExportPreset('youtube-4k', 60).shortEdge, 2160);
+ assert.equal(videoExportPreset('bilibili', 60).burn, false);
+ assert.deepEqual(videoExportPreset('unknown', 60), DEFAULT_VIDEO_EXPORT);
+});
+
+test('manual edits become custom, and selecting Default restores the default bundle', () => {
+ const platform = videoExportPreset('douyin', 60);
+ assert.equal(patchVideoExport(platform, { shortEdge: 1080 }), platform, 'choosing the current value is not an edit');
+ const custom = patchVideoExport(platform, { codec: 'hevc', shortEdge: 720 });
+ assert.deepEqual(
+ [custom.preset, custom.frame, custom.codec, custom.shortEdge, custom.fps],
+ ['custom', '9:16', 'hevc', 720, 30]
+ );
+ assert.deepEqual(patchVideoExport(custom, videoExportPreset('default', 60)), DEFAULT_VIDEO_EXPORT);
+});
+
+test('previous video and social settings migrate without discarding the chosen encoding, quality or subtitle behavior', () => {
+ assert.deepEqual(readVideoExport(), DEFAULT_VIDEO_EXPORT);
+ const previous = readVideoExport({ codec: 'hevc', shortEdge: 720, audio: false });
+ assert.deepEqual(
+ [previous.preset, previous.codec, previous.shortEdge, previous.audio],
+ ['custom', 'hevc', 720, true]
+ );
+ assert.equal(readVideoExport(videoExportPreset('youtube', 30)).preset, 'youtube');
+ const social = legacySocialVideo('douyin', 'master', 'off', 60);
+ assert.deepEqual(
+ [social.preset, social.frame, social.fps, social.quality, social.burn],
+ ['custom', '9:16', 30, 'master', false]
+ );
+ assert.equal(legacySocialVideo('douyin', 'high', 'auto', 60).preset, 'douyin');
+});
diff --git a/packages/openfilm/studio/ui/src/lib/video-export-preset.ts b/packages/openfilm/studio/ui/src/lib/video-export-preset.ts
new file mode 100644
index 0000000..e643e15
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/video-export-preset.ts
@@ -0,0 +1,78 @@
+/** Platform choices fill the same editable settings as the default video preset. */
+import type { FilmFrameFill, FilmFrameId } from './film-frame.ts';
+import { exportPreset, presetFps, type ExportQuality, type ExportVideoCodec } from './export-spec.ts';
+
+export interface VideoExportSettings {
+ /** 'default', 'custom', or a platform id. */
+ preset: string;
+ codec: ExportVideoCodec;
+ shortEdge: number;
+ fps: number | 'source';
+ quality: ExportQuality;
+ frame: FilmFrameId | 'current';
+ fill: FilmFrameFill;
+ audio: boolean;
+ burn: boolean;
+ sidecar: 'none' | 'srt' | 'vtt';
+}
+
+export const DEFAULT_VIDEO_EXPORT: VideoExportSettings = {
+ preset: 'default',
+ codec: 'h264',
+ shortEdge: 1080,
+ fps: 'source',
+ quality: 'high',
+ frame: 'current',
+ fill: 'contain',
+ audio: true,
+ burn: true,
+ sidecar: 'none',
+};
+
+export function videoExportPreset(id: string, projectFps: number): VideoExportSettings {
+ const platform = exportPreset(id);
+ return platform
+ ? {
+ ...DEFAULT_VIDEO_EXPORT,
+ preset: platform.id,
+ frame: platform.frame,
+ shortEdge: platform.shortEdge,
+ fps: presetFps(platform, projectFps),
+ burn: platform.burnSubtitles,
+ }
+ : { ...DEFAULT_VIDEO_EXPORT };
+}
+
+/** Editing a preset makes a custom configuration; picking a preset explicitly replaces that label as well. */
+export function patchVideoExport(
+ current: VideoExportSettings,
+ patch: Partial<VideoExportSettings>
+): VideoExportSettings {
+ if (Object.entries(patch).every(([key, value]) => current[key as keyof VideoExportSettings] === value))
+ return current;
+ return { ...current, ...patch, preset: patch.preset ?? 'custom' };
+}
+
+/** Keep older video settings. As before, opening Export starts with sound enabled. */
+export function readVideoExport(raw?: Partial<VideoExportSettings>): VideoExportSettings {
+ const video = { ...DEFAULT_VIDEO_EXPORT, ...raw, audio: true };
+ if (raw?.preset === 'default' || raw?.preset === 'custom' || exportPreset(raw?.preset)) return video;
+ const standard = Object.entries(DEFAULT_VIDEO_EXPORT).every(
+ ([key, value]) => key === 'preset' || video[key as keyof VideoExportSettings] === value
+ );
+ return { ...video, preset: standard ? 'default' : 'custom' };
+}
+
+/** The old separate social page becomes one video preset, preserving its quality and subtitle choices. */
+export function legacySocialVideo(
+ id: string,
+ quality: ExportQuality | undefined,
+ subtitles: 'auto' | 'on' | 'off' | undefined,
+ projectFps: number
+): VideoExportSettings {
+ const video = videoExportPreset(id, projectFps);
+ return patchVideoExport(video, {
+ quality: quality ?? video.quality,
+ burn: subtitles === 'on' ? true : subtitles === 'off' ? false : video.burn,
+ });
+}
diff --git a/packages/openfilm/studio/ui/src/lib/whats-new.test.ts b/packages/openfilm/studio/ui/src/lib/whats-new.test.ts
index 15f332e..96647e2 100644
--- a/packages/openfilm/studio/ui/src/lib/whats-new.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/whats-new.test.ts
@@ -22,12 +22,12 @@ test('after an update: the notes since the version last shown, the newest first;
assert.equal(releaseNotes('0.2.0', list), null);
});
-test('each release says what is new in every language, a few lines each', () => {
+test('each release says what is new in every language, a line a change', () => {
for (const r of RELEASES) {
assert.match(r.version, /^\d+\.\d+\.\d+$/);
assert.match(r.date, /^\d{4}-\d{2}-\d{2}$/);
for (const [language, notes] of Object.entries(r.notes)) {
- assert.ok(notes.length >= 1 && notes.length <= 6, `${r.version} ${language}: 1 to 6 lines`);
+ assert.ok(notes.length >= 1 && notes.length <= 24, `${r.version} ${language}: 1 to 24 lines`);
for (const n of notes) assert.ok(n.text.trim().length > 0, `${r.version} ${language}`);
}
}
diff --git a/packages/openfilm/studio/ui/src/lib/whats-new.ts b/packages/openfilm/studio/ui/src/lib/whats-new.ts
index 2fa82c0..bdcabd6 100644
--- a/packages/openfilm/studio/ui/src/lib/whats-new.ts
+++ b/packages/openfilm/studio/ui/src/lib/whats-new.ts
@@ -1,10 +1,12 @@
/**
- * What each release brings, said to the person after an update: a few lines a release, in every language Studio
- * speaks (a release without them all does not compile), grouped as new, improved and fixed. The newest first.
+ * What each release brings, said to the person after an update, in every language Studio speaks (a release without them
+ * all does not compile), grouped as new, improved and fixed. The newest first. The dialog shows every release's under
+ * the newest, so this is the history people read in their own language: the changelog on GitHub is in English.
*
* Written when a release is made (the "Version packages" pull request): the changesets say everything that changed,
- * for the changelog; these say what a person would notice, in their words, at most six lines. A version without them
- * fails the tests (whats-new.test.ts), so that pull request cannot be merged until they are written.
+ * for the changelog; these say every change a person would notice, in their words, one line each (at most 24). A
+ * version without them fails the tests (whats-new.test.ts), so that pull request cannot be merged until they are
+ * written.
*
* After an update the release notes since the version last shown appear once (lib's notesToShow; Studio's prefs keep
* `seenVersion`). A new install shows none: there is nothing it was updated from.