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: a canvas that changes like CapCut's, and editor polish (#23)

riverisbuildinge688860dec67
diff --git a/.changeset/desktop-dialog-export-folder.md b/.changeset/desktop-dialog-export-folder.md
new file mode 100644
index 0000000..5c3c4fa
--- /dev/null
+++ b/.changeset/desktop-dialog-export-folder.md
@@ -0,0 +1,6 @@
+---
+"openfilm": patch
+"@openfilm/desktop": patch
+---
+
+Studio: the Desktop dialog is laid out again, with the app's window and the agents it works with beside eight clear points (two-way chat with the editor, live changes, media dropped in, any agent, faster preview and export, no terminal or dependencies, updates, kept chats) and the download. A layer selected on the picture lets go when the timeline is pressed or the playhead leaves its clip, and the picture no longer gets a ring of its own while something is selected. The bar over a selection shows at once, without rising. The subtitle row's menu can hide it, and says where it comes back. The export's "Save to" is one button with the folder's name; in the desktop app it opens the system's folder dialog instead of a typed path. A track's name shows under its badge, so the track heads keep their width. The examples follow the Projects view (cards or rows). A media folder just named stays in place until the listing has it, and a click on empty space in the media pane lets go of what is selected. The Desktop dialog's download sits bottom right beside the version, and its agents' names show on hover. Settings → Models shows a choice only while its provider is connected. Files dragged from the computer onto a media folder go into that folder. A page previewed in the media pane starts at 0 when another is picked. The projects' sort by name says so, a folder's name sits in the Projects title (its projects start where the list does), folders in the list view show their covers, and removing a project whose folder is gone says that nothing of it is left on disk. Projects folders can hold folders, with the trail to them in the title. The media pane can show a list as well as a grid, says why a web page cannot go into a folder, and no longer picks a file when a drag starts. The export's "Save to" opens the system's folder dialog in a browser too (Studio opens it on this computer), exports go to the Desktop by default, and the frame rate is picked from an editor's list (10 to 60 fps, 23.976, 29.97, 59.94, and 120). `pnpm dev` refuses to start a second time for the same checkout. Studio works inside another app's frame (an agent's preview pane): its sign-in has a partitioned twin a frame keeps, and the film's pages no longer refuse to be framed there. A clip dragged onto another clip of its own track goes in between them, as in an editor's main track, instead of cutting it (⌥ still overwrites). A transcript that runs past the end of its file (made from another version of it, such as one sped up in place) is listed to be made again, so its subtitles no longer drift and lose their end. A browser that opens Studio's address without its key is told so, and which address lets it in, instead of a page that seems to reconnect forever. The manual tells agents to change a clip's speed only with `speed`, so its subtitles stay with it. A media file opens playing from its start, with one full-screen button in its bar. Ratios add 3:4, 3:2, 2:3, 2.39:1, 1.85:1 and 2:1 and any ratio typed from 1:4 to 4:1. The project's frame rate is picked from the same list as the export's (23.976 to 60, 48 and 120), in Studio's own menu. Web pages can be moved into folders like any media: their links (and those of every page pointing at what moved) are written again; paths a page makes while it runs are named before the move. The viewer's ratio button and the inspector change the film's canvas itself, at any time, as CapCut does: the shapes CapCut offers (and Fit to the first picture, and any typed size), the canvas's short side kept, and the film scaled into it whole, centered, in one undoable step; the inspector gives the words that ask the agent to lay the film out again. A delivery frame (bars or a crop) is now the export's alone. The export dialog's destinations scroll, so its note is never cut. A web page that sets no size of its own keeps the size it was laid out at when the canvas changes shape (film.html's new `size` on a page clip, which Studio writes), so it is scaled into place like a video instead of being laid out again smaller.
diff --git a/apps/desktop/shell/bridge.ts b/apps/desktop/shell/bridge.ts
index 16e98b2..556d453 100644
--- a/apps/desktop/shell/bridge.ts
+++ b/apps/desktop/shell/bridge.ts
@@ -22,7 +22,7 @@ interface Native {
hello(): Promise<{ flavor: string; version: string; ffmpeg: unknown; update: unknown; chatOpen: boolean; chatWidth: number; chatMin: number; studioMin: number; fullScreen: boolean }>;
pathForFile(file: File): string;
revealPath(path: string): Promise<void>;
- pickFolder(): Promise<string | null>;
+ pickFolder(options?: { title?: string; button?: string; at?: string }): Promise<string | null>;
capture(rect: { x: number; y: number; width: number; height: number }): Promise<string | null>;
agents: NonNullable<StudioHost['agents']>;
localAgents: Record<string, unknown>;
diff --git a/apps/desktop/src/folder-dialog.mjs b/apps/desktop/src/folder-dialog.mjs
new file mode 100644
index 0000000..2521a56
--- /dev/null
+++ b/apps/desktop/src/folder-dialog.mjs
@@ -0,0 +1,24 @@
+// @ts-check
+import { isAbsolute } from 'node:path';
+
+/**
+ * The system's folder dialog, as Studio asks for it: to open a project (no options, the File menu's words), or with
+ * Studio's own words and starting folder (the export's "Save to"). What the page sends is checked: short text only,
+ * and a starting folder only when it is a full path.
+ * @param {unknown} options
+ * @returns {import('electron').OpenDialogOptions}
+ */
+export function folderDialogOptions(options) {
+ const o = options && typeof options === 'object' ? /** @type {Record<string, unknown>} */ (options) : {};
+ const text = (/** @type {unknown} */ v) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, 120) : null);
+ const title = text(o.title) ?? 'Open Project';
+ const at = typeof o.at === 'string' && o.at.length < 4096 && isAbsolute(o.at) ? o.at : null;
+ return {
+ title,
+ /* macOS shows no title on this dialog: the message line says it instead */
+ message: title,
+ buttonLabel: text(o.button) ?? 'Open',
+ ...(at ? { defaultPath: at } : {}),
+ properties: ['openDirectory', 'createDirectory'],
+ };
+}
diff --git a/apps/desktop/src/folder-dialog.test.mjs b/apps/desktop/src/folder-dialog.test.mjs
new file mode 100644
index 0000000..9ef31ab
--- /dev/null
+++ b/apps/desktop/src/folder-dialog.test.mjs
@@ -0,0 +1,26 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { folderDialogOptions } from './folder-dialog.mjs';
+
+test('with no options the dialog opens a project', () => {
+ const o = folderDialogOptions(undefined);
+ assert.equal(o.title, 'Open Project');
+ assert.equal(o.buttonLabel, 'Open');
+ assert.equal(o.defaultPath, undefined);
+ assert.deepEqual(o.properties, ['openDirectory', 'createDirectory']);
+});
+
+test("Studio's words and starting folder are used", () => {
+ const o = folderDialogOptions({ title: 'Export to', button: 'Choose', at: '/Users/me/Movies' });
+ assert.equal(o.title, 'Export to');
+ assert.equal(o.message, 'Export to');
+ assert.equal(o.buttonLabel, 'Choose');
+ assert.equal(o.defaultPath, '/Users/me/Movies');
+});
+
+test('a starting folder that is not a full path, and text that is not text, are left out', () => {
+ const o = folderDialogOptions({ title: 42, button: ' ', at: 'Movies' });
+ assert.equal(o.title, 'Open Project');
+ assert.equal(o.buttonLabel, 'Open');
+ assert.equal(o.defaultPath, undefined);
+});
diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs
index db92417..cb4b4b8 100644
--- a/apps/desktop/src/main.mjs
+++ b/apps/desktop/src/main.mjs
@@ -13,6 +13,7 @@ import { basename, join } from 'node:path';
import { Readable } from 'node:stream';
import { fileURLToPath } from 'node:url';
import { FLAVOR, IDENTITY, PRODUCT_NAME } from './flavor.mjs';
+import { folderDialogOptions } from './folder-dialog.mjs';
import { childEnvironment, loginShellEnvironment } from './environment.mjs';
import { startWindowStudio } from './studio.mjs';
import { CHAT_MIN, STUDIO_MIN, WINDOW_MIN, placeOnDisplays, readWindowState, writeWindowState } from './window-state.mjs';
@@ -125,19 +126,18 @@ async function studioApi(path, method = 'GET', body = undefined) {
return res.json();
}
-/** A folder to open as a project, picked by the person (null: cancelled). Any folder: one not yet a project becomes one. */
-async function pickProjectFolder() {
- const { canceled, filePaths } = await dialog.showOpenDialog(win, {
- title: 'Open Project',
- buttonLabel: 'Open',
- properties: ['openDirectory', 'createDirectory'],
- });
+/**
+ * A folder picked by the person (null: cancelled): with no options, one to open as a project (any folder: one not yet
+ * a project becomes one); with Studio's own words and starting folder, any other (see folder-dialog.mjs).
+ */
+async function pickFolder(options) {
+ const { canceled, filePaths } = await dialog.showOpenDialog(win, folderDialogOptions(options));
return canceled || !filePaths[0] ? null : filePaths[0];
}
/** File › Open Project…: the folder picked, shown in the window (Studio switches its pages to it). */
async function openProjectFolder() {
- const folder = await pickProjectFolder();
+ const folder = await pickFolder();
if (!folder || !studio) return;
try {
await studioApi('/api/open', 'POST', { path: folder, fallback: 0 });
@@ -205,6 +205,9 @@ async function start() {
extra: {
OPENFILM_HOME: IDENTITY.studioHome ?? process.env.OPENFILM_HOME ?? join(app.getPath('home'), '.openfilm'),
...((IDENTITY.library ?? process.env.OPENFILM_LIBRARY) ? { OPENFILM_LIBRARY: IDENTITY.library ?? process.env.OPENFILM_LIBRARY } : {}),
+ /* the app names Studio's home, which would put exports inside it (Studio's rule for a home kept apart): the
+ Desktop, where `openfilm` puts them, unless this is a flavour with a home of its own */
+ ...(IDENTITY.studioHome || process.env.OPENFILM_EXPORTS ? {} : { OPENFILM_EXPORTS: app.getPath('desktop') }),
},
});
@@ -341,7 +344,7 @@ async function start() {
} catch (error) { return { ok: false, error: error.message }; }
});
ipcMain.handle('desktop:reveal', (event, path) => { if (fromPage(event) && typeof path === 'string' && path) shell.showItemInFolder(path); });
- ipcMain.handle('desktop:pick-folder', (event) => (fromPage(event) ? pickProjectFolder() : null));
+ ipcMain.handle('desktop:pick-folder', (event, options) => (fromPage(event) ? pickFolder(options) : null));
/* a picture of part of the window (the viewer, for a reference in the chat): what the person sees, as JPEG */
ipcMain.handle('desktop:capture', async (event, rect) => {
if (!fromPage(event) || !rect || typeof rect !== 'object') return null;
diff --git a/apps/desktop/src/preload.cjs b/apps/desktop/src/preload.cjs
index c45de2b..a180ed4 100644
--- a/apps/desktop/src/preload.cjs
+++ b/apps/desktop/src/preload.cjs
@@ -21,8 +21,8 @@ contextBridge.exposeInMainWorld('openfilmNative', {
hello: () => ipcRenderer.invoke('desktop:hello'),
pathForFile: (file) => { try { return webUtils.getPathForFile(file); } catch { return ''; } },
revealPath: (path) => ipcRenderer.invoke('desktop:reveal', String(path)),
- /* a folder the person picks (Studio's "Open…" on its Projects list): its path, or null */
- pickFolder: () => ipcRenderer.invoke('desktop:pick-folder'),
+ /* a folder the person picks (Studio's "Open…" on its Projects list, the export's "Save to"): its path, or null */
+ pickFolder: (options) => ipcRenderer.invoke('desktop:pick-folder', options ?? null),
/* part of the window as a JPEG (base64), for a reference's picture: null when it could not be taken */
capture: (rect) => ipcRenderer.invoke('desktop:capture', rect),
diff --git a/packages/openfilm/MANUAL.md b/packages/openfilm/MANUAL.md
index 090106d..6569e5a 100644
--- a/packages/openfilm/MANUAL.md
+++ b/packages/openfilm/MANUAL.md
@@ -43,10 +43,11 @@ A folder:
- `at`: where it starts in the film, in seconds; without it, 0.
- `left`, `top`, `width`, `height` in its `style` (px) and `rotate` (degrees, clockwise): where it sits. Without them, a video or picture is the stage, and a page is its own size, centered. With only `width` or `height`, the other keeps its proportions.
- Its look is CSS, in `class` or `style`: a video or picture fits whole in its box unless you say otherwise (`object-fit: cover` crops it to the box). The film's CSS holds still; what moves is a page.
- - `speed` (video and sound): 0.25 to 4. The clip lasts `(out − in) / speed` seconds.
+ - `speed` (video and sound): 0.25 to 4. The clip lasts `(out − in) / speed` seconds. To make it faster or slower, change `speed` only: never make the file again at another speed, nor move its `.vtt`'s times. Its subtitles follow `speed` on their own.
- `volume` (video and sound): 1 is the file's own level; `muted` silences it.
- `id`: a name, unique in the film; without it, the file's name.
- `overrides`: the person's changes made in Studio. Keep them as they are.
+ - `size` (page): the px a page without its own `width` and `height` is laid out at; without it, the stage's. Studio sets it when the frame changes shape. Keep it as it is; remove it only when you lay the page out again for the new frame.
- Cut a long recording by trimming it: every clip of it is the same file with its own `#t=`. Never cut, crop or re-encode media into new files; CSS crops.
## A page
diff --git a/packages/openfilm/SPEC.md b/packages/openfilm/SPEC.md
index c33fc6a..50a68c7 100644
--- a/packages/openfilm/SPEC.md
+++ b/packages/openfilm/SPEC.md
@@ -58,6 +58,9 @@ where, and CSS that says how each looks. A page draws a shot.
- `speed` on videos and sounds: the playback rate, 0.25 to 4, sound keeping its pitch. The clip lasts
`(out − in) / speed` on the film.
- `volume` on videos and sounds: linear gain, 1 the file's own level; `muted` is 0.
+ - `size` on pages: `size="1920x1080"`, the CSS pixels a page without its own `width` and `height` (§2) is laid
+ out at; without it, the stage's. An editor writes it when the stage changes shape, so such a page is scaled into
+ its box like a video rather than laid out again in the new shape.
- Where a picture sits is its own style's `left`, `top`, `width` and `height` in stage pixels, and `rotate` in
degrees, clockwise about its center. Nothing else places a clip: the host does, on the element, so no other CSS
moves it (`position`, `transform`, `margin` and the like in a clip's style are an error). `width` and `height`
@@ -136,7 +139,7 @@ window.film = {
| `frame(t)` | function | Draw the complete picture for time `t ≥ 0` (below `duration` when there is one). If it returns a Promise, the picture is complete when it resolves. |
| `duration` | number | Optional. The page's own length in seconds. Without it a page has no end, like a still: its clip's media fragment (`title.html#t=0,4`) says how long it plays, and a range is given to check or render it alone. |
| `ready` | Promise \| () => Promise | Optional. Resolves when fonts, images, models and data are loaded. The host calls `frame` only after it settles. For web fonts, load each face used (`document.fonts.load('700 64px Fraunces')`), not only `document.fonts.ready`. |
-| `width`, `height` | number | Optional. The page's size in CSS pixels, for a page that is part of the picture (a chart in a corner). Without them the page is the size of the stage, or 1920 × 1080 opened on its own. The host sizes the viewport to it; higher resolutions use device pixel ratio. |
+| `width`, `height` | number | Optional. The page's size in CSS pixels, for a page that is part of the picture (a chart in a corner). Without them the page is its clip's `size` (§1), else the size of the stage, or 1920 × 1080 opened on its own. The host sizes the viewport to it; higher resolutions use device pixel ratio. |
The frame rate is not the page's: a film is timed in seconds, and the rate is chosen when it is rendered.
diff --git a/packages/openfilm/scripts/dev.mjs b/packages/openfilm/scripts/dev.mjs
index 1a8bcd0..f879b1b 100644
--- a/packages/openfilm/scripts/dev.mjs
+++ b/packages/openfilm/scripts/dev.mjs
@@ -11,7 +11,7 @@
* so an agent opened in that folder uses it without being told.
*/
import { spawn } from 'node:child_process';
-import { chmodSync, existsSync, mkdirSync, readFileSync, watch, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, watch, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -28,6 +28,22 @@ const env = {
OPENFILM_STUDIO_WORKER: '1',
};
+/* one `pnpm dev` per checkout: two would share .dev/home and fight over the port, the loser taking another one and
+ writing it into run.json, so the agent's `openfilm` (and its browser) would point at a Studio that moves on every
+ restart and is refused in between */
+mkdirSync(DEV, { recursive: true });
+const LOCK = join(DEV, 'dev.pid');
+const holder = (() => { try { return Number(readFileSync(LOCK, 'utf8').trim()) || null; } catch { return null; } })();
+const alive = (/** @type {number} */ pid) => { try { process.kill(pid, 0); return true; } catch { return false; } };
+if (holder && holder !== process.pid && alive(holder)) {
+ console.error(`pnpm dev is already running for this checkout (pid ${holder}). Use that one, or stop it first: kill ${holder}`);
+ process.exit(1);
+}
+writeFileSync(LOCK, `${process.pid}\n`);
+process.on('exit', () => {
+ try { if (Number(readFileSync(LOCK, 'utf8').trim()) === process.pid) rmSync(LOCK); } catch { /* gone already */ }
+});
+
/* this checkout's `openfilm` on this Studio, for your agent: the same environment, and it names itself in the manual */
const BIN = join(DEV, 'bin');
mkdirSync(BIN, { recursive: true });
diff --git a/packages/openfilm/src/film-doc.mjs b/packages/openfilm/src/film-doc.mjs
index 5016ce8..025a512 100644
--- a/packages/openfilm/src/film-doc.mjs
+++ b/packages/openfilm/src/film-doc.mjs
@@ -90,7 +90,7 @@ const pair = (v, ok) => Array.isArray(v) && v.length === 2 && ok(v[0]) && ok(v[1
/** The fields each kind of clip takes, in the order they are written back. */
const CLIP_FIELDS = {
- page: ['src', 'id', 'at', 'time', 'box', 'class', 'style', 'overrides', 'attrs'],
+ page: ['src', 'id', 'at', 'time', 'box', 'size', 'class', 'style', 'overrides', 'attrs'],
video: ['src', 'id', 'at', 'time', 'box', 'volume', 'speed', 'class', 'style', 'overrides', 'attrs'],
still: ['src', 'id', 'at', 'time', 'box', 'class', 'style', 'overrides', 'attrs'],
sound: ['src', 'id', 'sound', 'at', 'time', 'volume', 'speed', 'overrides', 'attrs'],
@@ -101,6 +101,8 @@ const KEPT_ATTRIBUTE = /^(alt|title|lang|dir|data-[a-z0-9-]+|aria-[a-z]+)$/;
const KEPT_TRACK_ATTRIBUTE = /^(id|class|title|lang|dir|data-[a-z0-9-]+|aria-[a-z]+)$/;
const OVERRIDE_FIELDS = ['at', 'n', 't', 's', 'r', 'style', 'lock', 'text', 'fade'];
const BOX_FIELDS = ['x', 'y', 'w', 'h', 'r'];
+/** The largest side a page is laid out at (`size`): a stage's. */
+const PAGE_SIZE_MAX = 8192;
/** A copy of `row` with only `fields`, in that order: what is written back reads the same every time. */
const ordered = (row, fields) => Object.fromEntries(fields.filter((k) => row[k] !== undefined).map((k) => [k, row[k]]));
const TRACK_FIELDS = ['clips', 'locked', 'hidden', 'muted', 'attrs'];
@@ -196,6 +198,9 @@ function readClip(raw, where, problems) {
problems.push(`${at}speed has to be a number from ${SPEED_MIN} to ${SPEED_MAX}.`);
}
if (raw.box !== undefined && kind !== 'sound') checkBox(raw.box, at, problems);
+ if (raw.size !== undefined && !(isObject(raw.size) && Object.keys(raw.size).length === 2 && [raw.size.w, raw.size.h].every((v) => Number.isInteger(v) && v > 0 && v <= PAGE_SIZE_MAX))) {
+ problems.push(`${at}size is the px a page is laid out at, whole numbers up to ${PAGE_SIZE_MAX}: { "w": 1920, "h": 1080 }.`);
+ }
if (raw.overrides !== undefined) {
if (!Array.isArray(raw.overrides) || raw.overrides.length > 200) problems.push(`${at}overrides has to be a list (at most 200).`);
else {
@@ -220,6 +225,7 @@ function readClip(raw, where, problems) {
if (problems.length > before) return null;
const clip = ordered(raw, CLIP_FIELDS[kind]);
if (clip.box) clip.box = ordered(clip.box, BOX_FIELDS);
+ if (clip.size) clip.size = { w: clip.size.w, h: clip.size.h };
if (clip.overrides) clip.overrides = clip.overrides.map((o) => ordered(o, OVERRIDE_FIELDS));
return clip;
}
@@ -421,7 +427,7 @@ export function fittedFade(fade, length) {
/**
* Where a clip's picture lands on the stage. `kind` is the clip's (see clipKind); `own` the picture's own size: a
- * page's width × height (the stage's when it sets none), a video's or still's pixels. The box's w and h, its own size
+ * page's width × height (when it sets none, its clip's `size`, else the stage's), a video's or still's pixels. The box's w and h, its own size
* without them, and with only one of them the other follows the picture's proportions. A video or still is its box
* (the stage without one), the picture inside it as CSS says; a page is fitted whole inside its box and centered (its
* own size, centered, without one). Returns the rectangle drawn `{ x, y, w, h }` before it turns, and `r`: degrees clockwise
@@ -461,14 +467,16 @@ const TRACK_FLAGS = ['hidden', 'muted', 'locked'];
const TIMED = /^(animation|transition)(-|$)/;
const STILL_CSS = 'a film\'s CSS holds still — what moves is a web page of its own, a clip (its animation runs on the clip\'s time; in film.html it would run on the film\'s).';
/** A clip's attributes, each with what it says. */
-const CLIP_ATTRIBUTES = new Set(['id', 'src', 'at', 'speed', 'volume', 'muted', 'class', 'style', 'overrides']);
+const CLIP_ATTRIBUTES = new Set(['id', 'src', 'at', 'speed', 'volume', 'muted', 'size', 'class', 'style', 'overrides']);
/** What one kind of clip does not take, and why. */
const NO_SOUND = 'has no sound: a sound is a clip of its own, an <audio> (or a <video>\'s own sound)';
+const PAGE_ONLY = 'size is the px a web page is laid out at: a file has its own size.';
const NOT_OF_KIND = {
page: { volume: `a page ${NO_SOUND}.`, muted: `a page ${NO_SOUND}.`, speed: 'a page has no speed: its own frame(t) decides how fast it moves.' },
- still: { volume: `a still ${NO_SOUND}.`, muted: `a still ${NO_SOUND}.`, speed: 'a still has no speed: it holds for as long as its #t=0,length.' },
- sound: { style: 'a sound has no look: it is heard, not seen.' },
+ video: { size: PAGE_ONLY },
+ still: { volume: `a still ${NO_SOUND}.`, muted: `a still ${NO_SOUND}.`, speed: 'a still has no speed: it holds for as long as its #t=0,length.', size: PAGE_ONLY },
+ sound: { style: 'a sound has no look: it is heard, not seen.', size: PAGE_ONLY },
};
/**
@@ -668,6 +676,11 @@ function clipOfTag(tag, where, problems) {
else if (from > 0) raw.time = [from];
}
} else if (name === 'class') { if (value.trim()) raw.class = value.trim().split(/\s+/).join(' '); }
+ else if (name === 'size') {
+ const m = /^\s*(\d+)\s*[x×]\s*(\d+)\s*$/i.exec(value);
+ if (!m) problems.push(`${where}: size is the px the page is laid out at, width x height, like size="1920x1080" — "${value}" is not.`);
+ else raw.size = { w: Number(m[1]), h: Number(m[2]) };
+ }
else if (name === 'muted') muted = true;
else if (name === 'overrides') {
try { raw.overrides = JSON.parse(value); }
@@ -858,6 +871,7 @@ export function clipTag(clip) {
if (clip.speed != null && clip.speed !== 1) parts.push(`speed="${clip.speed}"`);
if (clip.volume === 0) parts.push('muted');
else if (clip.volume != null && clip.volume !== 1) parts.push(`volume="${clip.volume}"`);
+ if (clip.size) parts.push(`size="${clip.size.w}x${clip.size.h}"`);
if (clip.class) parts.push(`class="${escapeAttr(clip.class)}"`);
const b = clip.box;
const px = (v) => Number(v.toFixed(3));
diff --git a/packages/openfilm/src/film-doc.test.mjs b/packages/openfilm/src/film-doc.test.mjs
index a604fff..4d343ba 100644
--- a/packages/openfilm/src/film-doc.test.mjs
+++ b/packages/openfilm/src/film-doc.test.mjs
@@ -279,3 +279,17 @@ test('fadeGain: a straight ramp in and out, fitted to the clip when longer than
assert.equal(fadeGain(0.5, 2, [3, 3]), 0.5);
assert.equal(fadeGain(1, 2, [3, 3]), 1);
});
+
+test('a page\'s size is the px it is laid out at: read from size="WxH", written back as it was, a page\'s alone', () => {
+ const text = page([['<iframe id="title" src="title.html#t=0,3" size="1920x1080" style="left: 0px; top: 416px; width: 1080px; height: 608px"></iframe>']]);
+ const { doc, value, problems: found } = readFilmFile(text);
+ assert.deepEqual(found, []);
+ assert.deepEqual(doc.tracks[0].clips[0].size, { w: 1920, h: 1080 });
+ assert.equal(filmHtml(value, text), text);
+ value.tracks[0].clips[0].size = { w: 1280, h: 720 };
+ assert.match(filmHtml(value, text), /<iframe id="title" src="title.html#t=0,3" size="1280x720" style=/);
+ assert.match(said(page([['<iframe src="t.html#t=0,3" size="wide"></iframe>']])), /size="1920x1080"/);
+ assert.match(said(page([['<video src="a.mp4" size="1920x1080"></video>']])), /a file has its own size/);
+ assert.match(problems(film({ src: 't.html', id: 't', time: [0, 3], size: { w: 0, h: 1080 } })), /size is the px/);
+ assert.match(problems(film({ src: 't.html', id: 't', time: [0, 3], size: { w: 9000, h: 1080 } })), /up to 8192/);
+});
diff --git a/packages/openfilm/src/timeline.mjs b/packages/openfilm/src/timeline.mjs
index 827ba0b..aa9e7c8 100644
--- a/packages/openfilm/src/timeline.mjs
+++ b/packages/openfilm/src/timeline.mjs
@@ -441,6 +441,8 @@ function settle(c, row, track, ti) {
c.span = clipSpan(row, c.native, where);
c.end = c.at + c.span.length;
c.fade = fittedFade(clipFade(row), c.span.length);
+ /* a page that sets no size of its own is laid out at its clip's size, else the stage's */
+ if (c.kind === 'page') { const own = c.own ?? row.size ?? stage; c.nw = own.w; c.nh = own.h; }
dress(c, row);
/* the tweaks of a page's elements (the clip's own entry, its fades, is not one) */
const tweaks = row.overrides?.filter((o) => o.at !== undefined);
@@ -508,8 +510,8 @@ async function load(row, track, ti, el) {
}
const win = c.win = el.contentWindow;
c.child = win.film;
- const sized = c.child.width > 0 && c.child.height > 0;
- c.nw = sized ? c.child.width : stage.w; c.nh = sized ? c.child.height : stage.h;
+ /* its own size, when it says one (else its clip's size, or the stage's: see settle) */
+ if (c.child.width > 0 && c.child.height > 0) c.own = { w: c.child.width, h: c.child.height };
await ready(c.child);
/* a page without a duration has no end: its clip's #t= is its length, as a still's */
const length = c.child.duration;
@@ -609,10 +611,12 @@ window.__filmProgress = () => progress;
/* for `look`: where each picture starts, to check the picture is there */
window.__filmCuts = () => clips.filter((c) => c.kind !== 'sound' && !c.hidden).map((c) => ({ id: c.id, src: c.src, at: c.at, end: c.end }));
/* for an editor: where every clip sits on the film, sounds included, in seconds, its source's own length and picture
- size (a page's width × height, a video's frame, a still's pixels; none for a sound), and how a picture looks */
+ size (a page's width × height, a video's frame, a still's pixels; none for a sound), whether it is a page that sets
+ no size of its own (`reflows`: laid out at its clip's size, else the stage's), and how a picture looks */
window.__filmSpans = () => clips.map((c) => ({
id: c.id, src: c.src, track: c.track, at: c.at, end: c.end, native: Number.isFinite(c.native) ? c.native : null,
...(c.kind !== 'sound' && c.nw > 0 && c.nh > 0 ? { w: c.nw, h: c.nh } : {}),
+ ...(c.kind === 'page' && !c.own ? { reflows: true } : {}),
...(c.el ? { look: lookOf(c) } : {}),
}));
/**
diff --git a/packages/openfilm/src/timeline.test.mjs b/packages/openfilm/src/timeline.test.mjs
index e47389f..aa34ebe 100644
--- a/packages/openfilm/src/timeline.test.mjs
+++ b/packages/openfilm/src/timeline.test.mjs
@@ -81,6 +81,27 @@ test('a page without a size is the stage\'s, laid out for it; one with a size is
}
});
+test('a page without a size of its own is laid out at its clip\'s size, scaled into its box as a video is', { timeout: 60_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-sized-'));
+ writeFileSync(join(dir, 'wide.html'), `<!doctype html><body style="margin:0"><script>window.film={duration:2,frame(){}}</script></body>`);
+ /* a 16:9 page on a 3:4 stage: laid out at 320 × 180 and scaled to the stage's width, not laid out again at 240 × 320 */
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 240, h: 320 }, tracks: [
+ { clips: [{ src: 'wide.html', id: 'wide', size: { w: 320, h: 180 }, box: { x: 0, y: 92, w: 240, h: 135 } }] },
+ ] }));
+ const s = await open(dir);
+ try {
+ await s.film.seek(1);
+ const seen = await s.film.page.evaluate(() => [...document.querySelectorAll('iframe')].map((el) => {
+ const r = el.getBoundingClientRect();
+ return [el.contentWindow.innerWidth, el.contentWindow.innerHeight, r.left, r.top, r.width, r.height];
+ }));
+ assert.deepEqual(seen, [[320, 180, 0, 92, 240, 135]]);
+ assert.deepEqual(await s.film.page.evaluate(() => window.__filmSpans().map((c) => [c.w, c.h, c.reflows])), [[320, 180, true]]);
+ } finally {
+ await s.close();
+ }
+});
+
test('a page without a size, opened on its own, is 1920 × 1080', { timeout: 60_000 }, async () => {
const dir = mkdtempSync(join(tmpdir(), 'of-alone-'));
writeFileSync(join(dir, 'index.html'), `<!doctype html><body style="margin:0"><script>window.film={duration:2,frame(){}}</script></body>`);
diff --git a/packages/openfilm/studio/server/captions.mjs b/packages/openfilm/studio/server/captions.mjs
index 597c6fc..3562bca 100644
--- a/packages/openfilm/studio/server/captions.mjs
+++ b/packages/openfilm/studio/server/captions.mjs
@@ -194,6 +194,20 @@ async function wantsTranscript(root, src) {
return (await probe(root, src).catch(() => null))?.audio === true;
}
+/** How far past its file's end a transcript's last line may run (rounding, a codec's padding) before it is not the file's. */
+const OUTLAST_MS = 1000;
+
+/**
+ * Whether a transcript runs on past the end of its file (`seconds`; unknown: it cannot tell, so no): then it was made
+ * from another version of the file.
+ * @param {readonly { endMs: number }[]} lines @param {number | undefined} seconds
+ */
+export function transcriptOutlasts(lines, seconds) {
+ if (!(typeof seconds === 'number' && seconds > 0)) return false;
+ const end = lines.reduce((m, line) => Math.max(m, line.endMs), 0);
+ return end > seconds * 1000 + OUTLAST_MS;
+}
+
/**
* The film's subtitles as film.html is now.
* cues every line, sorted by start (film ms), with `alt` translations, the `clip` id it comes from and the
@@ -228,13 +242,23 @@ export async function filmCaptions(root, options = {}) {
known.set(src, one);
return one;
};
+ /** @type {Map<string, Promise<number | undefined>>} */
+ const lengths = new Map();
+ const lengthOf = (/** @type {string} */ src) => {
+ if (!lengths.has(src)) lengths.set(src, duration(src));
+ return /** @type {Promise<number | undefined>} */ (lengths.get(src));
+ };
/** @type {FilmSubtitleCue[]} */
const cues = [];
const untranscribed = new Set();
for (const clip of heardClips(root, doc)) {
const said = await transcriptOf(clip.src);
if (!said) { if (await wantsTranscript(root, clip.src)) untranscribed.add(clip.src); continue; }
- const native = clip.time?.length === 2 ? undefined : await duration(clip.src) ?? (said.lines.at(-1)?.endMs ?? 0) / 1000;
+ /* a transcript that runs on past the end of its file is not this file's any more (it was made again faster, or
+ the transcript's times were moved): its lines would drift later and later and the last ones fall off. It is
+ still shown, and made again with the rest (the CC button) */
+ if (await transcriptOutlasts(said.lines, await lengthOf(clip.src))) untranscribed.add(clip.src);
+ const native = clip.time?.length === 2 ? undefined : await lengthOf(clip.src) ?? (said.lines.at(-1)?.endMs ?? 0) / 1000;
let span;
try { span = clipSpan(clip, native ?? NaN); } catch { continue; }
cues.push(...clipCues(said.lines, {
@@ -252,6 +276,13 @@ export async function filmCaptions(root, options = {}) {
};
}
+/** Whether `src`'s transcript outlasts the file as it is now (see transcriptOutlasts). @param {string} root @param {string} src */
+async function outlastsItsFile(root, src) {
+ const read = await readTranscript(root, src);
+ if (!read) return false;
+ return transcriptOutlasts(read.lines, await probe(root, src).then((p) => p.duration, () => undefined));
+}
+
/* ── the person's style ──────────────────────────────────────────────────── */
/**
@@ -407,7 +438,8 @@ export async function captionRoutes(req, res, root, rest, { translate = async ()
/** @type {{ transcribed: string[], failed: { src: string, error: string }[] }} */
const out = { transcribed: [], failed: [] };
for (const src of untranscribed) {
- if (await transcriptIsCurrent(root, src)) continue;
+ /* one made since the file changed is kept, unless it outlasts the file (filmCaptions): then it is not its own */
+ if (await transcriptIsCurrent(root, src) && !(await outlastsItsFile(root, src))) continue;
if (!transcribe) throw new HttpError(409, CONNECT_TRANSCRIBER, { code: 'no-transcriber' });
try {
await transcribe(root, src, controller.signal);
diff --git a/packages/openfilm/studio/server/captions.test.mjs b/packages/openfilm/studio/server/captions.test.mjs
index cb866e6..3463a8c 100644
--- a/packages/openfilm/studio/server/captions.test.mjs
+++ b/packages/openfilm/studio/server/captions.test.mjs
@@ -6,7 +6,7 @@ import { tmpdir } from 'node:os';
import { dirname, join, relative } from 'node:path';
import {
CaptionError, SUBTITLE_STYLE_FILE, captionRoutes, captionText, filmCaptions, readSubtitleStyle, spokenLines,
- translateFilmSubtitles, writeSubtitleStyle,
+ transcriptOutlasts, translateFilmSubtitles, writeSubtitleStyle,
} from './captions.mjs';
import { FILM_SUBTITLE_DEFAULT, filmSubtitleShown, filmSubtitleSrt, filmSubtitleVtt } from './film-subtitle.mjs';
import { HttpError, json } from './http.mjs';
@@ -361,3 +361,17 @@ test('a translation follows the original\'s subtitles; one that cannot be cut sp
close();
}
});
+
+/* the file was made again shorter (sped up in place) while its transcript stayed: the lines would drift later and the
+ last ones fall off its end; it is listed to be made again, and still shown until then */
+test('a transcript that runs past the end of its file is listed to be made again', async () => {
+ assert.equal(transcriptOutlasts([{ endMs: 2500 }], 3), false);
+ assert.equal(transcriptOutlasts([{ endMs: 2500 }], undefined), false);
+ assert.equal(transcriptOutlasts([{ endMs: 2500 }], 1.2), true);
+ const root = project([{ clips: [{ id: 'v', src: 'assets/vo.mp3' }] }], { 'assets/vo.mp3': 'x', 'assets/vo.vtt': VTT });
+ const kept = await filmCaptions(root, { duration: async () => 3 });
+ assert.deepEqual(kept.untranscribed, []);
+ const shorter = await filmCaptions(root, { duration: async () => 1.2 });
+ assert.deepEqual(shorter.untranscribed, ['assets/vo.mp3']);
+ assert.ok(shorter.cues.length > 0, 'still shown until it is made again');
+});
diff --git a/packages/openfilm/studio/server/exports.mjs b/packages/openfilm/studio/server/exports.mjs
index dbb7631..2eda321 100644
--- a/packages/openfilm/studio/server/exports.mjs
+++ b/packages/openfilm/studio/server/exports.mjs
@@ -5,17 +5,16 @@
* One at a time, in the order asked, each cancellable. A video export is `openfilm render` itself and the sound is the
* same mix, so what Studio exports is what the agent checked with `look` and `render`.
*
- * Files go to the exports folder (~/Movies/OpenFilm/Exports on macOS, ~/Videos/OpenFilm/Exports elsewhere,
- * <OPENFILM_HOME>/exports when that is set, or OPENFILM_EXPORTS), or a folder the person chose, named after the
- * project, never over an earlier one.
+ * Files go to the exports folder (the Desktop, <OPENFILM_HOME>/exports when that is set, or OPENFILM_EXPORTS), or a
+ * folder the person chose, named after the project, never over an earlier one.
*
* What an export asks (POST exports, one ask or `{ jobs: [ask…], folder? }`):
*
* { kind: 'video', codec?, frame?, fill?, shortEdge?, fps?, quality?, audio?, clip?, scale?, preset?, sidecar? }
* codec h264 (default) | hevc | vp9 | prores422hq | prores4444 | hevc_alpha | png (a zipped PNG sequence);
* vp9, prores4444, hevc_alpha and png keep transparency
- * frame native (default) | 16:9 | 9:16 | 1:1 | 4:5 | 4:3 | 21:9: a delivery frame around the film, which is
- * fitted with bars (fill: 'contain', default) or fills it and is cropped (fill: 'cover')
+ * frame native (default), or a ratio W:H from 1:4 to 4:1 (16:9, 9:16, 4:5, 2.39:1…): a delivery frame around
+ * the film, which is fitted with bars (fill: 'contain', default) or fills it and is cropped (fill: 'cover')
* shortEdge the picture's short side in pixels (default: the film's own size)
* clip only this clip of film.html (by id), from its start, at the stage's size × `scale` (default 1)
* preset a platform's name, for the file name
@@ -67,15 +66,15 @@ import { PROJECT_PARTS, TOOL_DIR } from './projects.mjs';
/**
* The exports folder: OPENFILM_EXPORTS, else `exports` in OPENFILM_HOME when that is set (a Studio kept apart, for work
- * on OpenFilm itself, leaves nothing in the person's own folder), else ~/Movies/OpenFilm/Exports (~/Videos/… off macOS).
+ * on OpenFilm itself, leaves nothing in the person's own folder), else the Desktop, where a file just made is found.
*/
export const exportsRoot = () => process.env.OPENFILM_EXPORTS
|| (process.env.OPENFILM_HOME ? join(process.env.OPENFILM_HOME, 'exports') : '')
- || join(homedir(), process.platform === 'darwin' ? 'Movies' : 'Videos', 'OpenFilm', 'Exports');
+ || join(homedir(), 'Desktop');
/**
* @typedef {'h264' | 'hevc' | 'vp9' | 'prores422hq' | 'prores4444' | 'hevc_alpha' | 'png'} VideoCodec
- * @typedef {'native' | '16:9' | '9:16' | '1:1' | '4:5' | '4:3' | '21:9'} FrameId
+ * @typedef {'native' | `${number}:${number}`} FrameId
* @typedef {'standard' | 'high' | 'master'} Quality
* @typedef {{ frame?: FrameId, fill?: 'contain' | 'cover', burnSubtitles?: boolean }} Framing
* @typedef {Framing & { kind: 'video', codec?: VideoCodec, shortEdge?: number, scale?: number,
@@ -142,8 +141,13 @@ export async function exportCapabilities() {
/* ── delivery frames (the same arithmetic as the editor's lib/film-frame.ts) ── */
-const FRAME_RATIO = /** @type {Record<string, number>} */ ({ '16:9': 16 / 9, '9:16': 9 / 16, '1:1': 1, '4:5': 4 / 5, '4:3': 4 / 3, '21:9': 21 / 9 });
-const FRAMES = ['native', ...Object.keys(FRAME_RATIO)];
+/** A frame written `W:H` ("16:9", "2.39:1"), from 1:4 to 4:1: its width ÷ height, or null. @param {unknown} frame */
+export function frameRatio(frame) {
+ const m = typeof frame === 'string' ? /^(\d{1,4}(?:\.\d{1,3})?):(\d{1,4}(?:\.\d{1,3})?)$/.exec(frame) : null;
+ if (!m) return null;
+ const ratio = Number(m[1]) / Number(m[2]);
+ return Number.isFinite(ratio) && ratio >= 1 / 4 && ratio <= 4 ? ratio : null;
+}
const MAX_DIM = 4096;
const even = (/** @type {number} */ n) => Math.max(2, Math.round(n / 2) * 2);
@@ -153,8 +157,8 @@ const even = (/** @type {number} */ n) => Math.max(2, Math.round(n / 2) * 2);
* @param {{ w: number, h: number }} stage @param {string} frame @param {'contain' | 'cover'} fill
*/
export function frameBox(stage, frame, fill) {
- if (frame === 'native' || !FRAME_RATIO[frame]) return { w: even(stage.w), h: even(stage.h), scale: 1 };
- const ratio = FRAME_RATIO[frame];
+ const ratio = frame === 'native' ? null : frameRatio(frame);
+ if (ratio == null) return { w: even(stage.w), h: even(stage.h), scale: 1 };
const box = stage.w / ratio >= stage.h ? { w: stage.w, h: stage.w / ratio } : { w: stage.h * ratio, h: stage.h };
const w = even(box.w), h = even(box.h);
return { w, h, scale: fill === 'cover' ? Math.max(w / stage.w, h / stage.h) : Math.min(w / stage.w, h / stage.h) };
@@ -246,7 +250,7 @@ function checked(/** @type {ExportAsk} */ ask) {
throw new ExportError('a range is [from, to] 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 ('frame' in ask && ask.frame !== undefined && !FRAMES.includes(ask.frame)) throw new ExportError(`frame: ${FRAMES.join(', ')}`);
+ 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)');
if ('fill' in ask && ask.fill !== undefined && ask.fill !== 'contain' && ask.fill !== 'cover') throw new ExportError('fill: contain or cover');
if ('shortEdge' in ask && !between(ask.shortEdge, 64, MAX_DIM)) throw new ExportError(`shortEdge: 64 to ${MAX_DIM} pixels`);
if ('burnSubtitles' in ask && ask.burnSubtitles !== undefined && typeof ask.burnSubtitles !== 'boolean') throw new ExportError('burnSubtitles: true or false');
diff --git a/packages/openfilm/studio/server/exports.test.mjs b/packages/openfilm/studio/server/exports.test.mjs
index 1df33bc..b565177 100644
--- a/packages/openfilm/studio/server/exports.test.mjs
+++ b/packages/openfilm/studio/server/exports.test.mjs
@@ -121,7 +121,7 @@ test('the exports folder: OPENFILM_EXPORTS, else `exports` in OPENFILM_HOME, els
assert.equal(exportsRoot(), join(scratch, 'Mine'));
delete process.env.OPENFILM_EXPORTS;
delete process.env.OPENFILM_HOME;
- assert.equal(exportsRoot(), join(homedir(), process.platform === 'darwin' ? 'Movies' : 'Videos', 'OpenFilm', 'Exports'));
+ assert.equal(exportsRoot(), join(homedir(), 'Desktop'));
} finally {
for (const [key, value] of [['OPENFILM_EXPORTS', env.exports], ['OPENFILM_HOME', env.home]]) {
if (value === undefined) delete process.env[key]; else process.env[key] = value;
@@ -186,7 +186,7 @@ test('a cancelled export stops and leaves no file, and a bad ask is refused befo
const stopped = await ended(exports, job);
assert.equal(stopped.status, 'cancelled');
assert.ok(!existsSync(running.out), 'the half-written file is gone');
- for (const bad of [{ kind: 'pdf' }, { kind: 'video', range: [3, 1] }, { kind: 'video', codec: 'av1' }, { kind: 'video', frame: '2:1' },
+ 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: 'slides', format: 'key' }, { kind: 'slides', range: [0, 1] }, { kind: 'nle', fps: 500 }, { kind: 'nle', audio: 'mix' }, { kind: 'nle', range: [0, 1] }]) {
assert.throws(() => exports.start(project(), bad), ExportError, JSON.stringify(bad));
diff --git a/packages/openfilm/studio/server/files.mjs b/packages/openfilm/studio/server/files.mjs
index a962e47..6836951 100644
--- a/packages/openfilm/studio/server/files.mjs
+++ b/packages/openfilm/studio/server/files.mjs
@@ -9,7 +9,7 @@
import { execFile } from 'node:child_process';
import { createHash } from 'node:crypto';
import { createReadStream, createWriteStream, existsSync, lstatSync, realpathSync, statSync } from 'node:fs';
-import { copyFile, mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
+import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { basename, dirname, extname, isAbsolute, join, normalize, relative, sep } from 'node:path';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
@@ -17,6 +17,7 @@ import { FILM_FILE, clipKind } from '../../src/film-doc.mjs';
import { readProjectFilm, writeProjectFilm } from './film.mjs';
import { TOOL_DIR } from './projects.mjs';
import { moveToTrash } from './trash.mjs';
+import { linkKind, rewriteLinks } from './page-links.mjs';
import { ffmpeg } from '../../src/shared.mjs';
export const ASSETS = 'assets';
@@ -242,9 +243,76 @@ export async function makeFolder(/** @type {string} */ root, /** @type {string}
return rel;
}
+/* ── links between the project's own files, kept when one moves (page-links.mjs) ── */
+
+/** The project's pages, stylesheets and scripts (its own: no dot folder, no node_modules), as paths from the root. */
+async function linkedFiles(/** @type {string} */ root) {
+ /** @type {string[]} */
+ const out = [];
+ const walk = async (/** @type {string} */ dir) => {
+ for (const entry of await readdir(join(root, dir), { withFileTypes: true }).catch(() => [])) {
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
+ const rel = dir ? `${dir}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) { if (out.length < 5000) await walk(rel); } else if (entry.isFile() && linkKind(entry.name)) out.push(rel);
+ }
+ };
+ await walk('');
+ return out;
+}
+
+/** Where a file that was at `path` is after `from` moved to `to` (a file, or a folder and what is in it). */
+const movedTo = (/** @type {string} */ from, /** @type {string} */ to) => (/** @type {string} */ path) => (
+ path === from ? to : path.startsWith(`${from}/`) ? to + path.slice(from.length) : path
+);
+
+/**
+ * What moving `from` to `to` cannot keep true: the paths its pages and scripts make while they run (page-links.mjs),
+ * by file. Nothing moves.
+ * @param {string} root @param {string} from @param {string} to
+ */
+export async function moveCheck(root, from, to) {
+ const src = posix(from);
+ const where = movedTo(src, posix(to));
+ /** @type {{ file: string, unseen: string[] }[]} */
+ const out = [];
+ for (const file of await linkedFiles(root)) {
+ if (file !== src && !file.startsWith(`${src}/`)) continue;
+ const kind = linkKind(file);
+ if (!kind) continue;
+ const text = await readFile(inside(root, file), 'utf8').catch(() => '');
+ const { unseen } = rewriteLinks(text, kind, posix(dirname(file)), posix(dirname(where(file))), where);
+ if (unseen.length) out.push({ file, unseen });
+ }
+ return out;
+}
+
+/**
+ * After `from` moved to `to`: every page, stylesheet and script of the project written again so its links reach the
+ * same files (those that moved, and what they link to). Returns how many files changed.
+ * @param {string} root @param {string} from @param {string} to
+ */
+async function relinkAfterMove(root, from, to) {
+ const where = movedTo(from, to);
+ const back = (/** @type {string} */ path) => (path === to ? from : path.startsWith(`${to}/`) ? from + path.slice(to.length) : path);
+ let changed = 0;
+ for (const file of await linkedFiles(root)) {
+ const kind = linkKind(file);
+ if (!kind) continue;
+ const was = back(file);
+ const abs = inside(root, file);
+ const text = await readFile(abs, 'utf8').catch(() => null);
+ if (text == null) continue;
+ const next = rewriteLinks(text, kind, posix(dirname(was)), posix(dirname(file)), where);
+ if (next.changed) { await writeFile(abs, next.text); changed++; }
+ }
+ return changed;
+}
+
/**
* Rename or move a file or a folder, never over another, and point film.html's clips at the new place in the same
- * step: a renamed picture stays on the timeline. The new name is cleaned (cleanName).
+ * step: a renamed picture stays on the timeline. Pages, stylesheets and scripts that link to what moved, or that moved
+ * themselves, are written again so their links still reach their files (relinkAfterMove). The new name is cleaned
+ * (cleanName).
* @param {string} root @param {string} from @param {string} asked
*/
export async function moveFile(root, from, asked) {
@@ -264,7 +332,8 @@ export async function moveFile(root, from, asked) {
await mkdir(dirname(dst), { recursive: true });
await rename(src, dst);
const moved = await repoint(root, posix(relative(root, src)), posix(relative(root, dst)));
- return { path: posix(relative(root, dst)), clips: moved };
+ const pages = await relinkAfterMove(root, posix(relative(root, src)), posix(relative(root, dst)));
+ return { path: posix(relative(root, dst)), clips: moved, pages };
}
/** Whether two paths are one file on disk: a name changed only in case, on a disk that ignores case, is not "taken". */
diff --git a/packages/openfilm/studio/server/files.test.mjs b/packages/openfilm/studio/server/files.test.mjs
index 14d0c9d..7ad6c29 100644
--- a/packages/openfilm/studio/server/files.test.mjs
+++ b/packages/openfilm/studio/server/files.test.mjs
@@ -4,7 +4,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkS
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
-import { FileError, cleanName, extractAudio, freezeFrame, importFile, inProject, inside, listFiles, makeFolder, moveFile, trashFile } from './files.mjs';
+import { FileError, cleanName, extractAudio, freezeFrame, importFile, inProject, inside, listFiles, makeFolder, moveCheck, moveFile, trashFile } from './files.mjs';
import { execFileSync } from 'node:child_process';
import { filmHtml, readFilmFile } from '../../src/film-doc.mjs';
@@ -116,7 +116,7 @@ test('moving a file or a folder points film.html at the new place; nothing is mo
writeFileSync(join(root, 'film.html'), filmHtml({ stage: { w: 10, h: 10 }, tracks: [{ clips: [
{ src: 'assets/a.png', id: 'a', time: [0, 2] }, { src: 'assets/sfx/hit.wav', id: 'hit' },
] }] }));
- assert.deepEqual(await moveFile(root, 'assets/a.png', 'assets/stills/logo.png'), { path: 'assets/stills/logo.png', clips: 1 });
+ assert.deepEqual(await moveFile(root, 'assets/a.png', 'assets/stills/logo.png'), { path: 'assets/stills/logo.png', clips: 1, pages: 0 });
assert.equal((await moveFile(root, 'assets/sfx', 'assets/sounds')).clips, 1);
const srcs = readFilmFile(readFileSync(join(root, 'film.html'), 'utf8')).value.tracks[0].clips.map((c) => c.src);
assert.deepEqual(srcs, ['assets/stills/logo.png', 'assets/sounds/hit.wav']);
@@ -124,6 +124,25 @@ test('moving a file or a folder points film.html at the new place; nothing is mo
await assert.rejects(moveFile(root, 'assets/sounds', 'assets/sounds/inner'), FileError);
});
+test('a page moved into a folder keeps its links; a page linking to a moved picture follows it', async () => {
+ put('assets/logo.png'); put('anim.js');
+ writeFileSync(join(root, 'title.html'), '<script src="anim.js"></script><img src="assets/logo.png"><script type="module">fetch(dir + n)</script>');
+ writeFileSync(join(root, 'end.html'), '<img src="assets/logo.png">');
+ writeFileSync(join(root, 'film.html'), filmHtml({ stage: { w: 10, h: 10 }, tracks: [{ clips: [{ src: 'title.html', id: 't', time: [0, 2] }] }] }));
+ /* asked first: what it cannot see is named, and nothing moves */
+ const [said] = await moveCheck(root, 'title.html', 'scenes/title.html');
+ assert.equal(said.file, 'title.html');
+ assert.ok(said.unseen.some((u) => u.startsWith('fetch(dir')));
+ assert.ok(existsSync(join(root, 'title.html')));
+ const out = await moveFile(root, 'title.html', 'scenes/title.html');
+ assert.deepEqual([out.path, out.clips, out.pages], ['scenes/title.html', 1, 1]);
+ assert.match(readFileSync(join(root, 'scenes', 'title.html'), 'utf8'), /src="\.\.\/anim\.js".*src="\.\.\/assets\/logo\.png"/);
+ /* the picture moves: the pages that show it follow (the moved one too) */
+ await moveFile(root, 'assets/logo.png', 'assets/brand/logo.png');
+ assert.match(readFileSync(join(root, 'end.html'), 'utf8'), /src="assets\/brand\/logo\.png"/);
+ assert.match(readFileSync(join(root, 'scenes', 'title.html'), 'utf8'), /src="\.\.\/assets\/brand\/logo\.png"/);
+});
+
test('a rename never changes what a file is: another ending of the same kind is fine, a name in another case too', async () => {
put('assets/red.png'); put('assets/tone.mp3'); put('assets/notes.txt'); put('assets/clips.mp3/x.png');
await assert.rejects(moveFile(root, 'assets/red.png', 'assets/red.mp3'), (e) => e.status === 400 && /red\.png can't be renamed red\.mp3/.test(e.message));
diff --git a/packages/openfilm/studio/server/folder-picker.mjs b/packages/openfilm/studio/server/folder-picker.mjs
new file mode 100644
index 0000000..64a7140
--- /dev/null
+++ b/packages/openfilm/studio/server/folder-picker.mjs
@@ -0,0 +1,79 @@
+// @ts-check
+/**
+ * The system's own folder dialog, opened by Studio for a page in a browser (which can never learn a folder's path):
+ * the export's "Save to". The desktop app opens its own instead (lib/host.ts `folders.pick`).
+ *
+ * macOS osascript, `choose folder`
+ * Windows PowerShell, the Windows Forms folder dialog
+ * Linux zenity, else kdialog
+ *
+ * The page's words and the folder it starts in reach the dialog as arguments or environment variables, never inside
+ * the script, so nothing typed can run as code.
+ */
+import { execFile } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { isAbsolute } from 'node:path';
+
+/**
+ * How to open the dialog here: the program, its arguments and the environment it adds; null when this system has none.
+ * @param {NodeJS.Platform} platform @param {{ title: string, at?: string | null }} ask @param {(name: string) => boolean} [has]
+ * @returns {{ cmd: string, args: string[], env?: Record<string, string> } | null}
+ */
+export function folderPickerCommand(platform, { title, at }, has = () => true) {
+ const start = at && isAbsolute(at) ? at : '';
+ if (platform === 'darwin') {
+ return {
+ cmd: 'osascript',
+ args: [
+ '-e', 'on run argv',
+ '-e', 'activate',
+ '-e', 'if (item 2 of argv) is "" then',
+ '-e', 'return POSIX path of (choose folder with prompt (item 1 of argv))',
+ '-e', 'end if',
+ '-e', 'return POSIX path of (choose folder with prompt (item 1 of argv) default location (POSIX file (item 2 of argv)))',
+ '-e', 'end run',
+ title, start,
+ ],
+ };
+ }
+ if (platform === 'win32') {
+ const script = [
+ 'Add-Type -AssemblyName System.Windows.Forms',
+ '$d = New-Object System.Windows.Forms.FolderBrowserDialog',
+ '$d.Description = $env:OPENFILM_PICK_TITLE',
+ '$d.UseDescriptionForTitle = $true',
+ 'if ($env:OPENFILM_PICK_AT) { $d.SelectedPath = $env:OPENFILM_PICK_AT }',
+ '$w = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true }',
+ 'if ($d.ShowDialog($w) -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($d.SelectedPath) }',
+ ].join('; ');
+ return { cmd: 'powershell.exe', args: ['-NoProfile', '-STA', '-Command', script], env: { OPENFILM_PICK_TITLE: title, OPENFILM_PICK_AT: start } };
+ }
+ if (has('zenity')) {
+ return { cmd: 'zenity', args: ['--file-selection', '--directory', `--title=${title}`, ...(start ? [`--filename=${start}/`] : [])] };
+ }
+ if (has('kdialog')) return { cmd: 'kdialog', args: ['--getexistingdirectory', start || '.', '--title', title] };
+ return null;
+}
+
+/** Whether a program is on the PATH (Linux: which dialog there is). @param {string} name */
+const onPath = (name) => (process.env.PATH ?? '').split(':').some((dir) => dir && existsSync(`${dir}/${name}`));
+
+/**
+ * Ask the person for a folder. Resolves its path, or null when they cancelled; rejects when this system has no dialog
+ * Studio can open (the page lets them type one then).
+ * @param {{ title: string, at?: string | null }} ask @returns {Promise<string | null>}
+ */
+export function pickFolder(ask) {
+ const command = folderPickerCommand(process.platform, ask, onPath);
+ if (!command) return Promise.reject(new Error('no folder dialog on this system'));
+ return new Promise((resolve, reject) => {
+ execFile(command.cmd, command.args, { env: { ...process.env, ...command.env }, windowsHide: false, timeout: 15 * 60_000 }, (error, stdout) => {
+ const path = String(stdout).trim().replace(/[\\/]+$/, '') || (String(stdout).trim() === '/' ? '/' : '');
+ if (path) { resolve(path); return; }
+ /* cancelled: osascript says error -128, zenity and kdialog exit 1, Windows prints nothing */
+ if (!error || /-128|User canceled/i.test(String(error.message)) || error.code === 1) { resolve(null); return; }
+ if (/** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT') { reject(new Error('no folder dialog on this system')); return; }
+ reject(error);
+ });
+ });
+}
diff --git a/packages/openfilm/studio/server/folder-picker.test.mjs b/packages/openfilm/studio/server/folder-picker.test.mjs
new file mode 100644
index 0000000..eb1c715
--- /dev/null
+++ b/packages/openfilm/studio/server/folder-picker.test.mjs
@@ -0,0 +1,28 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { folderPickerCommand } from './folder-picker.mjs';
+
+test('macOS: the words and the folder are arguments of the script, never inside it', () => {
+ const c = folderPickerCommand('darwin', { title: 'Save "here" end tell', at: '/Volumes/Films' });
+ assert.equal(c.cmd, 'osascript');
+ assert.deepEqual(c.args.slice(-2), ['Save "here" end tell', '/Volumes/Films']);
+ assert.ok(c.args.filter((a, i) => c.args[i - 1] === '-e').every((line) => !line.includes('here')));
+});
+
+test('a starting folder that is not a full path is left out', () => {
+ assert.equal(folderPickerCommand('darwin', { title: 'T', at: 'Desktop' }).args.at(-1), '');
+ assert.equal(folderPickerCommand('win32', { title: 'T', at: 'Desktop' }).env.OPENFILM_PICK_AT, '');
+});
+
+test('Windows: PowerShell reads the words from its environment', () => {
+ const c = folderPickerCommand('win32', { title: "it's mine", at: 'D:\\Films' });
+ assert.equal(c.cmd, 'powershell.exe');
+ assert.equal(c.env.OPENFILM_PICK_TITLE, "it's mine");
+ assert.ok(!c.args.join(' ').includes("it's mine"));
+});
+
+test('Linux: zenity, else kdialog, else none', () => {
+ assert.equal(folderPickerCommand('linux', { title: 'T', at: '/srv/films' }, (n) => n === 'zenity').cmd, 'zenity');
+ assert.equal(folderPickerCommand('linux', { title: 'T' }, (n) => n === 'kdialog').cmd, 'kdialog');
+ assert.equal(folderPickerCommand('linux', { title: 'T' }, () => false), null);
+});
diff --git a/packages/openfilm/studio/server/folders.test.mjs b/packages/openfilm/studio/server/folders.test.mjs
index 247e14b..a28c086 100644
--- a/packages/openfilm/studio/server/folders.test.mjs
+++ b/packages/openfilm/studio/server/folders.test.mjs
@@ -79,3 +79,18 @@ test('the film\'s length is listed once Studio has learnt it, and only while fil
writeFileSync(film, JSON.stringify({ stage: { w: 640, h: 360 }, tracks: [{ clips: [] }] }));
assert.equal((await api('projects')).body.projects.find((p) => p.id === project.id).duration, undefined);
});
+
+test('folders inside folders: made in their parent, and deleted with it, their projects too', async () => {
+ const { body: { folder: outer } } = await api('projects/folders', { method: 'POST', body: { name: 'Clients' } });
+ const { body: { folder: inner } } = await api('projects/folders', { method: 'POST', body: { name: 'Acme', parentId: outer.id } });
+ assert.equal(inner.parentId, outer.id);
+ assert.equal((await api('projects/folders', { method: 'POST', body: { name: 'Lost', parentId: 'nope' } })).status, 404);
+
+ const { body: { project } } = await api('projects', { method: 'POST', body: { name: 'Acme spot' } });
+ await api(`projects/${project.id}/folder`, { method: 'PUT', body: { folderId: inner.id } });
+
+ const deleted = await api(`projects/folders/${outer.id}`, { method: 'DELETE' });
+ assert.deepEqual(deleted.body.projects, [project.id]);
+ const left = (await api('projects/folders')).body.folders.map((f) => f.id);
+ assert.ok(!left.includes(outer.id) && !left.includes(inner.id));
+});
diff --git a/packages/openfilm/studio/server/ops.mjs b/packages/openfilm/studio/server/ops.mjs
index ab16294..1af6a1d 100644
--- a/packages/openfilm/studio/server/ops.mjs
+++ b/packages/openfilm/studio/server/ops.mjs
@@ -69,7 +69,7 @@ function targetTrack(/** @type {FilmValue} */ value, /** @type {number | undefin
const dropEmptyTracks = (/** @type {FilmValue} */ value) => { value.tracks = value.tracks.filter((track) => track.clips.length); };
/** Fields a person sets from Studio, by kind of clip (the rest of a clip is the agent's to write). */
-const SETTABLE = new Set(['at', 'time', 'box', 'volume', 'speed', 'overrides', 'src']);
+const SETTABLE = new Set(['at', 'time', 'box', 'size', 'volume', 'speed', 'overrides', 'src']);
/** @param {FilmValue} value @param {Op[]} ops */
export function applyOps(value, ops) {
diff --git a/packages/openfilm/studio/server/page-links.mjs b/packages/openfilm/studio/server/page-links.mjs
new file mode 100644
index 0000000..4ee5a41
--- /dev/null
+++ b/packages/openfilm/studio/server/page-links.mjs
@@ -0,0 +1,98 @@
+// @ts-check
+/**
+ * A web page's links to the files beside it, kept true when it moves. A page is code: `<script src="anim.js">`,
+ * `<img src="../assets/logo.png">`, `url(bg.png)` and `import './lib.js'` are read from where the page is, so a page
+ * moved to another folder would look for them in the wrong place. Moving one (files.mjs moveFile) writes each such
+ * link again so it still reaches the same file, wherever that file is now (a folder moved with its page takes its
+ * files along).
+ *
+ * What is rewritten: in a page, `src`, `href` and `poster` attributes, CSS `url()` (in `<style>` and `style=""`), and
+ * in its scripts `import … from '…'`, `import '…'`, `import('…')`, `new URL('…', import.meta.url)` and `fetch('…')`
+ * with a literal path; in a stylesheet, its `url()` and `@import`; in a module script, its imports. A path made while
+ * the page runs (`fetch(base + name)`, `` img.src = `${dir}/x.png` ``) cannot be seen: it is listed (`unseen`) so the
+ * person is told before the page moves.
+ */
+import { posix } from 'node:path';
+
+/** A link that leads elsewhere than a file beside the page: a scheme, the site's root, a fragment, a template. */
+const NOT_RELATIVE = /^(?:[a-z][a-z0-9+.-]*:|\/|#|\?|\$\{|\{\{)/i;
+
+/**
+ * The same link from `toDir`, to the file it reached from `fromDir` (`where` gives where that file is now). Null when
+ * it is not a link to a file beside the page, or nothing changes.
+ * @param {string} ref @param {string} fromDir @param {string} toDir @param {(path: string) => string} where
+ * @param {boolean} [module] an import: it must start with ./ or ../ (a bare name is a package's)
+ */
+function relink(ref, fromDir, toDir, where, module = false) {
+ const trimmed = ref.trim();
+ if (!trimmed || NOT_RELATIVE.test(trimmed) || trimmed.includes('${')) return null;
+ if (module && !/^\.\.?\//.test(trimmed)) return null;
+ const cut = trimmed.search(/[?#]/);
+ const path = cut < 0 ? trimmed : trimmed.slice(0, cut);
+ const tail = cut < 0 ? '' : trimmed.slice(cut);
+ if (!path) return null;
+ const target = posix.normalize(posix.join(fromDir, path));
+ if (target.startsWith('../')) return null;
+ let next = posix.relative(toDir, where(target)) || posix.basename(target);
+ if (path.endsWith('/') && !next.endsWith('/')) next += '/';
+ if (module && !next.startsWith('.')) next = `./${next}`;
+ const out = next + tail;
+ return out === trimmed ? null : out;
+}
+
+/** Paths made while the code runs: what can be named, so the person knows what was not rewritten. */
+const MADE_AT_RUN = [
+ /\b(?:fetch|import|new\s+URL|new\s+Audio|new\s+Worker)\s*\(\s*(?![\s'"])[^)]{0,60}/g,
+ /\b(?:fetch|import|new\s+URL|new\s+Audio|new\s+Worker)\s*\(\s*`[^`]*\$\{[^`]{0,60}`/g,
+ /\.(?:src|href)\s*=\s*(?![\s'"])[^;\n]{0,60}/g,
+ /\.(?:src|href)\s*=\s*`[^`]*\$\{[^`]{0,60}`/g,
+ /\b(?:src|href)\s*=\s*["'][^"']*\$\{[^"']{0,60}["']/g,
+];
+
+/** What in `text` makes a path while it runs, each once, shortened. @param {string} text */
+function unseenIn(text) {
+ const found = new Set();
+ for (const re of MADE_AT_RUN) for (const m of text.matchAll(re)) found.add(m[0].replace(/\s+/g, ' ').trim().slice(0, 80));
+ return [...found];
+}
+
+/**
+ * A file's links written again for its move. `kind`: what the file is (a page, a stylesheet, a module script).
+ * @param {string} text @param {'html' | 'css' | 'js'} kind @param {string} fromDir @param {string} toDir
+ * @param {(path: string) => string} [where] where a file that was at `path` is now (its own place by default)
+ * @returns {{ text: string, changed: number, unseen: string[] }}
+ */
+export function rewriteLinks(text, kind, fromDir, toDir, where = (p) => p) {
+ let changed = 0;
+ const swap = (/** @type {string} */ whole, /** @type {string} */ ref, /** @type {boolean} */ module = false) => {
+ const next = relink(ref, fromDir, toDir, where, module);
+ if (next == null) return whole;
+ changed++;
+ const at = whole.lastIndexOf(ref);
+ return whole.slice(0, at) + next + whole.slice(at + ref.length);
+ };
+ let out = text;
+ /* CSS, in a stylesheet or a page */
+ out = out.replace(/url\(\s*(["']?)([^"')\s]+)\1\s*\)/gi, (whole, _q, ref) => swap(whole, ref));
+ if (kind === 'css') out = out.replace(/@import\s+(["'])([^"']+)\1/gi, (whole, _q, ref) => swap(whole, ref));
+ if (kind === 'html') {
+ out = out.replace(/(\s(?:src|href|poster)\s*=\s*)(["'])([^"']*)\2/gi, (whole, _a, _q, ref) => swap(whole, ref));
+ out = out.replace(/\bfetch\(\s*(["'])([^"']+)\1/g, (whole, _q, ref) => swap(whole, ref));
+ }
+ if (kind === 'html' || kind === 'js') {
+ out = out.replace(/(\b(?:import|export)\b[^'";]*?\bfrom\s*)(["'])([^"']+)\2/g, (whole, _a, _q, ref) => swap(whole, ref, true));
+ out = out.replace(/\bimport\s*(["'])([^"']+)\1/g, (whole, _q, ref) => swap(whole, ref, true));
+ out = out.replace(/\bimport\(\s*(["'])([^"']+)\1\s*\)/g, (whole, _q, ref) => swap(whole, ref, true));
+ out = out.replace(/\bnew\s+URL\(\s*(["'])([^"']+)\1\s*,\s*import\.meta\.url/g, (whole, _q, ref) => swap(whole, ref));
+ }
+ return { text: out, changed, unseen: kind === 'css' ? [] : unseenIn(text) };
+}
+
+/** What a file is, for its links: a page, a stylesheet, a module script, or none. @param {string} name */
+export function linkKind(name) {
+ const ext = posix.extname(name).toLowerCase();
+ if (ext === '.html' || ext === '.htm') return 'html';
+ if (ext === '.css') return 'css';
+ if (ext === '.js' || ext === '.mjs') return 'js';
+ return null;
+}
diff --git a/packages/openfilm/studio/server/page-links.test.mjs b/packages/openfilm/studio/server/page-links.test.mjs
new file mode 100644
index 0000000..de824d0
--- /dev/null
+++ b/packages/openfilm/studio/server/page-links.test.mjs
@@ -0,0 +1,53 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { linkKind, rewriteLinks } from './page-links.mjs';
+
+const PAGE = `<!doctype html>
+<link rel="stylesheet" href="style.css">
+<style>body { background: url("../assets/bg.png") } .x { background: url(#grain) }</style>
+<img src="../assets/logo.png" alt=""><a href="https://example.com">x</a><img src="data:image/png;base64,AA">
+<div style="background-image: url('pic.jpg')"></div>
+<script type="module">
+import { tween } from './lib/tween.js';
+import three from 'three';
+const data = await fetch('data.json?v=2').then((r) => r.json());
+const more = await fetch(base + name);
+img.src = \`\${dir}/x.png\`;
+</script>`;
+
+test('a page moved one folder down: every link it can read still reaches its file', () => {
+ const { text, changed, unseen } = rewriteLinks(PAGE, 'html', 'scenes', 'scenes/intro');
+ assert.match(text, /href="\.\.\/style\.css"/);
+ assert.match(text, /url\("\.\.\/\.\.\/assets\/bg\.png"\)/);
+ assert.match(text, /src="\.\.\/\.\.\/assets\/logo\.png"/);
+ assert.match(text, /url\('\.\.\/pic\.jpg'\)/);
+ assert.match(text, /from '\.\.\/lib\/tween\.js'/);
+ assert.match(text, /fetch\('\.\.\/data\.json\?v=2'\)/);
+ /* left alone: other sites, data, fragments, packages */
+ assert.match(text, /href="https:\/\/example\.com"/);
+ assert.match(text, /url\(#grain\)/);
+ assert.match(text, /from 'three'/);
+ assert.match(text, /src="data:image\/png;base64,AA"/);
+ assert.equal(changed, 6);
+ /* what is made while it runs cannot be rewritten: it is named */
+ assert.ok(unseen.some((u) => u.startsWith('fetch(base')), unseen.join(' | '));
+ assert.ok(unseen.some((u) => u.includes('${dir}')), unseen.join(' | '));
+});
+
+test('moved back where it was, nothing changes; a file moved along is followed', () => {
+ assert.equal(rewriteLinks(PAGE, 'html', 'scenes', 'scenes').changed, 0);
+ /* the folder scenes/ moved to shots/: its own files went with it, assets/ stayed */
+ const where = (p) => (p.startsWith('scenes/') ? `shots/${p.slice('scenes/'.length)}` : p);
+ const { text } = rewriteLinks('<img src="logo.png"><img src="../assets/a.png">', 'html', 'scenes', 'shots', where);
+ assert.equal(text, '<img src="logo.png"><img src="../assets/a.png">');
+ const deeper = rewriteLinks('<img src="logo.png"><img src="../assets/a.png">', 'html', 'scenes', 'film/shots', (p) => (p.startsWith('scenes/') ? `film/shots/${p.slice(7)}` : p));
+ assert.equal(deeper.text, '<img src="logo.png"><img src="../../assets/a.png">');
+});
+
+test('stylesheets and module scripts are rewritten as well; an import stays relative', () => {
+ assert.equal(rewriteLinks('@import "base.css"; a { background: url(i.png) }', 'css', 'css', 'css/theme').text,
+ '@import "../base.css"; a { background: url(../i.png) }');
+ assert.equal(rewriteLinks("import a from './a.js';", 'js', 'lib', 'lib/x', (p) => (p === 'lib/a.js' ? 'lib/x/a.js' : p)).text, "import a from './a.js';");
+ assert.equal(linkKind('scene.HTML'), 'html');
+ assert.equal(linkKind('clip.mp4'), null);
+});
diff --git a/packages/openfilm/studio/server/pages.mjs b/packages/openfilm/studio/server/pages.mjs
index d26c108..4f682d0 100644
--- a/packages/openfilm/studio/server/pages.mjs
+++ b/packages/openfilm/studio/server/pages.mjs
@@ -15,7 +15,7 @@
*
* Pages get the host flag (the film's clock, see src/host.mjs) before any of their scripts, as `look` and `render`
* give it, so a film draws here exactly as it renders. Everything may be read by the editor's origin (its sound mixer
- * fetches the media), and pages may be framed only by it. A media file asked for with `?film-sound` is its sound,
+ * fetches the media), which frames the pages. A media file asked for with `?film-sound` is its sound,
* small (derived.mjs soundOf): what the mixer plays, never the whole of a video; 204 when it has none.
*/
import { execFile } from 'node:child_process';
@@ -101,10 +101,11 @@ function servable(root, plain) {
* @param {{ port: number, editorOrigin: () => string, secret: string, projects: () => Promise<{ id: string, path: string }[]> }} options
*/
export async function startPages({ port, editorOrigin, secret, projects }) {
- /* read by the editor (its mixer fetches the media), framed only by it */
+ /* read by the editor (its mixer fetches the media). Framed by it with no frame-ancestors rule: that rule is checked
+ against every frame up to the window, so Studio shown inside another app's frame (an agent's preview pane) would
+ lose its picture; a page is reached only through its project's token, which only the editor has */
const policy = () => ({
'access-control-allow-origin': editorOrigin(),
- 'content-security-policy': `frame-ancestors 'self' ${editorOrigin()}`,
'x-content-type-options': 'nosniff',
});
/* Studio's scripts, told the editor's origin (the only one they answer) */
diff --git a/packages/openfilm/studio/server/project-settings.mjs b/packages/openfilm/studio/server/project-settings.mjs
index 4fe3a2f..0073b6f 100644
--- a/packages/openfilm/studio/server/project-settings.mjs
+++ b/packages/openfilm/studio/server/project-settings.mjs
@@ -23,7 +23,7 @@ import { TOOL_DIR } from './projects.mjs';
export const PROJECT_SETTINGS_FILE = `${TOOL_DIR}/settings.json`;
/** The rates a project can be set to, as editors name them (23.976 is 24000/1001, and so on). */
-export const FRAME_RATES = /** @type {const} */ ([23.976, 24, 25, 29.97, 30, 50, 59.94, 60]);
+export const FRAME_RATES = /** @type {const} */ ([23.976, 24, 25, 29.97, 30, 48, 50, 59.94, 60, 120]);
/** @typedef {{ name: string, index: number, clips: string[] }} TrackName */
/** @typedef {{ height: number, index: number, clips: string[] }} TrackHeight */
diff --git a/packages/openfilm/studio/server/projects.mjs b/packages/openfilm/studio/server/projects.mjs
index 0f17c73..ef4ce2f 100644
--- a/packages/openfilm/studio/server/projects.mjs
+++ b/packages/openfilm/studio/server/projects.mjs
@@ -62,7 +62,8 @@ export const libraryRoot = () => process.env.OPENFILM_LIBRARY
/**
* @typedef {{ id: string, path: string, openedAt: number, folderId?: string }} Recent
- * @typedef {{ id: string, name: string, createdAt: number }} ProjectFolder a folder of the Projects list (not on disk)
+ * @typedef {{ id: string, name: string, createdAt: number, parentId?: string }} ProjectFolder a folder of the Projects
+ * list (not on disk); `parentId` the folder it is in (none: the top level)
* @typedef {{ recent: Recent[], folders: ProjectFolder[] }} StudioState
*/
@@ -216,10 +217,12 @@ export async function listFolders() {
return (await readState()).folders;
}
-/** A new folder in the list. */
-export async function createFolder(/** @type {unknown} */ name) {
+/** A new folder in the list: at the top level, or in the folder `parentId`. */
+export async function createFolder(/** @type {unknown} */ name, /** @type {unknown} */ parentId = null) {
const state = await readState();
- const folder = { id: newId(), name: listFolderName(name), createdAt: Date.now() };
+ const parent = typeof parentId === 'string' && parentId ? parentId : null;
+ if (parent && !state.folders.some((f) => f.id === parent)) throw new ProjectError('no such folder', 404);
+ const folder = { id: newId(), name: listFolderName(name), createdAt: Date.now(), ...(parent ? { parentId: parent } : {}) };
state.folders.push(folder);
await writeState(state);
return folder;
@@ -235,15 +238,26 @@ export async function renameFolder(/** @type {string} */ id, /** @type {unknown}
return folder;
}
+/** A folder and every folder inside it, at any depth: their ids. @param {ProjectFolder[]} folders @param {string} id */
+export function folderTree(folders, id) {
+ const ids = new Set([id]);
+ for (let grew = true; grew;) {
+ grew = false;
+ for (const f of folders) if (f.parentId && ids.has(f.parentId) && !ids.has(f.id)) { ids.add(f.id); grew = true; }
+ }
+ return ids;
+}
+
/**
- * Take a folder off the list; its projects go back to the top level. Returns the ids of the projects that were in it
- * (deleting a folder deletes them too: the caller deletes each, see deleteProject).
+ * Take a folder off the list, with the folders inside it; their projects go back to the top level. Returns the ids of
+ * the projects that were in them (deleting a folder deletes them too: the caller deletes each, see deleteProject).
*/
export async function deleteFolder(/** @type {string} */ id) {
const state = await readState();
if (!state.folders.some((f) => f.id === id)) throw new ProjectError('no such folder', 404);
- state.folders = state.folders.filter((f) => f.id !== id);
- const inside = state.recent.filter((r) => r.folderId === id);
+ const gone = folderTree(state.folders, id);
+ state.folders = state.folders.filter((f) => !gone.has(f.id));
+ const inside = state.recent.filter((r) => r.folderId && gone.has(r.folderId));
for (const r of inside) delete r.folderId;
await writeState(state);
return inside.map((r) => r.id);
diff --git a/packages/openfilm/studio/server/providers/index.mjs b/packages/openfilm/studio/server/providers/index.mjs
index 8a7d96a..1e5eb39 100644
--- a/packages/openfilm/studio/server/providers/index.mjs
+++ b/packages/openfilm/studio/server/providers/index.mjs
@@ -86,6 +86,27 @@ export async function chooseProvider(verb, { via, settings } = {}) {
return named(chosen, kind, saved, false);
}
+/**
+ * What each kind of media is made with, as Settings → Models shows it: the person's choice while its provider has a
+ * key, else none. A choice whose key went away (an environment's key not set where Studio runs now) is kept in the
+ * settings, and comes back with the key, but is not shown as if it could make anything.
+ * @param {ProviderSettings} settings
+ */
+export function shownChoices(settings) {
+ const live = (/** @type {string} */ verb) => {
+ const provider = OWN.find((p) => p.id === settings.use[verb]);
+ return provider && providerKey(provider, settings) ? provider : null;
+ };
+ return {
+ use: Object.fromEntries(USE_VERBS.map((v) => [v, live(v)?.id ?? null])),
+ /* the model each kind of media is made with, whoever makes it */
+ model: Object.fromEntries(USE_VERBS.map((v) => {
+ const provider = live(v);
+ return [v, (provider && modelFor(settings, provider, v)) ?? null];
+ })),
+ };
+}
+
/** What Settings → Providers and Models show. Never a key: where it comes from and its last four characters. */
async function state() {
const settings = await readSettings();
@@ -96,12 +117,7 @@ async function state() {
const inEnv = envKey(p);
return { id: p.id, name: p.name, verbs: p.verbs, models: p.models ?? {}, keysUrl: p.keysUrl, env: key?.env ?? inEnv?.env ?? p.env, envKey: Boolean(inEnv), source: key?.source ?? null, last4: key ? key.key.slice(-4) : null };
}),
- use: Object.fromEntries(USE_VERBS.map((v) => [v, settings.use[v] ?? null])),
- /* the model each kind of media is made with, whoever makes it */
- model: Object.fromEntries(USE_VERBS.map((v) => {
- const provider = OWN.find((p) => p.id === settings.use[v]);
- return [v, (provider && modelFor(settings, provider, v)) ?? null];
- })),
+ ...shownChoices(settings),
};
}
diff --git a/packages/openfilm/studio/server/providers/index.test.mjs b/packages/openfilm/studio/server/providers/index.test.mjs
index e66d514..db3922e 100644
--- a/packages/openfilm/studio/server/providers/index.test.mjs
+++ b/packages/openfilm/studio/server/providers/index.test.mjs
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { chooseProvider, listProviders } from './index.mjs';
+import { chooseProvider, listProviders, shownChoices } from './index.mjs';
before(() => {
/* this machine's own keys must not decide these */
@@ -55,3 +55,13 @@ test('a key in the environment counts as much as a kept one', async () => {
delete process.env.GOOGLE_API_KEY;
}
});
+
+test('Settings shows a choice only while its provider has a key; the choice itself is kept', () => {
+ const kept = settings({}, { image: 'openai', sfx: 'elevenlabs' });
+ const shown = shownChoices({ ...kept, off: [] });
+ assert.equal(shown.use.image, null);
+ assert.equal(shown.model.image, null);
+ assert.equal(shown.use.sfx, null);
+ assert.deepEqual(kept.use, { image: 'openai', sfx: 'elevenlabs' });
+ assert.equal(shownChoices({ ...settings({ openai: 'sk-0123456789' }, { image: 'openai' }), off: [] }).use.image, 'openai');
+});
diff --git a/packages/openfilm/studio/server/server.mjs b/packages/openfilm/studio/server/server.mjs
index 634f19a..37d76b9 100644
--- a/packages/openfilm/studio/server/server.mjs
+++ b/packages/openfilm/studio/server/server.mjs
@@ -19,7 +19,7 @@ import { mkdir, readFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { EditError, editProjectFilm, readProjectFilm } from './film.mjs';
-import { FileError, extractAudio, freezeFrame, importFile, inside, listFiles, makeFolder, moveFile, trashFile } from './files.mjs';
+import { FileError, extractAudio, freezeFrame, importFile, inside, listFiles, makeFolder, moveCheck, moveFile, trashFile } from './files.mjs';
import { ExportError, createExports, 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';
@@ -33,6 +33,7 @@ import {
import { FetchError, createFetches } from './fetch-repo.mjs';
import { BrowseError, browseFolder, browsePlaces } from './browse.mjs';
import { listExamples } from './examples.mjs';
+import { pickFolder } from './folder-picker.mjs';
import { npmOpenfilm, olderThanThis } from '../client.mjs';
import { writeAtomic } from './atomic.mjs';
import { createWatchers } from './watch.mjs';
@@ -52,6 +53,11 @@ import { createAsks, getRoute, subtitleTranscriber, subtitleTranslator } from '.
/* the session cookie's name carries the port: cookies are per host, not per port, so two Studios on 127.0.0.1 (an
installed one and a checkout, say) would otherwise sign each other's pages out */
const cookieName = (/** @type {number} */ port) => `openfilm_studio_${port}`;
+/* and its twin for a page shown inside another site's frame (an agent's preview pane): a SameSite=Strict cookie is
+ neither kept nor sent there, so Studio would say "open it from the address…" however it was opened. This one is
+ Partitioned (CHIPS): kept for that frame's top-level site only, so a page elsewhere never has it unless it framed the
+ address with the key itself; and a write still has to come from the editor's own origin (authorize) */
+const framedCookieName = (/** @type {number} */ port) => `${cookieName(port)}_framed`;
/** How long `/open` waits, after a restart, for the pages of the Studio before to come back (they retry every second). */
const PAGES_BACK_MS = 3000;
/** The project's website (package.json `homepage`). */
@@ -83,6 +89,9 @@ export function desktopInstaller(os, arch, base = DESKTOP_FILES) {
*/
export async function startStudio({ port = 4747, key, openBrowser = systemBrowser, advertise = false, onQuit, stays = false, editorDir = EDITOR_DIR, working = () => [] } = {}) {
let COOKIE = cookieName(port);
+ let FRAMED = framedCookieName(port);
+ /** 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();
/** questions about spending for the person, in the pages showing a project (see get.mjs) */
@@ -115,7 +124,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
/** The caller holds the key; a browser write must also come from the editor's own origin. */
function authorize(/** @type {Req} */ req) {
if (sameKey(/** @type {string | undefined} */ (req.headers['x-studio-key']))) return;
- if (!sameKey(cookie(req, COOKIE))) throw new HttpError(401, 'open Studio from the address `openfilm open` prints');
+ if (!sameKey(cookieKey(req))) throw new HttpError(401, 'open Studio from the address `openfilm open` prints');
if (req.method !== 'GET' && req.method !== 'HEAD' && req.headers.origin !== origin) throw new HttpError(403, 'not from Studio');
}
@@ -151,7 +160,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
const to = url.searchParams.get('to') ?? '/';
res.writeHead(302, {
location: /^\/(?!\/)[^\s\\]*$/.test(to) ? to : '/',
- 'set-cookie': `${COOKIE}=${key}; Path=/; HttpOnly; SameSite=Strict`,
+ 'set-cookie': [`${COOKIE}=${key}; Path=/; HttpOnly; SameSite=Strict`, `${FRAMED}=${key}; Path=/; HttpOnly; Secure; SameSite=None; Partitioned`],
});
return res.end();
}
@@ -227,6 +236,17 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
try { return await getRoute(req, res, parts.slice(1), asks); } finally { making -= req.method === 'POST' ? 1 : 0; }
}
+ /* the system's folder dialog, opened here for a page in a browser (folder-picker.mjs): { path } (null: cancelled);
+ 501 when this system has none Studio can open */
+ if (parts[0] === 'pick-folder' && parts.length === 1 && req.method === 'POST') {
+ const { title, at } = /** @type {{ title?: unknown, at?: unknown }} */ (await readJson(req).catch(() => ({})) ?? {});
+ try {
+ const path = await pickFolder({ title: typeof title === 'string' && title.trim() ? title.trim().slice(0, 120) : 'Choose a folder', at: typeof at === 'string' ? at : null });
+ return json(res, 200, { path });
+ } catch (e) {
+ throw new HttpError(501, /** @type {Error} */ (e).message);
+ }
+ }
/* the web editor's folder browser (browse.mjs): `path`'s folders, only under the home folder, and where to start */
if (parts[0] === 'browse' && parts.length === 1 && req.method === 'GET') {
const listing = await browseFolder(url.searchParams.get('path'));
@@ -252,12 +272,15 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
if (parts.length === 3 && req.method === 'GET') return json(res, 200, { job: fetches.get(parts[2]) });
if (parts.length === 3 && req.method === 'DELETE') { fetches.cancel(parts[2]); return json(res, 200, {}); }
}
- /* the Projects list's folders (projects.mjs): GET / POST { name } `projects/folders`, PATCH { name } / DELETE
- `projects/folders/:id` (DELETE answers the ids of the projects that were in it), PUT { folderId }
+ /* the Projects list's folders (projects.mjs): GET / POST { name, parentId? } `projects/folders`, PATCH { name } /
+ DELETE `projects/folders/:id` (with the folders inside it; answers the ids of the projects that were in them), PUT { folderId }
`projects/:id/folder` (null: no folder) */
if (parts[1] === 'folders' && parts.length <= 3) {
if (parts.length === 2 && req.method === 'GET') return json(res, 200, { folders: await listFolders() });
- if (parts.length === 2 && req.method === 'POST') return json(res, 200, { folder: await createFolder(/** @type {{ name?: string }} */ (await readJson(req)).name) });
+ if (parts.length === 2 && req.method === 'POST') {
+ const { name, parentId } = /** @type {{ name?: string, parentId?: string | null }} */ (await readJson(req));
+ return json(res, 200, { folder: await createFolder(name, parentId) });
+ }
if (parts.length === 3 && req.method === 'PATCH') return json(res, 200, { folder: await renameFolder(parts[2], /** @type {{ name?: string }} */ (await readJson(req)).name) });
if (parts.length === 3 && req.method === 'DELETE') return json(res, 200, { projects: await deleteFolder(parts[2]) });
}
@@ -444,7 +467,9 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
return json(res, 200, { path: landed, ...(unreadable ? { unreadable } : {}) });
}
if (req.method === 'PATCH') {
- const { from, to } = /** @type {{ from?: string, to?: string }} */ (await readJson(req));
+ const { from, to, check } = /** @type {{ from?: string, to?: string, check?: boolean }} */ (await readJson(req));
+ /* `check`: what the move could not keep true (paths a page makes while it runs), nothing moved */
+ if (check === true) return json(res, 200, { unseen: await moveCheck(project.path, String(from ?? ''), String(to ?? '')) });
return json(res, 200, await moveFile(project.path, String(from ?? ''), String(to ?? '')));
}
if (req.method === 'DELETE') {
@@ -573,7 +598,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
if (!ownHost(req, /** @type {import('node:net').AddressInfo} */ (editor.address()).port)) return refuse('403 Forbidden');
void (async () => {
const path = new URL(req.url ?? '/', origin).pathname;
- const keyed = sameKey(/** @type {string | undefined} */ (req.headers['x-studio-key'])) || (sameKey(cookie(req, COOKIE)) && req.headers.origin === origin);
+ const keyed = sameKey(/** @type {string | undefined} */ (req.headers['x-studio-key'])) || (sameKey(cookieKey(req)) && req.headers.origin === origin);
if (!keyed) return refuse('401 Unauthorized');
const parts = path.split('/').slice(1).map(decodeURIComponent);
/** @type {() => void} */
@@ -601,6 +626,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
const address = /** @type {import('node:net').AddressInfo} */ (editor.address());
origin = `http://127.0.0.1:${address.port}`;
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 pages = await startPages({ port: port ? address.port + 1 : 0, editorOrigin: () => origin, secret: key, projects: listProjects }).catch(async (e) => {
watchers.closeAll();
diff --git a/packages/openfilm/studio/server/server.test.mjs b/packages/openfilm/studio/server/server.test.mjs
index f5e345d..322fe57 100644
--- a/packages/openfilm/studio/server/server.test.mjs
+++ b/packages/openfilm/studio/server/server.test.mjs
@@ -48,10 +48,17 @@ test('the API needs the key; /open sets it as a cookie and goes where it was ask
const res = await api(`/open?key=${studio.key}&to=/projects/x`, { key: null });
assert.equal(res.status, 302);
assert.equal(res.headers.get('location'), '/projects/x');
- const cookie = res.headers.get('set-cookie').split(';')[0];
- assert.equal((await api('/api/projects', { key: null, headers: { cookie } })).status, 200);
+ const [cookie, framed] = res.headers.getSetCookie();
+ assert.match(cookie, /SameSite=Strict/);
+ /* its twin for a page inside another site's frame (an agent's preview): kept for that frame alone */
+ assert.match(framed, /SameSite=None/);
+ assert.match(framed, /Partitioned/);
+ assert.equal((await api('/api/projects', { key: null, headers: { cookie: cookie.split(';')[0] } })).status, 200);
+ assert.equal((await api('/api/projects', { key: null, headers: { cookie: framed.split(';')[0] } })).status, 200);
+ const wrongTwin = framed.split(';')[0].replace(/=.*/, '=nope');
+ assert.equal((await api('/api/projects', { key: null, headers: { cookie: wrongTwin } })).status, 401);
/* a write with the cookie from any other origin is refused (a page elsewhere cannot drive Studio) */
- const write = await api('/api/projects', { method: 'POST', key: null, body: { name: 'x' }, headers: { cookie, origin: 'http://evil.test' } });
+ const write = await api('/api/projects', { method: 'POST', key: null, body: { name: 'x' }, headers: { cookie: framed.split(';')[0], origin: 'http://evil.test' } });
assert.equal(write.status, 403);
});
@@ -184,7 +191,9 @@ test('the film origin serves a project\'s files, with ranges, never .film/, and
const html = await page.text();
assert.ok(html.indexOf('window.filmHost') < html.indexOf('window.mine'), 'the clock comes before the page\'s own script');
assert.equal(page.headers.get('access-control-allow-origin'), studio.origin);
- assert.match(page.headers.get('content-security-policy'), /frame-ancestors/);
+ /* no frame-ancestors: it is checked against every frame up to the window, and Studio inside an agent's preview pane
+ would lose its picture */
+ assert.equal(page.headers.get('content-security-policy'), null);
const tail = await fetch(`${folder}tone.wav`, { headers: { range: 'bytes=-3' } });
assert.equal(tail.status, 206);
diff --git a/packages/openfilm/studio/ui/src/App.tsx b/packages/openfilm/studio/ui/src/App.tsx
index d66f724..910e6d5 100644
--- a/packages/openfilm/studio/ui/src/App.tsx
+++ b/packages/openfilm/studio/ui/src/App.tsx
@@ -54,6 +54,37 @@ export function App() {
return <>{page}<ConnectionNotice /></>;
}
+/**
+ * Studio answers, but not this browser: it was opened at Studio's address without the key (pasted, typed, an agent's
+ * browser given the bare address). Nothing to wait for: the page is covered and says which address lets it in.
+ */
+function LockedNotice() {
+ const t = useT();
+ const [copied, setCopied] = useState(false);
+ const COMMAND = 'openfilm open';
+ return (
+ <div role="alert" className="fixed inset-0 z-[10050] flex items-center justify-center bg-[var(--dock-shell)] p-6">
+ <div className="w-full max-w-[460px] rounded-2xl border border-[var(--border)] bg-[var(--surface)] p-6 shadow-[var(--shadow-lg)]">
+ <p className="text-[16px] font-semibold text-[var(--text)]">{t('connection.lockedTitle')}</p>
+ <p className="mt-2 text-[13px] leading-relaxed text-[var(--text-muted)]">{t('connection.lockedBody')}</p>
+ <p className="mt-3 rounded-lg bg-[var(--surface-2)] px-3 py-2 font-mono text-[12px] text-[var(--text-dim)]">{`${location.origin}/open?key=…`}</p>
+ {studioHost ? null : (
+ <div className="mt-4 flex items-center gap-2 text-[12.5px] text-[var(--text-muted)]">
+ <span>{t('connection.lockedHow')}</span>
+ <button
+ type="button"
+ onClick={() => { void navigator.clipboard?.writeText(COMMAND).then(() => setCopied(true), () => {}); }}
+ className="rounded-md bg-[var(--surface-2)] px-2 py-0.5 font-mono text-[12px] text-[var(--text)] ring-1 ring-inset ring-[var(--border)] hover:bg-[var(--bg-hover)]"
+ >
+ {copied ? t('connection.copied') : COMMAND}
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
/**
* Studio stopped (an update, a crash, the computer slept): a bar across the top while it is away, so nothing seems to
* hang for no reason. Reconnecting is tried all along; once it has been away a while the page is covered (an export or
@@ -65,6 +96,7 @@ function ConnectionNotice() {
const [copied, setCopied] = useState(false);
useEffect(() => { if (state === 'up') setCopied(false); }, [state]);
if (state === 'up') return null;
+ if (state === 'locked') return <LockedNotice />;
const gone = state === 'gone';
const COMMAND = 'openfilm open';
return (
diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.ts
index 0294b7b..0945d28 100644
--- a/packages/openfilm/studio/ui/src/api.ts
+++ b/packages/openfilm/studio/ui/src/api.ts
@@ -12,6 +12,8 @@ export interface StudioVersion { version: string; latest: string | null; newer:
export type Project = { id: string; path: string; name: string; openedAt: number; missing: boolean; working?: boolean };
export type Clip = { src: string; id: string; at?: number; time?: [number] | [number, number];
box?: { x: number; y: number; w?: number; h?: number; r?: number }; volume?: number; speed?: number; overrides?: unknown[];
+ /** a page that sets no size of its own: the px it is laid out at (the stage's without it) */
+ size?: { w: number; h: number };
/** a video's sound alone (an <audio> of its file) */
sound?: true;
/** its look: class names for the film's styles, and its own CSS */
@@ -62,6 +64,7 @@ async function call<T>(path: string, init: RequestInit & { json?: unknown } = {}
body: json === undefined ? rest.body : JSON.stringify(json),
});
const body = await res.json().catch(() => ({}));
+ if (res.status === 401) markLocked();
if (!res.ok) throw new ApiError(String(body.error ?? `Studio answered ${res.status}`), res.status, body);
return body as T;
} finally {
@@ -75,6 +78,9 @@ export const api = {
/** this Studio's version and the latest openfilm on npm; `check`: ask npm now */
version: (check = false) => call<StudioVersion>(`version${check ? '?check=1' : ''}`),
projects: () => call<{ projects: Project[] }>('projects').then((r) => r.projects),
+ /** the system's folder dialog, opened by Studio (a page in a browser cannot learn a path): the folder, or null when
+ cancelled; throws (501) where this system has none */
+ pickFolder: (title: string, at?: string) => call<{ path: string | null }>('pick-folder', { method: 'POST', json: { title, ...(at ? { at } : {}) } }).then((r) => r.path),
newProject: (name?: string) => call<{ project: Project }>('projects', { method: 'POST', json: { name } }).then((r) => r.project),
/** open a folder (its full path) as a project: made one when it is not yet */
openFolder: (path: string) => call<{ project: Project }>('projects', { method: 'POST', json: { path } }).then((r) => r.project),
@@ -158,6 +164,8 @@ export function listen(path: string, on: (event: FolderEvent) => void, { onBack,
if (stopped) return;
lost = true;
watcher?.down();
+ /* refused, not gone: Studio is there but this browser has no key (the stream says no reason, a request does) */
+ if (watch && tries === 0) void fetch('/api/version', { cache: 'no-store' }).then((r) => { if (r.status === 401) markLocked(); }, () => {});
/* soon at first, then every second: Studio restarting (`openfilm open` starts it afresh) is back within one
or two, and waits a few for the pages before it */
again = setTimeout(connect, Math.min(1000, 250 * 2 ** tries++));
@@ -171,18 +179,21 @@ export function listen(path: string, on: (event: FolderEvent) => void, { onBack,
let studioVersion: ReturnType<typeof watchStudioVersion> | null = null;
/**
- * Whether Studio answers, for the notice when it does not: 'up', 'lost' (stopped a moment ago, reconnecting) or
- * 'gone' (still not back, or this page's key is from another launch).
+ * Whether Studio answers, for the notice when it does not: 'up', 'lost' (stopped a moment ago, reconnecting), 'gone'
+ * (still not back), or 'locked': Studio answers but not this browser, which was never let in (its address was typed
+ * or pasted without the key `openfilm open` prints, or its key is another launch's). Waiting does not fix that one.
*/
-export type Connection = 'up' | 'lost' | 'gone';
+export type Connection = 'up' | 'lost' | 'gone' | 'locked';
let connection: Connection = 'up';
const connectionListeners = new Set<() => void>();
export const studioConnection = {
get: () => connection,
subscribe(fn: () => void) { connectionListeners.add(fn); return () => { connectionListeners.delete(fn); }; },
};
+/** Studio answered this page 401: it was never let in (see Connection). */
+export function markLocked() { setConnection('locked'); }
function setConnection(next: Connection) {
- if (next === connection) return;
+ if (next === connection || (connection === 'locked' && next !== 'up')) return;
connection = next;
for (const fn of [...connectionListeners]) fn();
}
diff --git a/packages/openfilm/studio/ui/src/components/Card.tsx b/packages/openfilm/studio/ui/src/components/Card.tsx
index c924f49..c179014 100644
--- a/packages/openfilm/studio/ui/src/components/Card.tsx
+++ b/packages/openfilm/studio/ui/src/components/Card.tsx
@@ -53,7 +53,7 @@ export function Card({
{icon ? <span className="mt-[2px] shrink-0 text-[var(--text-muted)]">{icon}</span> : null}
<div className="min-w-0 flex-1">
<h3 className="text-[13px] font-medium leading-snug text-[var(--text)]">{title}</h3>
- {body ? <div className="mt-1 text-[12.5px] leading-relaxed text-[var(--text-muted)]">{body}</div> : null}
+ {body ? <div className="mt-1 whitespace-pre-line break-words text-[12.5px] leading-relaxed text-[var(--text-muted)]">{body}</div> : null}
</div>
</div>
{children}
diff --git a/packages/openfilm/studio/ui/src/components/ContextMenu.tsx b/packages/openfilm/studio/ui/src/components/ContextMenu.tsx
index 281db51..4a3bb73 100644
--- a/packages/openfilm/studio/ui/src/components/ContextMenu.tsx
+++ b/packages/openfilm/studio/ui/src/components/ContextMenu.tsx
@@ -32,6 +32,8 @@ export interface ContextMenuItem {
disabled?: boolean;
/** Why it cannot be clicked. A grayed-out item must give a reason, otherwise users just keep clicking it. */
hint?: string;
+ /** A line under the label, in smaller type: what happens, or where to undo it (Hide row: where it comes back). */
+ note?: string;
/** Shortcut, drawn on the right. */
shortcut?: string;
/** Currently selected (the check mark in a sort list). `false` still reserves the space, to line up with checked items. */
@@ -346,7 +348,14 @@ export function ContextMenu({
{entry.icon}
</span>
) : null}
- <span className="min-w-0 flex-1 truncate">{entry.label}</span>
+ {entry.note ? (
+ <span className="flex min-w-0 max-w-[260px] flex-1 flex-col">
+ <span className="truncate">{entry.label}</span>
+ <span className="mt-0.5 whitespace-normal text-[11.5px] leading-snug text-[var(--text-faint)]">{entry.note}</span>
+ </span>
+ ) : (
+ <span className="min-w-0 flex-1 truncate">{entry.label}</span>
+ )}
{entry.shortcut ? (
<span className="shrink-0 text-[11px] text-[var(--text-faint)]">{entry.shortcut}</span>
) : null}
diff --git a/packages/openfilm/studio/ui/src/components/DesktopDialog.tsx b/packages/openfilm/studio/ui/src/components/DesktopDialog.tsx
index 899569f..8aad84d 100644
--- a/packages/openfilm/studio/ui/src/components/DesktopDialog.tsx
+++ b/packages/openfilm/studio/ui/src/components/DesktopDialog.tsx
@@ -1,23 +1,30 @@
/**
- * What the desktop app adds, opened from the top bar's Desktop button (never on its own): a picture of its window
- * (Studio with the person's agent beside the film), the agents it works with, everything it does, and the download
- * for this computer's system and chip (lib/desktop-build). "Download" has Studio open the installer in the person's
- * browser (the website when this build names no place for installers); Studio sends nothing else.
+ * What the desktop app adds, opened from the top bar's Desktop button (never on its own). Two halves: on the left a
+ * picture of its window (Studio with the person's agent beside the film) over the agents it works with; on the right
+ * what it does, in eight points, and the download for this computer's system and chip (lib/desktop-build), beside
+ * the version. "Download"
+ * has Studio open the installer in the person's browser (the website when this build names no place for
+ * installers); Studio sends nothing else.
*/
import React from 'react';
import { createPortal } from 'react-dom';
-import { FileDown, History, MessagesSquare, MousePointerClick, Rocket, Wand2, X } from 'lucide-react';
+import { ArrowLeftRight, Bot, FileDown, Gauge, History, MonitorPlay, PackageCheck, RefreshCw, X } from 'lucide-react';
import { useT } from '@/i18n';
import { desktopBuild, desktopSystem } from '@/lib/desktop-build';
+import { BrandLogo } from './BrandLogo';
import { ProviderMark } from './settings/ProviderMark';
+import { Tooltip } from './Tooltip';
+/* what the app does: the chat and the editor together, the agents, the engine, no setup, and staying current */
const FEATURES: { key: string; icon: React.ReactNode }[] = [
- { key: 'chat', icon: <MessagesSquare size={16} strokeWidth={1.75} /> },
- { key: 'point', icon: <MousePointerClick size={16} strokeWidth={1.75} /> },
- { key: 'drop', icon: <FileDown size={16} strokeWidth={1.75} /> },
- { key: 'setup', icon: <Wand2 size={16} strokeWidth={1.75} /> },
- { key: 'history', icon: <History size={16} strokeWidth={1.75} /> },
- { key: 'launch', icon: <Rocket size={16} strokeWidth={1.75} /> },
+ { key: 'sync', icon: <ArrowLeftRight size={15} strokeWidth={1.75} /> },
+ { key: 'live', icon: <MonitorPlay size={15} strokeWidth={1.75} /> },
+ { key: 'drop', icon: <FileDown size={15} strokeWidth={1.75} /> },
+ { key: 'agents', icon: <Bot size={15} strokeWidth={1.75} /> },
+ { key: 'speed', icon: <Gauge size={15} strokeWidth={1.75} /> },
+ { key: 'setup', icon: <PackageCheck size={15} strokeWidth={1.75} /> },
+ { key: 'updates', icon: <RefreshCw size={15} strokeWidth={1.75} /> },
+ { key: 'history', icon: <History size={15} strokeWidth={1.75} /> },
];
/** The agents it finds on the computer, by their marks (Codex's is OpenAI's, Gemini CLI's is Google's). */
@@ -34,6 +41,28 @@ const AGENTS: { id: string; name: string }[] = [
const SYSTEM_NAMES = { mac: 'macOS', win: 'Windows' } as const;
+/**
+ * The picture half is dark in either theme (a window on a stage): Studio's dark colors, set on it alone, so the drawn
+ * window and the agents' marks read the same in a light Studio.
+ */
+const DARK: React.CSSProperties = {
+ '--text': '#ededed',
+ '--text-muted': '#a3a3a3',
+ '--text-faint': '#6f6f6f',
+ '--surface': '#1d1f1f',
+ '--surface-2': '#272a2a',
+ '--border': 'rgba(255, 255, 255, 0.08)',
+ '--dock-shell': '#121414',
+ '--tl-playhead': '#ffffff',
+ '--tl-accent': '#45c2b4',
+ '--tl-wave': 'rgba(12, 168, 164, 0.9)',
+ background: [
+ 'radial-gradient(90% 70% at 0% 0%, color-mix(in srgb, #5ecb92 34%, transparent), transparent 70%)',
+ 'radial-gradient(80% 60% at 100% 100%, color-mix(in srgb, #7fd3e4 26%, transparent), transparent 70%)',
+ '#0d1110',
+ ].join(', '),
+} as React.CSSProperties;
+
const APPLE = 'M16.37 12.6c-.02-2.3 1.88-3.4 1.97-3.46-1.07-1.57-2.74-1.79-3.33-1.81-1.42-.14-2.77.84-3.49.84-.72 0-1.83-.82-3.01-.8-1.55.02-2.98.9-3.78 2.29-1.61 2.8-.41 6.94 1.16 9.2.77 1.11 1.68 2.36 2.88 2.31 1.16-.05 1.59-.75 2.99-.75 1.39 0 1.79.75 3.01.72 1.24-.02 2.03-1.13 2.79-2.25.88-1.29 1.24-2.54 1.26-2.6-.03-.01-2.42-.93-2.45-3.69ZM14.07 5.85c.64-.77 1.07-1.85.95-2.92-.92.04-2.03.61-2.69 1.38-.59.68-1.11 1.78-.97 2.83 1.02.08 2.07-.52 2.71-1.29Z';
const WINDOWS = 'M3 5.1 10.4 4v7.1H3V5.1Zm8.4-1.2L21 2.5v8.6h-9.6V3.9ZM3 12.9h7.4V20L3 18.9v-6Zm8.4 0H21v8.6l-9.6-1.4v-7.2Z';
@@ -45,6 +74,14 @@ export function DesktopDialog({ open, onClose }: { open: boolean; onClose: () =>
const close = React.useRef(onClose);
close.current = onClose;
const system = desktopSystem();
+ /* the version: Studio's, which the app shares (one version for all of OpenFilm) */
+ const [version, setVersion] = React.useState<string | null>(null);
+ React.useEffect(() => {
+ if (!open || version) return;
+ void fetch('/api/health', { cache: 'no-store' }).then((r) => r.json())
+ .then((h: { version?: unknown }) => { if (typeof h?.version === 'string') setVersion(h.version); })
+ .catch(() => { /* no version shown */ });
+ }, [open, version]);
React.useEffect(() => {
if (!open) return;
@@ -78,7 +115,7 @@ export function DesktopDialog({ open, onClose }: { open: boolean; onClose: () =>
return createPortal(
<div
- className="fixed inset-0 z-[10100] flex items-center justify-center bg-black/50 p-4 backdrop-blur-[3px]"
+ className="fixed inset-0 z-[10100] flex items-center justify-center bg-black/55 p-4 backdrop-blur-[3px]"
style={{ animation: 'openfilm-rise 0.18s ease-out both' }}
onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}
>
@@ -87,71 +124,76 @@ export function DesktopDialog({ open, onClose }: { open: boolean; onClose: () =>
role="dialog"
aria-modal="true"
aria-labelledby="desktop-title"
- className="relative flex max-h-[calc(100vh-32px)] w-full max-w-[780px] flex-col overflow-hidden rounded-[16px] border border-[var(--card-border)] bg-[var(--card-bg)] shadow-[0_24px_64px_-24px_rgba(0,0,0,0.55)]"
+ className="relative grid max-h-[calc(100vh-32px)] w-full max-w-[1040px] overflow-hidden rounded-[18px] border border-[var(--card-border)] bg-[var(--card-bg)] shadow-[0_32px_80px_-24px_rgba(0,0,0,0.6)] md:grid-cols-[minmax(0,0.72fr)_minmax(0,1.28fr)]"
>
<button
type="button"
onClick={onClose}
aria-label={t('desktop.close')}
- className="absolute right-3 top-3 z-10 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)]"
+ className="absolute right-3 top-3 z-10 flex h-8 w-8 items-center justify-center rounded-full text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
>
- <X size={15} />
+ <X size={16} />
</button>
- <div className="overflow-y-auto">
- <AppPicture />
+ {/* the picture: the window, then the agents it works with */}
+ <div className="flex min-w-0 flex-col gap-6 p-6 md:p-7" style={DARK}>
+ <div className="flex flex-1 items-center">
+ <AppPicture />
+ </div>
+ <div>
+ <div className="text-[11px] font-medium uppercase tracking-[0.1em] text-[var(--text-faint)]">{t('desktop.worksWith')}</div>
+ <div className="mt-2.5 flex flex-wrap items-center gap-1.5">
+ {AGENTS.map(({ id, name }) => (
+ <Tooltip key={id} label={name}>
+ <span aria-label={name} className="flex h-8 w-8 items-center justify-center rounded-[9px] border border-white/10 bg-white/[0.06] transition hover:border-white/25 hover:bg-white/[0.12]">
+ <ProviderMark id={id} size={15} />
+ </span>
+ </Tooltip>
+ ))}
+ </div>
+ <div className="mt-2.5 text-[12px] text-[var(--text-muted)]">{t('desktop.orOwnKey')}</div>
+ </div>
+ </div>
- <div className="px-7 pb-2 pt-5">
- <div className="text-[11.5px] font-medium uppercase tracking-[0.08em] text-[var(--text-faint)]">{t('desktop.title')}</div>
- <h2 id="desktop-title" className="mt-1.5 text-[22px] font-semibold leading-tight tracking-[-0.01em] text-[var(--text)]">
+ {/* what it does, and the download */}
+ <div className="flex min-h-0 min-w-0 flex-col">
+ <div className="min-h-0 flex-1 overflow-y-auto px-7 pb-5 pt-7 md:px-8">
+ <div className="flex items-center gap-2 text-[var(--text-muted)]">
+ <BrandLogo size={14} />
+ <span className="text-[11.5px] font-medium uppercase tracking-[0.1em]">{t('desktop.title')}</span>
+ </div>
+ <h2 id="desktop-title" className="mt-3 pr-8 text-[24px] font-semibold leading-[1.2] tracking-[-0.015em] text-[var(--text)]">
{t('desktop.tagline')}
</h2>
- <p className="mt-2 max-w-[600px] text-[13px] leading-relaxed text-[var(--text-muted)]">{t('desktop.intro')}</p>
-
- {/* the agents it works with */}
- <div className="mt-4 flex flex-wrap items-center gap-x-3 gap-y-2">
- <span className="text-[12px] text-[var(--text-faint)]">{t('desktop.worksWith')}</span>
- <span className="flex items-center gap-1.5">
- {AGENTS.map(({ id, name }) => (
- <span key={id} title={name} className="flex h-7 w-7 items-center justify-center rounded-lg border border-[var(--border)] bg-[var(--surface-2)]">
- <ProviderMark id={id} size={14} />
- </span>
- ))}
- </span>
- <span className="text-[12px] text-[var(--text-faint)]">{t('desktop.orOwnKey')}</span>
- </div>
+ <p className="mt-2.5 text-[13.5px] leading-relaxed text-[var(--text-muted)]">{t('desktop.intro')}</p>
- <ul className="mt-6 grid gap-x-6 gap-y-5 sm:grid-cols-2 md:grid-cols-3">
+ <ul className="mt-6 grid gap-x-6 gap-y-5 sm:grid-cols-2">
{FEATURES.map(({ key, icon }) => (
<li key={key} className="min-w-0">
- <span className="flex h-8 w-8 items-center justify-center rounded-lg border border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-dim)]">
- {icon}
+ <span className="flex items-center gap-2.5">
+ <span
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-[8px]"
+ style={{ background: 'color-mix(in srgb, var(--brand-wind-mid) 14%, transparent)', color: 'var(--brand-wind-from)' }}
+ >
+ {icon}
+ </span>
+ <span className="min-w-0 text-[13.5px] font-medium leading-snug text-[var(--text)]">{t(`desktop.features.${key}.title`)}</span>
</span>
- <span className="mt-2.5 block text-[13px] font-medium text-[var(--text)]">{t(`desktop.features.${key}.title`)}</span>
- <span className="mt-0.5 block text-[12.5px] leading-relaxed text-[var(--text-muted)]">{t(`desktop.features.${key}.body`)}</span>
+ <span className="mt-1.5 block text-[12.5px] leading-relaxed text-[var(--text-muted)]">{t(`desktop.features.${key}.body`)}</span>
</li>
))}
</ul>
</div>
- </div>
- <div className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-t border-[var(--border)] px-7 py-4">
- <span className="text-[12px] text-[var(--text-muted)]">
- {system ? t('desktop.status') : `${t('desktop.status')} · ${t('desktop.otherSystems')}`}
- </span>
- <div className="flex items-center gap-2">
- <button
- type="button"
- onClick={onClose}
- className="h-9 rounded-full px-4 text-[13px] text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
- >
- {t('desktop.close')}
- </button>
+ <div className="flex shrink-0 flex-wrap items-center justify-between gap-x-4 gap-y-3 border-t border-[var(--border)] px-7 py-4 md:px-8">
+ <span className="text-[12px] text-[var(--text-faint)]">
+ {[t('desktop.status'), t('desktop.otherSystems'), version ? `v${version}` : null].filter(Boolean).join(' · ')}
+ </span>
<button
ref={download}
type="button"
onClick={() => void openDownload()}
- className="inline-flex h-9 items-center gap-2 rounded-full bg-[var(--text)] px-5 text-[13px] font-medium text-[var(--card-bg)] transition hover:opacity-90"
+ className="inline-flex h-10 items-center gap-2 rounded-full bg-[var(--text)] px-5 text-[13.5px] font-medium text-[var(--card-bg)] transition hover:opacity-90"
>
{system ? (
<svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden><path d={system === 'mac' ? APPLE : WINDOWS} /></svg>
@@ -174,63 +216,53 @@ export function DesktopDialog({ open, onClose }: { open: boolean; onClose: () =>
function AppPicture() {
const t = useT();
return (
- <div
- aria-hidden
- className="relative h-[208px] shrink-0 overflow-hidden border-b border-[var(--card-border)]"
- style={{ background: 'radial-gradient(120% 140% at 15% 0%, color-mix(in srgb, var(--brand-wind-mid) 26%, transparent), transparent 60%), radial-gradient(90% 120% at 100% 100%, color-mix(in srgb, var(--brand-wind-to) 22%, transparent), transparent 55%), var(--surface-2)' }}
- >
- <div className="absolute inset-x-10 top-7 bottom-[-18px] overflow-hidden rounded-t-[10px] border border-[var(--border)] bg-[var(--dock-shell)] shadow-[0_18px_40px_-18px_rgba(0,0,0,0.5)]">
- {/* the window's top bar */}
- <div className="flex h-[18px] items-center gap-1 border-b border-[var(--border)] px-2">
- <span className="h-[6px] w-[6px] rounded-full bg-[#ff5f57]" />
- <span className="h-[6px] w-[6px] rounded-full bg-[#febc2e]" />
- <span className="h-[6px] w-[6px] rounded-full bg-[#28c840]" />
- </div>
- <div className="grid h-full grid-cols-[1fr_34%] gap-[5px] p-[5px]">
- {/* Studio: the picture, then the timeline */}
- <div className="flex min-w-0 flex-col gap-[5px]">
- <div className="flex h-[96px] items-center justify-center rounded-[5px] bg-[var(--surface)]">
- <div
- className="flex h-[78px] w-[138px] flex-col justify-end rounded-[3px] p-2"
- style={{ background: 'linear-gradient(135deg, var(--brand-wind-from), var(--brand-wind-to))' }}
- >
- <span className="h-[7px] w-[64px] rounded-full bg-white/90" />
- <span className="mt-1 h-[4px] w-[40px] rounded-full bg-white/60" />
- </div>
+ <div aria-hidden className="w-full overflow-hidden rounded-[12px] border border-white/10 bg-[var(--dock-shell)] shadow-[0_24px_48px_-20px_rgba(0,0,0,0.7)]">
+ {/* the window's top bar */}
+ <div className="flex h-[22px] items-center gap-[5px] border-b border-[var(--border)] px-2.5">
+ <span className="h-[7px] w-[7px] rounded-full bg-[#ff5f57]" />
+ <span className="h-[7px] w-[7px] rounded-full bg-[#febc2e]" />
+ <span className="h-[7px] w-[7px] rounded-full bg-[#28c840]" />
+ </div>
+ <div className="grid grid-cols-[1fr_40%] gap-[5px] p-[5px]">
+ {/* Studio: the picture, then the timeline */}
+ <div className="flex min-w-0 flex-col gap-[5px]">
+ <div className="flex aspect-[16/10] items-center justify-center rounded-[6px] bg-[var(--surface)]">
+ <div
+ className="flex aspect-video w-[78%] flex-col justify-end rounded-[4px] p-[8%]"
+ style={{ background: 'linear-gradient(135deg, #5ecb92, #7fd3e4)' }}
+ >
+ <span className="openfilm-desktop-pulse h-[7px] w-[58%] rounded-full bg-white/90" />
+ <span className="mt-[4px] h-[4px] w-[36%] rounded-full bg-white/60" />
</div>
- <div className="relative flex-1 rounded-[5px] bg-[var(--surface)] px-[6px] py-[6px]">
- <div className="flex flex-col gap-[4px]">
- <div className="flex gap-[3px]">
- <span className="h-[11px] w-[30%] rounded-[2px] bg-[color-mix(in_srgb,var(--text)_14%,transparent)]" />
- <span className="openfilm-desktop-pulse h-[11px] w-[26%] rounded-[2px] outline outline-[1.5px] outline-offset-[1px]" style={{ background: 'color-mix(in srgb, var(--tl-accent) 45%, transparent)', outlineColor: 'var(--tl-accent)' }} />
- <span className="h-[11px] w-[34%] rounded-[2px] bg-[color-mix(in_srgb,var(--text)_14%,transparent)]" />
- </div>
- <div className="flex gap-[3px] pl-[18%]">
- <span className="h-[11px] w-[48%] rounded-[2px] bg-[color-mix(in_srgb,var(--brand-wind-mid)_40%,transparent)]" />
- </div>
- <span className="h-[9px] w-[92%] rounded-[2px] bg-[color-mix(in_srgb,var(--tl-wave)_55%,transparent)]" />
+ </div>
+ <div className="relative rounded-[6px] bg-[var(--surface)] px-[6px] py-[7px]">
+ <div className="flex flex-col gap-[4px]">
+ <div className="flex gap-[3px]">
+ <span className="h-[10px] w-[30%] rounded-[2px] bg-white/[0.13]" />
+ <span className="openfilm-desktop-pulse h-[10px] w-[28%] rounded-[2px] outline outline-[1.5px] outline-offset-[1px]" style={{ background: 'color-mix(in srgb, var(--tl-accent) 45%, transparent)', outlineColor: 'var(--tl-accent)' }} />
+ <span className="h-[10px] w-[34%] rounded-[2px] bg-white/[0.13]" />
</div>
- <span className="openfilm-desktop-playhead absolute bottom-[4px] top-[2px] w-[1.5px] rounded-full bg-[var(--tl-playhead)]" />
+ <div className="flex gap-[3px] pl-[18%]">
+ <span className="h-[10px] w-[48%] rounded-[2px] bg-[color-mix(in_srgb,#66d8b8_40%,transparent)]" />
+ </div>
+ <span className="h-[8px] w-[92%] rounded-[2px] bg-[color-mix(in_srgb,var(--tl-wave)_55%,transparent)]" />
</div>
+ <span className="openfilm-desktop-playhead absolute bottom-[4px] top-[3px] w-[1.5px] rounded-full bg-[var(--tl-playhead)]" />
</div>
- {/* the chat beside it */}
- <div className="flex min-w-0 flex-col gap-[5px] rounded-[5px] bg-[var(--surface)] p-[6px]">
- <div className="ml-auto max-w-[92%] rounded-[6px] bg-[var(--surface-2)] px-[6px] py-[5px]">
- <span
- className="openfilm-desktop-pulse mb-[4px] inline-flex items-center gap-[3px] rounded-[3px] px-[4px] py-[1px] text-[7.5px] font-medium leading-tight"
- style={{ background: 'color-mix(in srgb, var(--tl-accent) 18%, transparent)', color: 'var(--tl-accent)', boxShadow: 'inset 0 0 0 1px var(--tl-accent)' }}
- >
- {t('desktop.picture.clip')}
- </span>
- <span className="block text-[8px] leading-snug text-[var(--text)]">{t('desktop.picture.ask')}</span>
- </div>
- <div className="max-w-[92%] text-[8px] leading-snug text-[var(--text-muted)]">{t('desktop.picture.reply')}</div>
- <div className="flex flex-col gap-[3px]">
- <span className="h-[4px] w-[86%] rounded-full bg-[color-mix(in_srgb,var(--text)_12%,transparent)]" />
- <span className="h-[4px] w-[64%] rounded-full bg-[color-mix(in_srgb,var(--text)_12%,transparent)]" />
- </div>
- <div className="mt-auto h-[16px] rounded-[5px] border border-[var(--border)] bg-[var(--surface-2)]" />
+ </div>
+ {/* the chat beside it */}
+ <div className="flex min-w-0 flex-col gap-[6px] rounded-[6px] bg-[var(--surface)] p-[6px]">
+ <div className="ml-auto max-w-[96%] rounded-[6px] bg-[var(--surface-2)] px-[6px] py-[5px]">
+ <span
+ className="openfilm-desktop-pulse mb-[4px] inline-flex max-w-full items-center truncate rounded-[3px] px-[4px] py-[1px] text-[7.5px] font-medium leading-tight"
+ style={{ background: 'color-mix(in srgb, var(--tl-accent) 18%, transparent)', color: 'var(--tl-accent)', boxShadow: 'inset 0 0 0 1px var(--tl-accent)' }}
+ >
+ {t('desktop.picture.clip')}
+ </span>
+ <span className="block text-[8px] leading-snug text-[var(--text)]">{t('desktop.picture.ask')}</span>
</div>
+ <div className="max-w-[96%] text-[8px] leading-snug text-[var(--text-muted)]">{t('desktop.picture.reply')}</div>
+ <div className="mt-auto h-[18px] rounded-[5px] border border-[var(--border)] bg-[var(--surface-2)]" />
</div>
</div>
</div>
diff --git a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx
index c7920e1..826be35 100644
--- a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx
+++ b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx
@@ -18,8 +18,8 @@ import * as React from 'react';
import {
AlignCenterHorizontal, AlignCenterVertical, AlignEndHorizontal, AlignEndVertical, AlignHorizontalDistributeCenter,
AlignStartHorizontal, AlignStartVertical, AlignVerticalDistributeCenter, ArrowRightToLine, AudioLines, Captions,
- ChevronRight, CircleAlert, Clapperboard, Film, Gauge, Image as ImageIcon, Link2, Maximize2, MousePointerClick,
- Lock, MoveHorizontal, Music, RotateCcw, Scissors, Shapes, Square, Type, Unlink2, Video, Volume2, X,
+ Check, ChevronRight, CircleAlert, Clapperboard, Copy, Film, Gauge, Image as ImageIcon, Link2, Maximize2, MousePointerClick,
+ Lock, MoveHorizontal, Music, RotateCcw, Scissors, Shapes, Sparkles, Square, Type, Unlink2, Video, Volume2, X,
} from 'lucide-react';
import {
@@ -39,12 +39,14 @@ import type { TimelineBlock } from '@/lib/timeline-layout';
import { editsForMoves } from '@/lib/timeline-drag';
import { useTimelinePrefs } from '@/lib/timeline-prefs';
import { formatTimecode, FRAME_RATES, timecodeFps, useTimecodeFps } from '@/lib/timecode';
-import { FILM_FRAME_IDS, filmFrameOf, filmFrameStage, type FilmFrameId } from '@/lib/film-frame';
+import { MenuSelect } from './MenuSelect';
+import { filmFrameOf, filmFrameRatio, type FilmFrameId } from '@/lib/film-frame';
+import { CANVAS_RATIOS, canvasRatioLabel } from './FramePicker';
import { declared, withDeclarations, type ClipLook } from '@/lib/clip-look';
import { PANE_BAR, PANE_BTN, PANE_ICON, PANE_TITLE } from './dock-pane-bar';
import { Tooltip } from './Tooltip';
import {
- ColorField, ICON, MIXED, NumField, RadiusGlyph, Row, RotateGlyph, Section, SectionAction, Segmented, SelectField, SliderField, SubLabel,
+ ColorField, ICON, MIXED, NumField, RadiusGlyph, Row, RotateGlyph, Section, SectionAction, Segmented, SliderField,
useTimeUnit, type FieldApply, type Mixed,
} from './inspector-fields';
import {
@@ -153,7 +155,6 @@ export const FilmInspector = React.memo(function FilmInspector({
onEditMask,
film,
onCanvas,
- frame,
layers,
onEditLayers,
locked = false,
@@ -207,10 +208,8 @@ export const FilmInspector = React.memo(function FilmInspector({
onEditMask?: (session: MaskSession | null) => void;
/** The film when nothing is selected. */
film?: FilmSummary | null;
- /** The stage's shape, while nothing has been made yet (FramePicker's onCanvas). */
- onCanvas?: (next: FilmFrameId, size: { w: number; h: number }) => void;
- /** The delivery frame, once the film has content (FramePicker's delivery mode). */
- frame?: { value: FilmFrameId; onChange: (next: FilmFrameId) => void } | null;
+ /** The canvas: a shape (the editor grows it around the film), or a size typed. */
+ onCanvas?: (next: FilmFrameId, size?: { w: number; h: number }) => void;
/** Several layers selected on the picture, and how to write them at once. */
layers?: readonly StageElement[];
onEditLayers?: (list: LayerEdit[]) => Promise<string | null>;
@@ -302,7 +301,7 @@ export const FilmInspector = React.memo(function FilmInspector({
) : geometry?.kind === 'group' && geometry.group ? (
<GroupPanel geometry={geometry} group={geometry.group} layers={layers} onEditLayers={onEditLayers} t={t} />
) : (
- <FilmPanel t={t} stage={stageSize} film={film ?? null} onCanvas={onCanvas} frame={frame ?? null} rate={rate ?? null} />
+ <FilmPanel t={t} stage={stageSize} film={film ?? null} onCanvas={onCanvas} rate={rate ?? null} />
)}
</div>
</fieldset>
@@ -312,28 +311,60 @@ export const FilmInspector = React.memo(function FilmInspector({
/* ───────────────────────────── nothing selected: the film ───────────────────────────── */
-const STAGE_PRESETS: FilmFrameId[] = ['16:9', '9:16', '1:1', '4:5'];
/** Even sizes: H.264 samples chroma in 2×2 blocks and refuses odd dimensions (as film-frame does). */
const even = (n: number) => Math.max(2, Math.round(n / 2) * 2);
+/**
+ * For a film that has clips: the canvas changes here, and laying the film out again for it is the agent's. The words
+ * that ask for it, with the canvas as it is now, to copy into the chat.
+ */
+function RedesignHint({ t, stage }: { t: T; stage: { w: number; h: number } }) {
+ const [open, setOpen] = React.useState(false);
+ const [copied, setCopied] = React.useState(false);
+ const shape = filmFrameOf(stage);
+ const ask = t('inspector.redesignAsk').replace('{ratio}', shape === 'native' ? `${stage.w}:${stage.h}` : shape).replace('{size}', `${stage.w}×${stage.h}`);
+ React.useEffect(() => { setCopied(false); }, [ask]);
+ return (
+ <div className="flex flex-col gap-2">
+ <button type="button" onClick={() => setOpen((v) => !v)} aria-expanded={open}
+ className="flex h-7 items-center gap-1.5 self-start rounded-md px-1.5 text-[11px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">
+ <Sparkles size={12} />
+ {t('inspector.redesignOpen')}
+ </button>
+ {open ? (
+ <div className="flex flex-col gap-2 rounded-lg border border-[var(--border)] bg-[var(--fill-tsp)] p-2.5">
+ <p className="text-[10.5px] leading-[15px] text-[var(--text-muted)]">{t('inspector.redesignBody')}</p>
+ <p className="select-text rounded-md bg-[var(--bg)] px-2 py-1.5 text-[11px] leading-[16px] text-[var(--text)]">{ask}</p>
+ <button type="button"
+ onClick={() => { void navigator.clipboard?.writeText(ask).then(() => setCopied(true), () => {}); }}
+ className="flex h-7 items-center justify-center gap-1.5 rounded-md bg-[var(--text)] text-[11px] font-medium text-[var(--bg)] transition hover:opacity-90">
+ {copied ? <Check size={12} /> : <Copy size={12} />}
+ {t(copied ? 'inspector.redesignCopied' : 'inspector.redesignCopy')}
+ </button>
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
/**
* The film itself: its name, its stage and shape, how long it is, what is in it. The shape changes as the
- * player's frame button changes it (FramePicker): the stage itself while nothing has been made (no coordinate can
- * break yet), the delivery frame around the film once it has content.
+ * player's ratio button changes it (FramePicker): the canvas itself, at any time, as an image editor's canvas size
+ * (what is on it stays as it is, centered); laying the film out again for it is the agent's (RedesignHint).
*/
function FilmPanel({
- t, stage, film, onCanvas, frame, rate,
+ t, stage, film, onCanvas, rate,
}: {
t: T;
stage: { w: number; h: number };
film: FilmSummary | null;
- onCanvas?: (next: FilmFrameId, size: { w: number; h: number }) => void;
- frame: { value: FilmFrameId; onChange: (next: FilmFrameId) => void } | null;
+ onCanvas?: (next: FilmFrameId, size?: { w: number; h: number }) => void;
rate: { fps: number; fromFootage: boolean; onChange: (fps: number) => void } | null;
}) {
- const canvas = Boolean(film?.empty && onCanvas);
- const shape = filmFrameOf(stage);
+ const canvas = Boolean(onCanvas);
+ const placed = Boolean(film && !film.empty);
+ const preset = CANVAS_RATIOS.find((r) => Math.abs(stage.w / Math.max(1, stage.h) - filmFrameRatio(r.id, stage)) < 0.01);
const setSize = (w: number, h: number) => {
const size = { w: even(w), h: even(h) };
if (size.w === stage.w && size.h === stage.h) return;
@@ -354,43 +385,32 @@ function FilmPanel({
/>
<Section id="film-stage" title={t('inspector.stage')}>
{canvas ? (
- <Segmented
+ <MenuSelect
label={t('inspector.stageShape')}
- value={STAGE_PRESETS.includes(shape) ? shape : 'custom'}
- small
- options={[...STAGE_PRESETS.map((id) => ({ value: id, label: id })), { value: 'custom', label: t('inspector.custom') }]}
- onChange={(id) => { if (id !== 'custom') onCanvas?.(id as FilmFrameId, filmFrameStage(stage, id as FilmFrameId)); }}
+ value={preset?.id ?? 'custom'}
+ groups={[
+ { choices: preset ? [] : [{ value: 'custom', label: `${t('viewer.frameCustom')} · ${stage.w}×${stage.h}` }] },
+ { choices: CANVAS_RATIOS.filter((r) => r.group === 'wide').map((r) => ({ value: r.id, label: canvasRatioLabel(t, r) })) },
+ { choices: CANVAS_RATIOS.filter((r) => r.group === 'tall').map((r) => ({ value: r.id, label: canvasRatioLabel(t, r) })) },
+ ].filter((g) => g.choices.length)}
+ onPick={(id) => { if (id !== 'custom') onCanvas?.(id as FilmFrameId); }}
/>
) : null}
<Row>
<NumField label={t('inspector.width')} prefix="W" value={stage.w} unit="px" min={2} max={8192} disabled={!canvas} onCommit={(w) => setSize(w, stage.h)} />
<NumField label={t('inspector.height')} prefix="H" value={stage.h} unit="px" min={2} max={8192} disabled={!canvas} onCommit={(h) => setSize(stage.w, h)} />
</Row>
- {!canvas && frame ? (
- <>
- <SubLabel>{t('inspector.deliveryFrame')}</SubLabel>
- <Segmented
- label={t('inspector.deliveryFrame')}
- value={frame.value}
- small
- options={FILM_FRAME_IDS.filter((id) => id === 'native' || STAGE_PRESETS.includes(id)).map((id) => ({
- value: id,
- label: id === 'native' ? t('viewer.frameNative') : id,
- }))}
- onChange={(id) => frame.onChange(id as FilmFrameId)}
- />
- </>
- ) : null}
- <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{canvas ? t('viewer.canvasNote') : t('inspector.stageFixed')}</p>
+ <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t(placed ? 'inspector.stageFixed' : 'viewer.canvasNote')}</p>
+ {/* with clips: the words that ask the agent to lay the film out again for this canvas */}
+ {placed ? <RedesignHint t={t} stage={stage} /> : null}
</Section>
{rate ? (
<Section id="film-rate" title={t('inspector.frameRate')}>
- <SelectField
+ <MenuSelect
label={t('inspector.frameRate')}
- prefix="fps"
value={String(rate.fps)}
- options={FRAME_RATES.map((r) => ({ value: String(r), label: String(r) }))}
- onCommit={(v) => rate.onChange(Number(v))}
+ groups={[{ choices: FRAME_RATES.map((r) => ({ value: String(r), label: `${r} fps` })) }]}
+ onPick={(v) => rate.onChange(Number(v))}
/>
<p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t(rate.fromFootage ? 'inspector.frameRateFootage' : 'inspector.frameRateNote')}</p>
</Section>
diff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
index d94930b..bb09d45 100644
--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
@@ -51,7 +51,7 @@ import { useT } from '@/i18n';
import { cropOf, declared, pxOf, type ClipLook, type Crop } from '@/lib/clip-look';
import { filmClipKind, filmDocLoc, filmSrcKind, parseFilmDocLoc, type FilmBox, type FilmDoc } from '@/lib/film';
import type { OverrideGeometry } from '@/lib/film-overrides';
-import type { ClipSpan } from '@/lib/film-shape';
+import { spanShows, type ClipSpan } from '@/lib/film-shape';
import {
mgSize, moveTransform, rotateTransform, sameMgTransform, snapMove, type MgBox, type MgGuide, type MgTransform,
} from '@/lib/mg-transform';
@@ -720,10 +720,21 @@ function FilmStageSelectImpl({
}, [syncQueue]);
React.useEffect(() => () => { if (geomRaf.current) cancelAnimationFrame(geomRaf.current); geomRaf.current = 0; }, []);
- /* the playhead moved a bucket on: what is selected stays selected, only where it is changed */
+ /* the playhead moved a bucket on: what is selected stays selected, only where it is changed. A layer whose clip is
+ not on screen any more lets go: its box would stand over a picture it is not in */
const stale = staleBucket(timeMs);
React.useEffect(() => {
- if (pickedRef.current) syncGeomSoon();
+ const held = pickedRef.current;
+ if (!held) return;
+ const clip = held.element?.kind !== 'clip' ? held.layer?.clip : undefined;
+ const span = clip ? spans.find((s) => s.id === clip) : undefined;
+ if (span && !spanShows(span, timeMs)) {
+ dropPick();
+ onSelectElement?.(null);
+ return;
+ }
+ syncGeomSoon();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [stale, syncGeomSoon]);
/* film.html changed (an edit, an undo, the agent): the picture follows it a moment later */
React.useEffect(() => {
@@ -1041,7 +1052,8 @@ function FilmStageSelectImpl({
};
keyHandler.current = onKey;
/* a press elsewhere lets go: selecting is "I mean this one", and the hand moving away ends it. Not the stage, its
- menus, the inspector (and its floating panels), the dividers, list boxes, or the timeline (it selects itself). */
+ menus, the inspector (and its floating panels), the dividers or list boxes. On the timeline only layers let go:
+ a whole clip in hand is the timeline's own selection, which it keeps or clears itself. */
const onDown = (e: PointerEvent) => {
const el = e.target as HTMLElement | null;
if (
@@ -1052,8 +1064,8 @@ function FilmStageSelectImpl({
|| el?.closest('[role="separator"]')
|| el?.closest('[role="listbox"]')
|| el?.closest('[data-popover-panel]')
- || el?.closest('[data-timeline]')
) return;
+ if (el?.closest('[data-timeline]') && (!pickedRef.current?.element || pickedRef.current.element.kind === 'clip')) return;
dropPick();
onSelectElement?.(null);
};
diff --git a/packages/openfilm/studio/ui/src/components/FramePicker.tsx b/packages/openfilm/studio/ui/src/components/FramePicker.tsx
index fe74cdf..d238812 100644
--- a/packages/openfilm/studio/ui/src/components/FramePicker.tsx
+++ b/packages/openfilm/studio/ui/src/components/FramePicker.tsx
@@ -1,60 +1,63 @@
/**
- * The aspect ratio button beside the picture. What it changes depends on how far the film has got.
- *
- * Canvas mode (`mode='canvas'`, nothing made yet): it changes the stage itself. No coordinate can break yet, and a
- * person picking 9:16 now means "this film is vertical" — so the film's stage really changes (`onCanvas`), and the
- * agent lays out vertically from then on.
- *
- * Delivery mode (`mode='delivery'`, the film has content): it changes the frame around the film. The film is fitted
- * in with black bars; film.html is untouched (see lib/film-frame). The choice is kept per project
- * (`useDeliveryFrame`).
+ * The aspect ratio button beside the picture: the film's canvas (its stage in film.html). Picking a shape changes the
+ * canvas itself (`onCanvas`), as an image editor's canvas size: it grows around the film, which stays as it is,
+ * centered, until the agent lays it out again. A delivery frame (bars or a crop around the film) is the export's.
*
* Each item draws its shape rather than only a ratio: a row of small boxes tells landscape from portrait at a glance.
*/
import * as React from 'react';
import { Check, Proportions } from 'lucide-react';
import { useT } from '@/i18n';
-import {
- FILM_FRAME_IDS,
- filmFrameOf,
- filmFrameRatio,
- filmFrameStage,
- readFilmFrame,
- writeFilmFrame,
- type FilmFrameId,
-} from '@/lib/film-frame';
+import { customFilmFrame, filmFrameRatio, type FilmFrameId } from '@/lib/film-frame';
import { Tooltip } from './Tooltip';
-/** Which layer the button changes: the film's canvas, or the delivery frame around it. */
-export type FramePickerMode = 'canvas' | 'delivery';
+/**
+ * The shapes a canvas is offered in, as CapCut lists them: landscape, then portrait (`hint`: a word after the ratio,
+ * from viewer.ratioHint).
+ */
+export const CANVAS_RATIOS: { group: 'wide' | 'tall'; id: FilmFrameId; hint?: string }[] = [
+ { group: 'wide', id: '16:9', hint: 'wide' },
+ { group: 'wide', id: '4:3' },
+ { group: 'wide', id: '2.35:1' },
+ { group: 'wide', id: '2:1' },
+ { group: 'wide', id: '1.85:1' },
+ { group: 'tall', id: '9:16', hint: 'tall' },
+ { group: 'tall', id: '3:4' },
+ { group: 'tall', id: '9:19.5', hint: 'phone' },
+ { group: 'tall', id: '1:1' },
+ { group: 'tall', id: '1:2' },
+];
+
+/** A ratio's name in the menu: "9:16 (TikTok)", "5.8″ phone". */
+export function canvasRatioLabel(t: (key: string) => string, item: { id: FilmFrameId; hint?: string }): string {
+ if (item.hint === 'phone') return t('viewer.ratioPhone');
+ return item.hint ? `${item.id} ${t(`viewer.ratioHint.${item.hint}`)}` : item.id;
+}
+
+/** Whether the stage has this ratio (to a hundredth). */
+const shaped = (stage: { w: number; h: number }, ratio: number) => Math.abs(stage.w / Math.max(1, stage.h) - ratio) < 0.01;
export function FramePicker({
- stage, value, mode, busy, onDelivery, onCanvas,
+ stage, original, busy, onCanvas,
}: {
stage: { w: number; h: number };
- /** The delivery frame now. Ignored in canvas mode, where the current one is the canvas's own shape. */
- value: FilmFrameId;
- mode: FramePickerMode;
+ /** The first picture's own size: "Fit (original)" takes its shape. None: nothing to fit to yet. */
+ original?: { w: number; h: number } | null;
/** The canvas change is being written: no second one meanwhile (two requests would race for one file). */
busy?: boolean;
- /** Delivery mode: a frame was picked (persist it with `useDeliveryFrame`). */
- onDelivery: (next: FilmFrameId) => void;
- /**
- * Canvas mode: change the film's stage to this ratio; `size` is the stage it should become (1080p family, see
- * filmFrameStage). If the film has gained content meanwhile, fall back to the delivery frame instead.
- */
- onCanvas: (next: FilmFrameId, size: { w: number; h: number }) => void;
+ /** Change the film's canvas to this shape (the editor works out its size and fits the film into it). */
+ onCanvas: (next: FilmFrameId) => void;
}): React.ReactElement {
const t = useT();
const [open, setOpen] = React.useState(false);
+ const [custom, setCustom] = React.useState(false);
const box = React.useRef<HTMLDivElement | null>(null);
- const canvas = mode === 'canvas';
- /* the canvas has no "native" to pick: the canvas is native. The tick goes on the item shaped like it. */
- const items = canvas ? FILM_FRAME_IDS.filter((id) => id !== 'native') : FILM_FRAME_IDS;
- const current = canvas ? filmFrameOf(stage) : value;
+ const fit = original ? customFilmFrame(original.w, original.h) : null;
+ const preset = CANVAS_RATIOS.find((r) => shaped(stage, filmFrameRatio(r.id, stage)));
+ const isFit = Boolean(original && shaped(stage, original.w / original.h));
React.useEffect(() => {
- if (!open) return undefined;
+ if (!open) { setCustom(false); return undefined; }
const away = (e: MouseEvent): void => {
if (!box.current?.contains(e.target as Node)) setOpen(false);
};
@@ -62,14 +65,20 @@ export function FramePicker({
return () => window.removeEventListener('mousedown', away);
}, [open]);
- const pick = (id: FilmFrameId) => {
- if (canvas) onCanvas(id, filmFrameStage(stage, id));
- else onDelivery(id);
- };
+ const pick = (id: FilmFrameId) => { setOpen(false); onCanvas(id); };
+ const row = 'flex w-full items-center gap-2.5 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-[var(--text)] transition hover:bg-[var(--bg-hover)] disabled:pointer-events-none disabled:opacity-40';
+ const tick = (on: boolean) => <span className="flex w-3.5 shrink-0 justify-center">{on ? <Check size={13} className="text-[var(--accent)]" /> : null}</span>;
+ const item = (r: (typeof CANVAS_RATIOS)[number]) => (
+ <button key={r.id} type="button" disabled={busy} onClick={() => pick(r.id)} onMouseDown={(e) => e.preventDefault()} className={row}>
+ {tick(!isFit && preset?.id === r.id)}
+ <span className="flex-1">{canvasRatioLabel(t, r)}</span>
+ <ShapeChip ratio={filmFrameRatio(r.id, stage)} />
+ </button>
+ );
return (
<div ref={box} className="relative flex items-center">
- <Tooltip label={t(canvas ? 'viewer.canvas' : 'viewer.frame')}>
+ <Tooltip label={t('viewer.canvas')}>
<button
type="button"
onClick={() => setOpen((v) => !v)}
@@ -78,46 +87,70 @@ export function FramePicker({
className={`flex h-[22px] items-center gap-1 rounded-md px-1.5 text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] ${
busy ? 'opacity-50' : ''
}`}
- aria-label={t(canvas ? 'viewer.canvas' : 'viewer.frame')}
+ aria-label={t('viewer.canvas')}
aria-expanded={open}
>
<Proportions size={14} />
- {/* the ratio is printed on the button: "this film is vertical now" must be visible without opening it */}
- {current !== 'native' ? (
- <span className="text-[12px] leading-none tabular-nums">{current}</span>
- ) : null}
+ {/* the ratio is printed on the button: "this film is vertical" must be visible without opening it */}
+ <span className="text-[12px] leading-none tabular-nums">{preset ? preset.id : `${stage.w}×${stage.h}`}</span>
</button>
</Tooltip>
{open ? (
- <div
- className="absolute bottom-[28px] right-0 z-50 w-[164px] rounded-[8px] border border-[var(--border)] bg-[var(--surface)] p-1 shadow-[var(--shadow-lg)]"
- >
- {/* picking does not close the menu: a ratio is judged by looking at the result, often two or three in a row */}
- {items.map((id) => (
- <button
- key={id}
- type="button"
- disabled={busy}
- onClick={() => pick(id)}
- onMouseDown={(e) => e.preventDefault()}
- className="flex w-full items-center gap-2.5 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-[var(--text)] transition hover:bg-[var(--bg-hover)] disabled:pointer-events-none disabled:opacity-40"
- >
- <ShapeChip ratio={filmFrameRatio(id, stage)} />
- <span className="flex-1">{id === 'native' ? t('viewer.frameNative') : id}</span>
- {current === id ? <Check size={13} className="shrink-0 text-[var(--accent)]" /> : null}
- </button>
- ))}
- {canvas ? (
- <p className="px-2 pb-1 pt-1.5 text-[10.5px] leading-snug text-[var(--text-faint)]">
- {t('viewer.canvasNote')}
- </p>
- ) : null}
+ <div className="absolute bottom-[28px] right-0 z-50 max-h-[min(520px,75vh)] w-[220px] overflow-y-auto rounded-[8px] border border-[var(--border)] bg-[var(--surface)] p-1 shadow-[var(--shadow-lg)]">
+ <button type="button" disabled={busy || !fit} onClick={() => fit && pick(fit)} onMouseDown={(e) => e.preventDefault()} className={row}>
+ {tick(isFit)}
+ <span className="flex-1">{t('viewer.ratioOriginal')}</span>
+ </button>
+ <button type="button" disabled={busy} onClick={() => setCustom((v) => !v)} onMouseDown={(e) => e.preventDefault()} className={row}>
+ {tick(!isFit && !preset)}
+ <span className="flex-1">{t('viewer.frameCustom')}</span>
+ {!preset ? <span className="text-[11px] tabular-nums text-[var(--text-faint)]">{`${stage.w}×${stage.h}`}</span> : null}
+ </button>
+ {custom ? <CustomFrame value={preset?.id ?? 'native'} disabled={busy} onPick={pick} /> : null}
+ <div className="mx-1 my-1 h-px bg-[var(--border)]" />
+ {CANVAS_RATIOS.filter((r) => r.group === 'wide').map(item)}
+ <div className="mx-1 my-1 h-px bg-[var(--border)]" />
+ {CANVAS_RATIOS.filter((r) => r.group === 'tall').map(item)}
</div>
) : null}
</div>
);
}
+/**
+ * A ratio of the person's own, typed as width and height ("2.39" by "1", "5" by "4"), from 1:4 to 4:1: Enter or the
+ * check puts it in use. Starts from the frame in use.
+ */
+export function CustomFrame({ value, disabled, onPick, className = '' }: {
+ value: FilmFrameId;
+ disabled?: boolean;
+ onPick: (id: FilmFrameId) => void;
+ className?: string;
+}) {
+ const t = useT();
+ const [w0, h0] = value === 'native' ? ['16', '9'] : value.split(':');
+ const [w, setW] = React.useState(w0 ?? '16');
+ const [h, setH] = React.useState(h0 ?? '9');
+ const id = customFilmFrame(Number(w), Number(h));
+ const apply = () => { if (id) onPick(id); };
+ const field = 'h-6 w-12 rounded-[5px] border border-[var(--border)] bg-[var(--bg)] px-1.5 text-center text-[12px] tabular-nums text-[var(--text)] outline-none focus:border-[var(--accent)]';
+ return (
+ <div className={`flex items-center gap-1.5 px-2 py-1 ${className}`}>
+ <span className="mr-auto text-[11.5px] text-[var(--text-muted)]">{t('viewer.frameCustom')}</span>
+ <input aria-label={t('viewer.frameCustomW')} inputMode="decimal" value={w} disabled={disabled}
+ onChange={(e) => setW(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') apply(); }} className={field} />
+ <span className="text-[12px] text-[var(--text-faint)]">:</span>
+ <input aria-label={t('viewer.frameCustomH')} inputMode="decimal" value={h} disabled={disabled}
+ onChange={(e) => setH(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') apply(); }} className={field} />
+ <button type="button" disabled={disabled || !id} onClick={apply} aria-label={t('viewer.frameCustomApply')}
+ title={id ? undefined : t('viewer.frameCustomRange')}
+ className="flex h-6 w-6 items-center justify-center rounded-[5px] text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-30">
+ <Check size={13} />
+ </button>
+ </div>
+ );
+}
+
/** A small box drawn to the ratio: the long side 16px, the short side follows. */
function ShapeChip({ ratio }: { ratio: number }) {
const w = ratio >= 1 ? 16 : 16 * ratio;
@@ -125,20 +158,9 @@ function ShapeChip({ ratio }: { ratio: number }) {
return (
<span className="flex h-4 w-4 shrink-0 items-center justify-center">
<span
- className="rounded-[2px] border border-current opacity-70"
+ className="rounded-[2px] border-[1.5px] border-current opacity-60"
style={{ width: Math.max(4, w), height: Math.max(4, h) }}
/>
</span>
);
}
-
-/** The project's delivery frame, kept in localStorage `openfilm.frame.<projectId>`. */
-export function useDeliveryFrame(projectId: string): [FilmFrameId, (next: FilmFrameId) => void] {
- const [frame, setFrame] = React.useState<FilmFrameId>(() => readFilmFrame(projectId));
- React.useEffect(() => { setFrame(readFilmFrame(projectId)); }, [projectId]);
- const set = React.useCallback((next: FilmFrameId) => {
- setFrame(next);
- writeFilmFrame(projectId, next);
- }, [projectId]);
- return [frame, set];
-}
diff --git a/packages/openfilm/studio/ui/src/components/MediaPool.tsx b/packages/openfilm/studio/ui/src/components/MediaPool.tsx
index 1e996e7..0c1d04f 100644
--- a/packages/openfilm/studio/ui/src/components/MediaPool.tsx
+++ b/packages/openfilm/studio/ui/src/components/MediaPool.tsx
@@ -21,6 +21,8 @@ import {
Folder,
FolderOpen,
FolderPlus,
+ LayoutGrid,
+ List,
ListFilter,
Pencil,
Plus,
@@ -58,6 +60,8 @@ const FILTERS: readonly Filter[] = ['all', 'video', 'image', 'audio', 'page'];
const SORTS: readonly SortKey[] = ['name', 'time', 'duration', 'type'];
/** A tile dragged inside the pane, to be moved into a folder. */
const FOLDER_DRAG = 'application/x-openfilm-media';
+/** Files dragged in from the computer, not a tile of this pane (the browser adds a dragged picture as a file). */
+const fromComputer = (dt: DataTransfer) => dt.types.includes('Files') && !dt.types.includes(FOLDER_DRAG);
/** The open folder per project, kept across remounts (the layout re-mounts the pane). */
const OPEN_FOLDER = new Map<string, string>();
@@ -68,7 +72,8 @@ const hiddenDir = (rel: string) => HIDDEN_DIRS.some((re) => re.test(rel));
const isMedia = (f: WorkspaceResource) => f.kind === 'video' || f.kind === 'image' || f.kind === 'audio';
const filterOf = (f: WorkspaceResource): Filter => (f.kind === 'mg' ? 'page' : f.kind as Filter);
-interface ViewState { sort: SortKey; filter: Filter }
+/** `layout`: tiles in a grid, or rows of a list (name, length, kind). */
+interface ViewState { sort: SortKey; filter: Filter; layout: 'grid' | 'list' }
const viewKey = (projectId: string) => `openfilm.media.${projectId}`;
function loadView(projectId: string): ViewState {
try {
@@ -76,8 +81,9 @@ function loadView(projectId: string): ViewState {
return {
sort: SORTS.includes(raw?.sort as SortKey) ? raw!.sort as SortKey : 'name',
filter: FILTERS.includes(raw?.filter as Filter) ? raw!.filter as Filter : 'all',
+ layout: raw?.layout === 'list' ? 'list' : 'grid',
};
- } catch { return { sort: 'name', filter: 'all' }; }
+ } catch { return { sort: 'name', filter: 'all', layout: 'grid' }; }
}
type Item = { type: 'folder'; rel: string; name: string; count: number; covers: WorkspaceResource[] } | { type: 'file'; file: WorkspaceResource };
@@ -99,6 +105,11 @@ export interface MediaPoolProps {
onImport: (files: File[], folder: string, onProgress: (ratio: number) => void) => Promise<unknown>;
/** Rename or move a file or folder (project-relative `from` → `to`); its clips follow. */
onMove: (from: string, to: string) => Promise<MediaResult>;
+ /**
+ * What a move could not keep true, asked before it: the paths a page or script among what moves makes while it runs
+ * (the rest of its links are written again by Studio). Empty: nothing to say.
+ */
+ onMoveCheck?: (from: string, to: string) => Promise<{ file: string; unseen: string[] }[]>;
/** Delete a file or folder (project-relative). Its clips were already taken off (`onDropClips`). */
onDelete: (path: string) => Promise<MediaResult>;
/** A video's sound made a file of its own beside it (it shows up in the listing like any new file). */
@@ -137,6 +148,7 @@ export function MediaPool({
onSelectFile,
onImport,
onMove,
+ onMoveCheck,
onDelete,
onExtractAudio,
onNewFolder,
@@ -249,13 +261,13 @@ export function MediaPool({
const folderPath = (rel: string) => (rel ? `${root}/${rel}` : root);
- const importFiles = async (list: File[]) => {
+ const importFiles = async (list: File[], intoRel = at) => {
if (!list.length) return;
setNotice(null);
setImporting({ count: list.length, ratio: 0 });
try {
- /* into the open folder: the top of assets/ unless the person went into one */
- await onImport(list, folderPath(at), (ratio) => setImporting({ count: list.length, ratio }));
+ /* into the open folder (the top of assets/ unless the person went into one), or the folder they were dropped on */
+ await onImport(list, folderPath(intoRel), (ratio) => setImporting({ count: list.length, ratio }));
} catch (e) {
setNotice(e instanceof Error && e.message ? e.message : t('assets.uploadFailed'));
} finally {
@@ -263,14 +275,23 @@ export function MediaPool({
}
};
- const moveInto = async (path: string, intoRel: string) => {
+ /* read when a move or rename settles: the file picked may have changed while it was on its way */
+ const selectedRef = React.useRef(selectedPath);
+ selectedRef.current = selectedPath;
+ /* a page (or a folder with one) whose code makes paths while it runs: those cannot be rewritten, so it is asked first */
+ const [moveAsk, setMoveAsk] = React.useState<{ path: string; intoRel: string; unseen: { file: string; unseen: string[] }[] } | null>(null);
+ const moveInto = async (path: string, intoRel: string, asked = false) => {
const into = folderPath(intoRel);
if (relDir(path) === into) return;
const name = path.slice(path.lastIndexOf('/') + 1);
+ if (!asked && onMoveCheck) {
+ const unseen = await onMoveCheck(path, `${into}/${name}`).catch(() => []);
+ if (unseen.length) { setMoveAsk({ path, intoRel, unseen }); return; }
+ }
const result = await onMove(path, `${into}/${name}`);
if (result === 'taken') setNotice(t('media.moveTaken').replace('{name}', name).replace('{folder}', intoRel ? intoRel.split('/').pop()! : t('media.filter_all')));
else if (result !== 'ok') setNotice(t('media.moveFailed'));
- else if (selectedPath === path) onSelectFile(null);
+ else if (selectedRef.current === path) onSelectFile(null);
};
const remove = async (target: { path: string; folder: boolean }) => {
@@ -298,13 +319,27 @@ export function MediaPool({
else if (selectedPath === path) onSelectFile(null);
};
+ /* a folder just named stays where it was typed until the listing has it: no blink between Enter and the refresh */
+ const [pendingFolder, setPendingFolder] = React.useState<string | null>(null);
const makeFolder = async (name: string) => {
setCreating(false);
const safe = safeName(name);
if (!safe) return;
+ setPendingFolder(safe);
const result = await onNewFolder(`${folderPath(at)}/${safe}`);
- if (result !== 'ok') setNotice(t(result === 'taken' ? 'assets.renameTaken' : 'assets.newFolderFailed'));
+ if (result !== 'ok') {
+ setPendingFolder(null);
+ setNotice(t(result === 'taken' ? 'assets.renameTaken' : 'assets.newFolderFailed'));
+ }
};
+ const pendingListed = pendingFolder != null && Boolean(items?.some((item) => item.type === 'folder' && item.name === pendingFolder));
+ React.useEffect(() => { if (pendingListed) setPendingFolder(null); }, [pendingListed]);
+ /* the listing never brought it (it was made elsewhere than shown): let go after a while */
+ React.useEffect(() => {
+ if (!pendingFolder) return undefined;
+ const timer = window.setTimeout(() => setPendingFolder(null), 5000);
+ return () => window.clearTimeout(timer);
+ }, [pendingFolder]);
const commonEntries = (path: string): ContextMenuEntry[] => [
...(onReveal ? [{ id: 'reveal', label: t('projects.revealFolder'), icon: <FolderOpen size={14} />, onSelect: () => onReveal(path) }] : []),
@@ -344,6 +379,7 @@ export function MediaPool({
const crumbs = at ? at.split('/') : [];
const flat = Boolean(query.trim()) || view.filter !== 'all';
+ const rows = view.layout === 'list';
/* results come from every folder: where a name shows more than once, each says which folder it is in */
const repeated = React.useMemo(() => {
const seen = new Map<string, number>();
@@ -353,17 +389,30 @@ export function MediaPool({
/* a tile dropped on a folder tile or a crumb moves there. Passing from one part of the tile to another is not
leaving it (the highlight would flicker) */
+ /* a folder takes what is dragged onto it: a file or folder of this pane (moved), or files from the computer (copied
+ in, there rather than into the folder open) */
const dropProps = (intoRel: string) => ({
- onDragOver: (e: React.DragEvent) => { if (e.dataTransfer.types.includes(FOLDER_DRAG)) { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'move'; setDropTarget(intoRel); } },
+ onDragOver: (e: React.DragEvent) => {
+ const inside = e.dataTransfer.types.includes(FOLDER_DRAG);
+ if (!inside && !fromComputer(e.dataTransfer)) return;
+ e.preventDefault(); e.stopPropagation();
+ e.dataTransfer.dropEffect = inside ? 'move' : 'copy';
+ setDropTarget(intoRel);
+ },
onDragLeave: (e: React.DragEvent) => {
if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
setDropTarget((cur) => (cur === intoRel ? null : cur));
},
onDrop: (e: React.DragEvent) => {
const path = e.dataTransfer.getData(FOLDER_DRAG);
- if (!path) return;
- e.preventDefault(); e.stopPropagation(); setDropTarget(null);
- void moveInto(path, intoRel);
+ if (path) {
+ e.preventDefault(); e.stopPropagation(); setDropTarget(null);
+ void moveInto(path, intoRel);
+ return;
+ }
+ if (!fromComputer(e.dataTransfer) || !e.dataTransfer.files.length) return;
+ e.preventDefault(); e.stopPropagation(); setDropTarget(null); setOsDrag(false);
+ void importFiles([...e.dataTransfer.files], intoRel);
},
});
@@ -395,12 +444,14 @@ export function MediaPool({
e.stopPropagation();
setConfirm({ path: file.path, name: file.name, folder: false });
}}
- onDragEnter={(e) => { if (e.dataTransfer.types.includes('Files')) { e.preventDefault(); setOsDrag(true); } }}
- onDragOver={(e) => { if (e.dataTransfer.types.includes('Files')) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; } }}
- onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setOsDrag(false); }}
+ /* files from the computer: a drag of this pane's own tiles is not one, whatever the browser adds to it (a picture
+ dragged carries itself as a file) */
+ onDragEnter={(e) => { if (fromComputer(e.dataTransfer)) { e.preventDefault(); setOsDrag(true); } }}
+ onDragOver={(e) => { if (fromComputer(e.dataTransfer)) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; } }}
+ onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) { setOsDrag(false); setDropTarget(null); } }}
onDrop={(e) => {
- if (!e.dataTransfer.files.length) return;
- e.preventDefault(); setOsDrag(false);
+ if (!fromComputer(e.dataTransfer) || !e.dataTransfer.files.length) return;
+ e.preventDefault(); setOsDrag(false); setDropTarget(null);
void importFiles([...e.dataTransfer.files]);
}}
>
@@ -419,6 +470,9 @@ export function MediaPool({
{t('media.upload')}
</button>
</Tooltip>
+ <BarButton label={t(rows ? 'media.viewGrid' : 'media.viewList')} onClick={() => setView((v) => ({ ...v, layout: rows ? 'grid' : 'list' }))}>
+ {rows ? <LayoutGrid size={14} /> : <List size={14} />}
+ </BarButton>
<BarButton label={t('media.filter')} on={view.filter !== 'all'} onClick={(e) => barMenu(e, FILTERS.map((f) => ({
id: f, label: `${t(`media.filter_${f}`)} ${counts[f]}`, checked: view.filter === f, onSelect: () => setView((v) => ({ ...v, filter: f })),
})))}><ListFilter size={14} /></BarButton>
@@ -478,7 +532,8 @@ export function MediaPool({
<div
ref={gridRef}
className="min-h-0 flex-1 overflow-y-auto px-2.5 pb-3 pt-1"
- onClick={(e) => { if (e.target === e.currentTarget) { setSelectedFolder(null); onSelectFile(null); } }}
+ /* a click on empty space (around the tiles, or in the gaps between them) lets go of what is selected */
+ onClick={(e) => { if (!(e.target as Element).closest('[data-media-path], [data-media-folder], [data-media-new-folder], button')) { setSelectedFolder(null); onSelectFile(null); } }}
onContextMenu={(e) => { if (e.target === e.currentTarget) { e.preventDefault(); openMenuAt(e, blankMenu); } }}
>
{items && !items.length && !creating ? (
@@ -494,12 +549,14 @@ export function MediaPool({
</div>
)
) : (
- <div className="grid gap-x-2 gap-y-2.5" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(104px, 1fr))' }}
+ <div className={rows ? 'flex flex-col gap-px' : 'grid gap-x-2 gap-y-2.5'} style={rows ? undefined : { gridTemplateColumns: 'repeat(auto-fill, minmax(104px, 1fr))' }}
onContextMenu={(e) => { if (e.target === e.currentTarget) { e.preventDefault(); openMenuAt(e, blankMenu); } }}>
- {creating ? <NewFolderTile label={t('assets.newFolder')} onDone={(name) => void makeFolder(name)} onCancel={() => setCreating(false)} /> : null}
+ {creating ? <NewFolderTile row={rows} label={t('assets.newFolder')} onDone={(name) => void makeFolder(name)} onCancel={() => setCreating(false)} /> : null}
+ {pendingFolder && !pendingListed ? <NewFolderTile row={rows} label={pendingFolder} /> : null}
{(items ?? []).map((item) => item.type === 'folder' ? (
<FolderTile
key={`d:${item.rel}`}
+ row={rows}
name={item.name}
count={item.count}
covers={item.covers}
@@ -518,6 +575,7 @@ export function MediaPool({
) : (
<FileTile
key={item.file.path}
+ row={rows}
file={item.file}
sources={sources}
duration={formatClipDuration(item.file.durationMs ?? 0)}
@@ -537,12 +595,22 @@ export function MediaPool({
)}
</div>
- {osDrag ? (
+ {/* over a folder, the folder shows where they go */}
+ {osDrag && dropTarget == null ? (
<div className="pointer-events-none absolute inset-1 z-30 flex items-center justify-center rounded-lg border-2 border-dashed border-[var(--accent)] bg-[var(--surface)]/80 text-[13px] text-[var(--text)]">
{t('media.dropHint')}
</div>
) : null}
{menu ? <ContextMenu x={menu.x} y={menu.y} flipTo={menu.flipTo} items={menu.items} onClose={() => setMenu(null)} dense={menu.dense} /> : null}
+ <ConfirmDialog
+ open={moveAsk != null}
+ title={t('media.moveAskTitle')}
+ description={moveAsk ? `${t('media.moveAskBody')}\n\n${moveAsk.unseen.flatMap((u) => u.unseen.map((line) => `${u.file}: ${line}`)).slice(0, 6).join('\n')}` : ''}
+ confirmLabel={t('media.moveAskConfirm')}
+ cancelLabel={t('confirm.cancel')}
+ onCancel={() => setMoveAsk(null)}
+ onConfirm={() => { const ask = moveAsk; setMoveAsk(null); if (ask) void moveInto(ask.path, ask.intoRel, true); }}
+ />
<ConfirmDialog
open={confirm != null}
title={confirm?.folder ? t('media.deleteFolderTitle').replace('{name}', confirm.name) : t('assets.deleteConfirmTitle')}
@@ -589,6 +657,9 @@ function NameInput({ value, onDone, onCancel }: { value: string; onDone: (name:
}
const TILE_BOX = 'relative aspect-video overflow-hidden rounded-md ring-2 transition';
+/** A row of the list view, and its small picture. */
+const ROW = 'group flex h-9 min-w-0 cursor-default select-none items-center gap-2 rounded-md px-1.5';
+const ROW_THUMB = 'relative aspect-video h-[26px] shrink-0 overflow-hidden rounded-[4px] bg-[var(--bg-hover)] ring-1 ring-[var(--border)]';
/** Whether a file can be a clip (a video, a still, a sound, a page; not a document). */
const canAdd = (file: WorkspaceResource) => file.kind === 'video' || file.kind === 'image' || file.kind === 'audio' || file.kind === 'mg';
@@ -619,12 +690,32 @@ function FolderTile(p: {
onDragStart: (e: React.DragEvent) => void;
onPress: () => void; onOpen: () => void; onMenu: (e: React.MouseEvent) => void;
onRename: (name: string) => void; onCancelRename: () => void;
+ /** A row of the list view, not a tile. */
+ row?: boolean;
}) {
const on = p.target || p.selected;
const cells = p.covers.length;
+ if (p.row) {
+ return (
+ <div className={`${ROW} ${on ? 'bg-[var(--bg-active)]' : 'hover:bg-[var(--bg-hover)]'} ${p.target ? 'ring-1 ring-inset ring-[var(--accent)]' : ''}`}
+ data-media-folder="" draggable={!p.renaming} onDragStart={p.onDragStart}
+ onClick={p.onPress} onDoubleClick={p.onOpen} onContextMenu={(e) => { e.preventDefault(); e.stopPropagation(); p.onMenu(e); }} {...p.drop}>
+ <span className={ROW_THUMB}>
+ <span className="pointer-events-none absolute inset-0 flex items-center justify-center">
+ {p.target ? <FolderOpen size={15} className="text-[var(--accent)]" /> : <Folder size={15} className="text-[var(--text-muted)]" />}
+ </span>
+ </span>
+ <span className="min-w-0 flex-1">
+ {p.renaming ? <NameInput value={p.name} onDone={p.onRename} onCancel={p.onCancelRename} />
+ : <span className={`block truncate text-[12.5px] font-medium ${on ? 'text-[var(--text)]' : 'text-[var(--text-dim)]'}`} style={KEEP_SPACES}>{p.name}</span>}
+ </span>
+ <span className="shrink-0 pr-1 text-[11px] tabular-nums text-[var(--text-faint)]">{p.count ? String(p.count) : ''}</span>
+ </div>
+ );
+ }
const grid = cells >= 4 ? 'grid-cols-2 grid-rows-2' : cells === 3 ? 'grid-cols-2 grid-rows-2' : cells === 2 ? 'grid-cols-2 grid-rows-1' : 'grid-cols-1 grid-rows-1';
return (
- <div className="group min-w-0 cursor-default select-none" draggable={!p.renaming} onDragStart={p.onDragStart}
+ <div className="group min-w-0 cursor-default select-none" data-media-folder="" draggable={!p.renaming} onDragStart={p.onDragStart}
onClick={p.onPress} onDoubleClick={p.onOpen} onContextMenu={(e) => { e.preventDefault(); e.stopPropagation(); p.onMenu(e); }} {...p.drop}>
<div className="relative pt-[7px]">
{/* the stack: two cards peeking out above the cover */}
@@ -632,7 +723,7 @@ function FolderTile(p: {
<span aria-hidden className="absolute inset-x-[7%] top-[3px] h-3 rounded-t-md bg-[var(--fill-tsp,rgba(127,127,127,0.18))]" />
<div className={`${TILE_BOX} bg-[var(--bg-hover)] shadow-[0_1px_0_rgba(255,255,255,0.06)_inset] ${on ? 'ring-[var(--accent)]' : 'ring-transparent group-hover:ring-[var(--border)]'} ${p.target ? 'scale-[1.03]' : ''}`}>
{cells ? (
- <div className={`absolute inset-0 grid gap-px bg-black/40 ${grid}`}>
+ <div className={`pointer-events-none absolute inset-0 grid gap-px bg-black/40 ${grid}`}>
{p.covers.map((file, i) => (
<span key={file.path} className={`relative overflow-hidden bg-[var(--bg-hover)] ${cells === 3 && i === 0 ? 'row-span-2' : ''}`}>
<MediaPreview file={file} sources={p.sources} />
@@ -655,15 +746,32 @@ function FolderTile(p: {
);
}
-function NewFolderTile({ label, onDone, onCancel }: { label: string; onDone: (name: string) => void; onCancel: () => void }) {
+/** The folder being named; without `onDone`, one just named and on its way (its name, not a field). */
+function NewFolderTile({ label, onDone, onCancel, row = false }: { label: string; onDone?: (name: string) => void; onCancel?: () => void; row?: boolean }) {
+ if (row) {
+ return (
+ <div className={`${ROW} bg-[var(--bg-hover)]`} data-media-new-folder="">
+ <span className={`${ROW_THUMB} ring-[var(--accent)]`}>
+ <span className="pointer-events-none absolute inset-0 flex items-center justify-center"><Folder size={15} className="text-[var(--text-muted)]" /></span>
+ </span>
+ <span className="min-w-0 flex-1">
+ {onDone ? <NameInput value={label} onDone={onDone} onCancel={onCancel ?? (() => {})} />
+ : <span className="block truncate text-[12.5px] font-medium text-[var(--text)]" style={KEEP_SPACES}>{label}</span>}
+ </span>
+ </div>
+ );
+ }
return (
- <div className="min-w-0">
+ <div className="min-w-0" data-media-new-folder="">
<div className="relative pt-[7px]">
<span aria-hidden className="absolute inset-x-[14%] top-0 h-3 rounded-t-md bg-[var(--fill-tsp,rgba(127,127,127,0.18))] opacity-60" />
<span aria-hidden className="absolute inset-x-[7%] top-[3px] h-3 rounded-t-md bg-[var(--fill-tsp,rgba(127,127,127,0.18))]" />
<div className={`${TILE_BOX} bg-[var(--bg-hover)] ring-[var(--accent)]`}><FolderGlyph /></div>
</div>
- <div className="mt-1 min-w-0 px-0.5"><NameInput value={label} onDone={onDone} onCancel={onCancel} /></div>
+ <div className="mt-1 min-w-0 px-0.5">
+ {onDone ? <NameInput value={label} onDone={onDone} onCancel={onCancel ?? (() => {})} />
+ : <div className="truncate text-[12px] font-medium text-[var(--text)]" style={KEEP_SPACES}>{label}</div>}
+ </div>
</div>
);
}
@@ -681,20 +789,41 @@ function FileTile(p: {
/** The "+": the file put on the timeline. */
onAdd?: () => void;
addLabel?: string;
+ /** A row of the list view, not a tile. */
+ row?: boolean;
}) {
+ const add = p.onAdd ? (
+ <Tooltip label={p.addLabel ?? ''} shortcut="Enter">
+ <button
+ type="button"
+ data-media-add=""
+ aria-label={p.addLabel}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={(e) => { e.stopPropagation(); p.onPress(); p.onAdd!(); }}
+ className={p.row
+ ? `flex h-6 w-6 shrink-0 items-center justify-center rounded text-[var(--text-muted)] transition hover:bg-[var(--accent)] hover:text-white ${p.selected ? 'opacity-100' : 'opacity-0 focus-visible:opacity-100 group-hover:opacity-100'}`
+ : `absolute left-1 top-1 z-10 flex h-5 w-5 items-center justify-center rounded bg-black/65 text-white transition hover:bg-[var(--accent)] ${p.selected ? 'opacity-100' : 'opacity-0 focus-visible:opacity-100 group-hover:opacity-100'}`}
+ >
+ <Plus size={13} strokeWidth={2.4} />
+ </button>
+ </Tooltip>
+ ) : null;
return (
<div
- className="group min-w-0 cursor-default select-none outline-none"
+ className={p.row
+ ? `${ROW} outline-none ${p.lit ? 'ring-1 ring-inset ring-[var(--tl-accent)]' : ''} ${p.selected ? 'bg-[var(--bg-active)]' : 'hover:bg-[var(--bg-hover)]'}`
+ : 'group min-w-0 cursor-default select-none outline-none'}
data-media-path={p.file.path}
data-chat-lit={p.lit ? '' : undefined}
title={p.where ? p.file.path : p.file.name}
draggable={!p.renaming}
+ /* a drag picks nothing: picking opens the inspector, and the pane laid out again under the pointer (or hidden for
+ room) would lose the drag */
onDragStart={(e) => {
- p.onPress();
setResourceDragData(e.dataTransfer, p.file);
if (p.studioRef) e.dataTransfer.setData(STUDIO_REF_TYPE, JSON.stringify([p.studioRef()]));
- /* web pages stay where their code is; assets can also go into a folder of this pane */
- if (p.file.kind !== 'mg') e.dataTransfer.setData(FOLDER_DRAG, p.file.path);
+ /* any file can go into a folder of this pane: a page's links are written again as it moves (Studio) */
+ e.dataTransfer.setData(FOLDER_DRAG, p.file.path);
e.dataTransfer.effectAllowed = 'copyMove';
}}
onDragEnd={() => clearResourceDrag()}
@@ -703,25 +832,26 @@ function FileTile(p: {
onClick={(e) => { e.currentTarget.focus({ preventScroll: true }); p.onPress(); }}
onContextMenu={(e) => { e.preventDefault(); e.stopPropagation(); p.onMenu(e); }}
>
+ {p.row ? (
+ <>
+ <span className={`${ROW_THUMB} pointer-events-none`}>
+ {p.file.kind === 'mg' ? <PagePoster file={p.file} sources={p.sources} /> : <MediaPreview file={p.file} sources={p.sources} />}
+ </span>
+ <span className="min-w-0 flex-1">
+ {p.renaming ? <NameInput value={p.file.name} onDone={p.onRename} onCancel={p.onCancelRename} />
+ : <span className={`block truncate text-[12.5px] ${p.selected ? 'text-[var(--text)]' : 'text-[var(--text-dim)]'}`} style={KEEP_SPACES}>{p.file.name}</span>}
+ {p.where ? <span className="block truncate text-left text-[11px] text-[var(--text-faint)]" dir="rtl"><bdi>{p.where}</bdi></span> : null}
+ </span>
+ {p.duration ? <span className="shrink-0 text-[11px] tabular-nums text-[var(--text-faint)]">{p.duration}</span> : null}
+ {add}
+ </>
+ ) : <>
{/* the same room above as a folder's stacked cards, so covers and names line up across a row */}
<div className="pt-[7px]">
<div className={`${TILE_BOX} bg-[var(--bg-hover)] ${p.lit ? 'ring-[var(--tl-accent)] shadow-[0_0_10px_1px_color-mix(in_srgb,var(--tl-accent)_55%,transparent)]' : p.selected ? 'ring-[var(--accent)]' : 'ring-transparent group-hover:ring-[var(--border)]'}`}>
{p.file.kind === 'mg' ? <PagePoster file={p.file} sources={p.sources} /> : <MediaPreview file={p.file} sources={p.sources} />}
{/* "+": on the timeline at the playhead (or the main track's end), without dragging it there */}
- {p.onAdd ? (
- <Tooltip label={p.addLabel ?? ''} shortcut="Enter">
- <button
- type="button"
- data-media-add=""
- aria-label={p.addLabel}
- onMouseDown={(e) => e.preventDefault()}
- onClick={(e) => { e.stopPropagation(); p.onPress(); p.onAdd!(); }}
- className={`absolute left-1 top-1 z-10 flex h-5 w-5 items-center justify-center rounded bg-black/65 text-white transition hover:bg-[var(--accent)] ${p.selected ? 'opacity-100' : 'opacity-0 focus-visible:opacity-100 group-hover:opacity-100'}`}
- >
- <Plus size={13} strokeWidth={2.4} />
- </button>
- </Tooltip>
- ) : null}
+ {add}
{p.duration ? <span className="absolute bottom-1 right-1 z-10 rounded bg-black/65 px-1 text-[10.5px] tabular-nums leading-[16px] text-white">{p.duration}</span> : null}
</div>
</div>
@@ -730,6 +860,7 @@ function FileTile(p: {
: <div className={`truncate text-[12px] ${p.selected ? 'text-[var(--text)]' : 'text-[var(--text-dim)]'}`} style={KEEP_SPACES}>{p.file.name}</div>}
{p.where ? <div className="truncate text-left text-[11px] text-[var(--text-faint)]" dir="rtl"><bdi>{p.where}</bdi></div> : null}
</div>
+ </>}
</div>
);
}
diff --git a/packages/openfilm/studio/ui/src/components/MenuSelect.tsx b/packages/openfilm/studio/ui/src/components/MenuSelect.tsx
index cc40273..6da980a 100644
--- a/packages/openfilm/studio/ui/src/components/MenuSelect.tsx
+++ b/packages/openfilm/studio/ui/src/components/MenuSelect.tsx
@@ -12,7 +12,7 @@ export type MenuChoice = { value: string; label: string };
export type MenuGroup = { label?: string; choices: MenuChoice[] };
export function MenuSelect({
- label, value, groups, onPick, disabled = false, className = '',
+ label, value, groups, onPick, disabled = false, className = '', size = 'sm',
}: {
/** what it chooses, for screen readers (the field shows the choice) */
label: string;
@@ -21,6 +21,8 @@ export function MenuSelect({
onPick: (value: string) => void;
disabled?: boolean;
className?: string;
+ /** `sm`: the inspector's fields; `md`: a dialog's (the export's) */
+ size?: 'sm' | 'md';
}) {
const [open, setOpen] = React.useState(false);
const [width, setWidth] = React.useState(0);
@@ -38,7 +40,14 @@ export function MenuSelect({
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps
React.useEffect(() => {
if (!open || active < 0) return;
- listRef.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: 'nearest' });
+ /* the list's own scroll only: scrollIntoView would also scroll what the field is in (a dialog's body) */
+ const list = listRef.current;
+ const item = list?.querySelector<HTMLElement>(`[data-index="${active}"]`);
+ if (!list || !item) return;
+ const top = item.offsetTop;
+ const bottom = top + item.offsetHeight;
+ if (top < list.scrollTop) list.scrollTop = top;
+ else if (bottom > list.scrollTop + list.clientHeight) list.scrollTop = bottom - list.clientHeight;
}, [open, active]);
const pick = (choice: MenuChoice) => {
@@ -73,7 +82,7 @@ export function MenuSelect({
/* the popover keeps focus where it was on a press: the keys need it here */
onClick={(e) => e.currentTarget.focus()}
onKeyDown={onKeyDown}
- className={`flex h-7 min-w-0 flex-1 items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--fill-tsp)] pl-2 pr-1.5 text-left text-[11px] text-[var(--text)] outline-none transition hover:border-[var(--text-faint)] focus-visible:border-[var(--accent)] disabled:opacity-50 ${open ? 'border-[var(--accent)]' : ''} ${className}`}
+ className={`flex min-w-0 flex-1 items-center gap-1.5 border border-[var(--border)] bg-[var(--fill-tsp)] text-left text-[var(--text)] ${size === 'md' ? 'h-9 rounded-lg pl-3 pr-2 text-[13px]' : 'h-7 rounded-md pl-2 pr-1.5 text-[11px]'} outline-none transition hover:border-[var(--text-faint)] focus-visible:border-[var(--accent)] disabled:opacity-50 ${open ? 'border-[var(--accent)]' : ''} ${className}`}
>
<span className="min-w-0 flex-1 truncate">{current?.label ?? value}</span>
<ChevronDown size={12} aria-hidden className={`shrink-0 text-[var(--text-faint)] transition-transform ${open ? 'rotate-180' : ''}`} />
@@ -85,7 +94,7 @@ export function MenuSelect({
role="listbox"
aria-label={label}
onKeyDown={onKeyDown}
- className="overflow-y-auto rounded-[8px] border border-[var(--border)] bg-[var(--panel)] p-1 shadow-[var(--shadow-lg)]"
+ 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))' }}
>
{groups.map((group, g) => (
@@ -109,7 +118,7 @@ export function MenuSelect({
onMouseEnter={() => setActive(i)}
onMouseDown={(e) => e.preventDefault()}
onClick={() => pick(choice)}
- className={`flex h-7 w-full items-center gap-2 rounded-[5px] px-2 text-left text-[11.5px] text-[var(--text)] ${i === active ? 'bg-[var(--bg-hover)]' : ''}`}
+ className={`flex w-full items-center gap-2 rounded-[5px] px-2 text-left text-[var(--text)] ${size === 'md' ? 'h-8 text-[13px]' : 'h-7 text-[11.5px]'} ${i === active ? 'bg-[var(--bg-hover)]' : ''}`}
>
<span className="min-w-0 flex-1 truncate">{choice.label}</span>
{chosen ? <Check size={12} aria-hidden className="shrink-0 text-[var(--accent)]" /> : null}
diff --git a/packages/openfilm/studio/ui/src/components/ProjectSources.tsx b/packages/openfilm/studio/ui/src/components/ProjectSources.tsx
index 2dfb0eb..7655b6b 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectSources.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectSources.tsx
@@ -387,11 +387,14 @@ export function ExamplesSection({
collapsed,
onToggle,
onOpen,
+ view = 'cards',
}: {
examples: Example[];
collapsed: boolean;
onToggle: () => void;
onOpen: (example: Example) => void;
+ /** As the projects above are shown: cards, or rows. */
+ view?: 'cards' | 'list';
}) {
const t = useT();
if (!examples.length) return null;
@@ -408,7 +411,11 @@ export function ExamplesSection({
{t('projects.examples.title')}
<span className="ml-1 text-[12px] font-normal tabular-nums text-[var(--text-faint)]">{examples.length}</span>
</button>
- {collapsed ? null : (
+ {collapsed ? null : view === 'list' ? (
+ <div className="mt-1 flex flex-col divide-y divide-[var(--border)]">
+ {examples.map((example) => <ExampleListRow key={example.id} example={example} onOpen={() => onOpen(example)} />)}
+ </div>
+ ) : (
<div className="mt-3 grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-4">
{examples.map((example) => <ExampleCard key={example.id} example={example} onOpen={() => onOpen(example)} />)}
</div>
@@ -417,9 +424,59 @@ export function ExamplesSection({
);
}
+/** An example's poster, faded in once loaded; a clapperboard when it has none or it does not load. */
+function ExamplePoster({ example }: { example: Example }) {
+ const [poster, setPoster] = React.useState<'loading' | 'ready' | 'failed'>(example.poster ? 'loading' : 'failed');
+ return poster === 'failed' ? (
+ <span className="absolute inset-0 flex items-center justify-center text-[var(--text-faint)]"><Clapperboard size={22} strokeWidth={1.5} /></span>
+ ) : (
+ <img
+ src={example.poster ?? undefined}
+ alt=""
+ loading="lazy"
+ draggable={false}
+ onLoad={() => setPoster('ready')}
+ onError={() => setPoster('failed')}
+ className={`absolute inset-0 h-full w-full object-cover transition-opacity duration-200 ${poster === 'ready' ? 'opacity-100' : 'opacity-0'}`}
+ />
+ );
+}
+
+/** An example in the list view: the projects' row, its description where a project's path would be. */
+function ExampleListRow({ example, onOpen }: { example: Example; onOpen: () => void }) {
+ const t = useT();
+ return (
+ <article className="group min-w-0">
+ <button
+ type="button"
+ onClick={onOpen}
+ aria-label={`${t('projects.examples.open')} · ${example.title}`}
+ className="flex w-full min-w-0 items-center gap-3 py-4 text-left sm:gap-4"
+ >
+ <span className="relative block aspect-video w-28 shrink-0 overflow-hidden rounded-md bg-[var(--surface-2)] ring-1 ring-[var(--border)] transition group-hover:brightness-[1.04] sm:w-36">
+ <ExamplePoster example={example} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[14px] font-semibold text-[var(--text)]">{example.title}</span>
+ {example.description ? <span className="mt-1 line-clamp-2 block text-[12.5px] leading-relaxed text-[var(--text-muted)]">{example.description}</span> : null}
+ {example.duration ? (
+ <span className="mt-2 flex items-center gap-1 text-[11.5px] tabular-nums text-[var(--text-faint)]">
+ <Clock3 size={11} />
+ {formatSeconds(example.duration)}
+ </span>
+ ) : null}
+ </span>
+ <span className="flex shrink-0 items-center gap-1.5 rounded-full px-3 py-1 text-[12px] font-medium text-[var(--text-muted)] opacity-0 transition group-hover:bg-[var(--bg-hover)] group-hover:text-[var(--text)] group-hover:opacity-100 group-focus-within:opacity-100">
+ <FolderOpen size={13} />
+ {t('projects.examples.open')}
+ </span>
+ </button>
+ </article>
+ );
+}
+
function ExampleCard({ example, onOpen }: { example: Example; onOpen: () => void }) {
const t = useT();
- const [poster, setPoster] = React.useState<'loading' | 'ready' | 'failed'>(example.poster ? 'loading' : 'failed');
return (
<article className="group min-w-0">
<button
@@ -428,19 +485,7 @@ function ExampleCard({ example, onOpen }: { example: Example; onOpen: () => void
aria-label={`${t('projects.examples.open')} · ${example.title}`}
className="relative block aspect-video w-full overflow-hidden rounded-lg bg-[var(--surface-2)] ring-1 ring-[var(--border)] transition hover:brightness-[1.04]"
>
- {poster === 'failed' ? (
- <span className="absolute inset-0 flex items-center justify-center text-[var(--text-faint)]"><Clapperboard size={22} strokeWidth={1.5} /></span>
- ) : (
- <img
- src={example.poster ?? undefined}
- alt=""
- loading="lazy"
- draggable={false}
- onLoad={() => setPoster('ready')}
- onError={() => setPoster('failed')}
- className={`absolute inset-0 h-full w-full object-cover transition-opacity duration-200 ${poster === 'ready' ? 'opacity-100' : 'opacity-0'}`}
- />
- )}
+ <ExamplePoster example={example} />
{example.duration ? (
<span className="absolute bottom-2 right-2 flex items-center gap-1 rounded bg-black/40 px-1.5 py-0.5 text-[10.5px] font-medium tabular-nums text-white/85 backdrop-blur-sm">
<Clock3 size={10} />
diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
index a61c351..63a5c06 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
@@ -15,7 +15,7 @@ import { Player } from '@/editor/player';
import { Preview, type FilmInfo, type PreviewHandle } from '@/editor/Preview';
import { filmShape, type MediaFacts } from '@/lib/film-shape';
import { layoutTracks, type TimelineBlock, type TimelineTrack } from '@/lib/timeline-layout';
-import { filmClipKind, filmSrcIsPage, filmTrackBadges, parseFilmDocLoc, type FilmDoc } from '@/lib/film';
+import { filmClipKind, filmSrcIsPage, filmSrcKind, filmTrackBadges, parseFilmDocLoc, type FilmBox, type FilmDoc } from '@/lib/film';
import { footageFps, secondFrames, setTimecodeFps, snapToFrame, stepFrames } from '@/lib/timecode';
import { keyCommandOf, loopBack, playStart, shuttleRate } from '@/lib/timeline-keys';
import { cutPoints, namedTrack, nextCut, trackNamesOf } from '@/lib/timeline-nav';
@@ -39,7 +39,8 @@ import { ladderStepMs, THUMB_CELL_PX, thumbAnchorTimes } from '@/lib/thumb-cache
import { clipThumbId } from '@/lib/thumb-frame';
import { useLoadedThumbs } from '@/lib/use-loaded-thumbs';
import { droppedOverrides, overrideTarget, undoneFields, type DroppedEdits, type PersonEdit } from '@/lib/dropped-overrides';
-import { filmFrameBox, filmFrameOf, type FilmFrameId } from '@/lib/film-frame';
+import { filmFrameBox, type FilmFrameId } from '@/lib/film-frame';
+import { canvasFor, fitToCanvas } from '@/lib/canvas-fit';
import { factsOfProbe, mediaListingOf, resourceKindOf, srcHitsAsset, warmProjectMedia, type MediaListing, type MediaResult, type MediaSources, type WorkspaceResource } from '@/lib/workspace-resources';
import { BrandLoadingScreen } from './BrandLoadingScreen';
import { BrandLogo } from './BrandLogo';
@@ -76,7 +77,7 @@ import { ProjectMenu } from './ProjectMenu';
import { ProjectHistoryButton, ProjectHistoryControls } from './ProjectHistoryControls';
import { useProjectHistory } from './use-project-history';
import { ProjectsPopover } from './ProjectsLibrary';
-import { FramePicker, useDeliveryFrame } from './FramePicker';
+import { FramePicker } from './FramePicker';
import { FilmFullscreenBar, useFullscreenKeys } from './FilmFullscreenBar';
import { ViewerBar } from './ViewerBar';
import { LiveTime, type PlaybackClock } from './LiveTime';
@@ -527,8 +528,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {
const timelineCommands = React.useRef<TimelineCommands | null>(null);
/**
* The picture has the keyboard (the last press was on it; the inspector and the picture's own bars and menus keep
- * it): the arrow keys move what is in hand there. Anywhere else they move the playhead. Shown by a ring round the
- * picture while something is in hand.
+ * it): the arrow keys move what is in hand there. Anywhere else they move the playhead. The frame round what is in
+ * hand is the only mark: a ring round the whole picture read as the picture being selected.
*/
const [viewerFocus, setViewerFocus] = React.useState(false);
React.useEffect(() => {
@@ -980,6 +981,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onSelectFile={pickMedia}
onImport={onImport}
onMove={onMove}
+ onMoveCheck={onMoveCheck}
onDelete={onDelete}
onExtractAudio={onExtractAudio}
onNewFolder={onNewFolder}
@@ -1670,6 +1672,11 @@ export function ProjectView({ projectId, onProject, onLeave }: {
const onMove = React.useCallback(async (from: string, to: string) => mediaResult(await fetch(`${projectApi}/files`, {
method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ from, to }),
})), [projectApi]);
+ const onMoveCheck = React.useCallback(async (from: string, to: string) => {
+ const res = await fetch(`${projectApi}/files`, { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ from, to, check: true }) });
+ const body = await res.json().catch(() => ({})) as { unseen?: { file: string; unseen: string[] }[] };
+ return res.ok ? body.unseen ?? [] : [];
+ }, [projectApi]);
const onDelete = React.useCallback(async (path: string) => mediaResult(await fetch(`${projectApi}/files?path=${encodeURIComponent(path)}`, { method: 'DELETE' })), [projectApi]);
const onExtractAudio = React.useCallback(async (path: string) => mediaResult(await fetch(`${projectApi}/files/audio`, {
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path }),
@@ -1684,16 +1691,42 @@ export function ProjectView({ projectId, onProject, onLeave }: {
/* ── picture: the delivery frame, fullscreen ── */
const stage = film.film?.stage ?? { w: 1920, h: 1080 };
stageRef.current = stage;
- const [deliveryFrame, setDeliveryFrame] = useDeliveryFrame(projectId);
const empty = !film.film?.tracks.some((tr) => tr.clips.length);
- const frame: FilmFrameId = empty ? filmFrameOf(stage) : deliveryFrame;
- const frameBox = React.useMemo(() => filmFrameBox(stage, empty ? 'native' : frame), [stage, empty, frame]);
- /* the stage's shape: while nothing is made it is the film's own (written to film.html), after that the frame it is
- delivered in; the viewer's picker and the inspector's film panel both change it this way */
- const changeCanvas = React.useCallback((next: FilmFrameId, size: { w: number; h: number }) => {
- if (!empty) { setDeliveryFrame(next); return; }
- void edit([{ op: 'stage', w: size.w, h: size.h }], 'history.stepEdit');
- }, [empty, edit, setDeliveryFrame]);
+ /* the picture is the canvas, nothing around it: another shape is another canvas (a delivery frame is the export's) */
+ const frameBox = React.useMemo(() => filmFrameBox(stage, 'native'), [stage]);
+ /* the canvas (the stage in film.html), from the viewer's ratio button or the inspector, as CapCut's: another shape
+ keeps the canvas's short side (canvasFor; a typed size is that size), and every picture on it is scaled by one
+ factor into the new canvas, centered, in the same edit (one undo). Laying the film out again for the new canvas
+ is the agent's (the inspector gives the words) */
+ /* "Fit (original)": the shape of the film's first picture (the earliest on the film whose size the preview knows) */
+ const originalSize = React.useMemo(() => {
+ const sized = new Map(spans.filter((span) => span.w && span.h).map((span) => [span.id, { w: span.w!, h: span.h! }]));
+ const first = (film.film?.tracks ?? []).flatMap((track) => track.clips)
+ .filter((clip) => !clip.sound && filmSrcKind(clip.src) !== 'sound' && sized.has(clip.id))
+ .sort((a, b) => (a.at ?? 0) - (b.at ?? 0))[0];
+ return first ? sized.get(first.id) ?? null : null;
+ }, [spans, film.film]);
+ const changeCanvas = React.useCallback((next: FilmFrameId, given?: { w: number; h: number }) => {
+ const size = given ?? canvasFor(stage, next);
+ if (size.w === stage.w && size.h === stage.h) return;
+ const own = new Map(spans.map((span) => [span.id, span.w && span.h ? { w: span.w, h: span.h } : null]));
+ const reflows = new Set(spans.filter((span) => span.reflows).map((span) => span.id));
+ const clips = (film.film?.tracks ?? []).flatMap((track) => track.clips.map((clip) => ({
+ id: clip.id,
+ kind: clip.sound ? 'sound' as const : filmSrcKind(clip.src),
+ own: own.get(clip.id) ?? null,
+ box: (clip.box as FilmBox | undefined) ?? null,
+ reflows: reflows.has(clip.id),
+ size: clip.size ?? null,
+ })));
+ void edit([
+ { op: 'stage', w: size.w, h: size.h },
+ ...fitToCanvas(clips, stage, size).flatMap((fit) => [
+ { op: 'set' as const, clip: fit.id, field: 'box', value: fit.box },
+ ...(fit.size ? [{ op: 'set' as const, clip: fit.id, field: 'size', value: fit.size }] : []),
+ ]),
+ ], 'history.stepEdit');
+ }, [edit, stage, spans, film.film]);
const stageFullRef = React.useRef<HTMLDivElement>(null);
const [fullscreen, setFullscreen] = React.useState(false);
React.useEffect(() => {
@@ -2179,10 +2212,6 @@ export function ProjectView({ projectId, onProject, onLeave }: {
) : null}
<div className="relative flex min-h-0 flex-1 items-center justify-center px-3 py-2.5" style={{ containerType: 'size' }} {...pictureDropProps}
data-viewer-picture="" data-viewer-focus={viewerFocus ? '1' : '0'} onPointerDownCapture={() => setBarAt('stage')}>
- {/* the picture has the keyboard and something is in hand: the arrow keys move it (not the playhead) */}
- {viewerFocus && stageElement && !fullscreen ? (
- <div aria-hidden data-viewer-keys="" className="pointer-events-none absolute inset-1 z-[25] rounded-md ring-1 ring-inset ring-[color-mix(in_srgb,var(--accent)_70%,transparent)]" />
- ) : null}
{pictureDrop ? (
<div className="pointer-events-none absolute inset-2 z-30 flex items-center justify-center rounded-lg bg-[color-mix(in_srgb,var(--accent)_10%,transparent)] ring-2 ring-inset ring-[var(--accent)]">
<span className="rounded-md bg-[var(--surface)] px-2.5 py-1 text-[12.5px] text-[var(--text)] shadow-sm">{t('project.dropOnPicture')}</span>
@@ -2292,13 +2321,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onPlayPause={toggle}
loop={{ on: loop, ranged: Boolean(markedRange), onToggle: () => setLoop((on) => !on) }}
frame={value ? (
- <FramePicker
- stage={stage}
- value={deliveryFrame}
- mode={empty ? 'canvas' : 'delivery'}
- onDelivery={setDeliveryFrame}
- onCanvas={changeCanvas}
- />
+ <FramePicker stage={stage} original={originalSize} onCanvas={changeCanvas} />
) : null}
onFullscreen={toggleFullscreen}
/>
@@ -2342,7 +2365,6 @@ export function ProjectView({ projectId, onProject, onLeave }: {
stage={stage}
film={filmSummary}
onCanvas={changeCanvas}
- frame={{ value: deliveryFrame, onChange: setDeliveryFrame }}
onEditLayers={editStageOverrides}
locked={inspectorLocked}
rate={frameRate}
@@ -2451,7 +2473,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
title={title || 'video'}
durationMs={totalMs}
stage={stage}
- frame={frame}
+ frame="native"
film={exportFilm as never}
playheadMs={timeMs}
mgBlocks={mgBlocks}
diff --git a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
index 17833be..d40f5c7 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
@@ -19,7 +19,7 @@ import { createPortal } from 'react-dom';
import { Loader2 } from 'lucide-react';
import { api, ApiError } from '@/api';
import { useT } from '@/i18n';
-import { folderApi, type ProjectFolder } from '@/lib/project-folders';
+import { folderApi, folderCounts, folderTrail, type ProjectFolder } from '@/lib/project-folders';
import { studioHost } from '@/lib/host';
import { SourceError, examplesCollapsed, setExamplesCollapsed, sourcesApi, type Example } from '@/lib/project-sources';
import { ConfirmDialog } from './ConfirmDialog';
@@ -100,9 +100,9 @@ function useProjectLibrary(open: boolean) {
return new Set(ids.filter((id) => !gone.has(id)));
}
- async function createFolder(name: string): Promise<ProjectFolder | null> {
+ async function createFolder(name: string, parentId: string | null = null): Promise<ProjectFolder | null> {
try {
- const folder = await folderApi.create(name);
+ const folder = await folderApi.create(name, parentId);
setFolders((list) => [...list, folder]);
return folder;
} catch {
@@ -128,7 +128,9 @@ function useProjectLibrary(open: boolean) {
* deleted as one is (its folder to the Trash). A project that fails stays, at the top level. Returns the ids deleted.
*/
async function deleteFolder(folder: ProjectFolder): Promise<Set<string>> {
- setFolders((list) => list.filter((f) => f.id !== folder.id));
+ /* the folders inside it go with it */
+ const gone = new Set([folder.id, ...folders.filter((f) => folderTrail(folders, f.id).some((up) => up.id === folder.id)).map((f) => f.id)]);
+ setFolders((list) => list.filter((f) => !gone.has(f.id)));
let inside: string[];
try {
inside = await folderApi.remove(folder.id);
@@ -137,7 +139,7 @@ function useProjectLibrary(open: boolean) {
reloadFolders();
return new Set();
}
- setProjects((list) => list.map((p) => (p.folderId === folder.id ? { ...p, folderId: undefined } : p)));
+ setProjects((list) => list.map((p) => (p.folderId && gone.has(p.folderId) ? { ...p, folderId: undefined } : p)));
return deleteProjects(inside);
}
@@ -320,7 +322,8 @@ export function ProjectsPopover({
const deleteDesc = !pendingDelete ? ''
: onlyMissing ? t('projects.removeDesc')
: `${t(pendingDelete.length > 1 ? 'confirm.deleteManyDesc' : 'confirm.deleteDesc')}${pendingMissing ? ` ${t('projects.removeAlso')}` : ''}`;
- const folderHeld = pendingFolder ? lib.projects.filter((p) => p.folderId === pendingFolder.id).length : 0;
+ /* what deleting it takes: its projects and those of the folders inside it */
+ const folderHeld = pendingFolder ? (folderCounts(lib.projects, lib.folders)[pendingFolder.id] ?? 0) : 0;
return createPortal(
<>
diff --git a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx b/packages/openfilm/studio/ui/src/components/ProjectsView.tsx
index 4aac004..ea6e466 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectsView.tsx
@@ -32,7 +32,7 @@ import { ExamplesSection } from './ProjectSources';
import { useLanguage, useT, type Language } from '@/i18n';
import { limitTitleWidth, TITLE_MAX_WIDTH } from '@/lib/title';
import type { Project } from '@/api';
-import { folderCounts, folderPosters, visibleProjects, type LibrarySort, type ProjectFolder } from '@/lib/project-folders';
+import { folderCounts, folderPosters, folderTrail, parentOf, visibleProjects, type LibrarySort, type ProjectFolder } from '@/lib/project-folders';
import { ContextMenu } from './ContextMenu';
import { ProjectMenu } from './ProjectMenu';
import { Tooltip } from './Tooltip';
@@ -89,7 +89,8 @@ export function ProjectsView({
/** The list's folders. */
folders: ProjectFolder[];
/** Make a folder; resolves to it (null: it could not be made). */
- onCreateFolder: (name: string) => Promise<ProjectFolder | null>;
+ /** A new folder, in `parentId` (null: the top level). */
+ onCreateFolder: (name: string, parentId?: string | null) => Promise<ProjectFolder | null>;
/** A new name for a folder. Never empty. */
onRenameFolder: (folderId: string, name: string) => void;
/** Ask to delete a folder and the projects in it (the popover confirms first). */
@@ -122,13 +123,16 @@ export function ProjectsView({
[projects, query, folderId, sort, folders, t],
);
/* folder cards only at the top level and not while searching: inside a folder is its content, a search its results */
- const showFolders = folderId === null && !query.trim();
+ /* the folders here: the top level's, or those inside the folder open (a search shows projects only) */
+ const showFolders = !query.trim();
+ const levelFolders = React.useMemo(() => folders.filter((f) => parentOf(f, folders) === folderId), [folders, folderId]);
const currentFolder = folders.find((f) => f.id === folderId) ?? null;
- const counts = React.useMemo(() => folderCounts(projects), [projects]);
- const posters = React.useMemo(() => folderPosters(projects), [projects]);
+ const trail = React.useMemo(() => folderTrail(folders, folderId), [folders, folderId]);
+ const counts = React.useMemo(() => folderCounts(projects, folders), [projects, folders]);
+ const posters = React.useMemo(() => folderPosters(projects, folders), [projects, folders]);
async function newFolder() {
- const created = await onCreateFolder(t('projects.untitledFolder'));
+ const created = await onCreateFolder(t('projects.untitledFolder'), folderId);
if (created) setRenamingFolderId(created.id);
}
@@ -243,7 +247,20 @@ export function ProjectsView({
{/* the header stays out of the scroll area: inside it, the list view's scrollbar would narrow the header */}
<header className="flex shrink-0 flex-col gap-3 px-6 pb-4 pt-5">
<div className="flex items-center gap-2">
- <h2 className="mr-auto text-[17px] font-semibold tracking-[-0.01em] text-[var(--text)]">{t('nav.projects')}</h2>
+ {/* inside a folder the title is the way back: "Projects / test", on the same line, so what is in the folder
+ starts where the projects do */}
+ {currentFolder ? (
+ <FolderCrumb
+ folder={currentFolder}
+ above={trail.slice(0, -1)}
+ count={counts[currentFolder.id] ?? 0}
+ onGo={setFolderId}
+ onRename={(name) => onRenameFolder(currentFolder.id, name)}
+ onDelete={() => onDeleteFolder(currentFolder)}
+ />
+ ) : (
+ <h2 className="mr-auto text-[17px] font-semibold tracking-[-0.01em] text-[var(--text)]">{t('nav.projects')}</h2>
+ )}
{projects.length > 0 ? (
<>
<label className="relative w-[240px] shrink-0">
@@ -262,18 +279,17 @@ export function ProjectsView({
<ViewButton active={view === 'cards'} label={t('library.viewCards')} onClick={() => setView('cards')} icon={<LayoutGrid size={14} />} />
<ViewButton active={view === 'list'} label={t('library.viewList')} onClick={() => setView('list')} icon={<List size={14} />} />
</div>
- {folderId === null ? (
- <Tooltip label={t('projects.newFolder')} side="bottom">
- <button
- type="button"
- aria-label={t('projects.newFolder')}
- onClick={() => void newFolder()}
- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
- >
- <FolderPlus size={15} strokeWidth={1.9} />
- </button>
- </Tooltip>
- ) : null}
+ {/* at the top level or inside a folder: a folder can hold folders */}
+ <Tooltip label={t('projects.newFolder')} side="bottom">
+ <button
+ type="button"
+ aria-label={t('projects.newFolder')}
+ onClick={() => void newFolder()}
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
+ >
+ <FolderPlus size={15} strokeWidth={1.9} />
+ </button>
+ </Tooltip>
</>
) : null}
{onClose ? (
@@ -287,39 +303,30 @@ export function ProjectsView({
</button>
) : null}
</div>
- {currentFolder ? (
- <FolderCrumb
- folder={currentFolder}
- count={counts[currentFolder.id] ?? 0}
- onBack={() => setFolderId(null)}
- onRename={(name) => onRenameFolder(currentFolder.id, name)}
- onDelete={() => onDeleteFolder(currentFolder)}
- />
- ) : null}
</header>
{/* the one scroll area; the scrollbar gutter is reserved so cards keep their width either way */}
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto [scrollbar-gutter:stable]">
<div className="w-full flex-1 px-6 pb-6">
- {visible.length === 0 && !showNew && !(showFolders && folders.length > 0) ? (
+ {visible.length === 0 && !showNew && !(showFolders && levelFolders.length > 0) ? (
<div className="flex min-h-[42vh] items-center justify-center text-[14px] text-[var(--text-muted)]">
{folderId && !query.trim() ? t('projects.folderEmpty') : t('library.noMatches')}
</div>
) : view === 'cards' ? (
<div className="grid grid-cols-2 gap-x-4 gap-y-6 sm:grid-cols-3 lg:grid-cols-4">
{showNew ? <NewProjectCard creating={creating} onNewProject={onNewProject} onOpenFolder={onOpenFolder} onGetFromGitHub={onGetFromGitHub} /> : null}
- {showFolders ? folders.map((folder) => <FolderCard key={`folder:${folder.id}`} {...folderProps(folder)} />) : null}
+ {showFolders ? levelFolders.map((folder) => <FolderCard key={`folder:${folder.id}`} {...folderProps(folder)} />) : null}
{visible.map((project) => <ProjectCard key={project.id} {...itemProps(project)} />)}
</div>
) : (
<div className="flex flex-col divide-y divide-[var(--border)]">
{showNew ? <NewProjectListRow creating={creating} onNewProject={onNewProject} onOpenFolder={onOpenFolder} onGetFromGitHub={onGetFromGitHub} /> : null}
- {showFolders ? folders.map((folder) => <FolderListRow key={`folder:${folder.id}`} {...folderProps(folder)} />) : null}
+ {showFolders ? levelFolders.map((folder) => <FolderListRow key={`folder:${folder.id}`} {...folderProps(folder)} />) : null}
{visible.map((project) => <ProjectListRow key={project.id} {...itemProps(project)} />)}
</div>
)}
{showNew && onOpenExample ? (
- <ExamplesSection examples={examples} collapsed={examplesCollapsed} onToggle={() => onToggleExamples?.()} onOpen={onOpenExample} />
+ <ExamplesSection examples={examples} collapsed={examplesCollapsed} onToggle={() => onToggleExamples?.()} onOpen={onOpenExample} view={view} />
) : null}
</div>
@@ -870,6 +877,30 @@ interface FolderItemProps {
onDelete: () => void;
}
+/**
+ * A folder's face: the covers of its newest projects (as many cells as covers: one fills the face, three put the first
+ * beside the other two, so no cell is blank), or the folder picture when it holds none. The card's, and the list row's
+ * thumbnail (`small`: tighter margins).
+ */
+function FolderFace({ posters, small = false }: { posters: FolderItemProps['posters']; small?: boolean }) {
+ if (!posters.length) {
+ return (
+ <div className="absolute inset-0 flex items-center justify-center">
+ <FolderGlyph className="w-[34%] transition-transform duration-200 group-hover:-translate-y-0.5" />
+ </div>
+ );
+ }
+ return (
+ <div className={`absolute grid ${small ? 'inset-1.5 gap-1' : 'inset-3 gap-1.5'} ${posters.length === 1 ? 'grid-cols-1' : posters.length === 2 ? 'grid-cols-2' : 'grid-cols-2 grid-rows-2'}`}>
+ {posters.slice(0, 4).map((cover, i) => (
+ <div key={cover.id} className={`relative overflow-hidden ${small ? 'rounded-[3px]' : 'rounded-[5px]'} bg-[var(--surface-3)] ${posters.length === 3 && i === 0 ? 'row-span-2' : ''}`}>
+ <MiniPoster id={cover.id} url={cover.poster} />
+ </div>
+ ))}
+ </div>
+ );
+}
+
/**
* A folder card: the project card's frame (a 16:9 face and a name under it), its face the covers of its newest
* projects, so what it holds shows at a glance; an empty one shows the folder picture. Double-click the name to rename.
@@ -895,20 +926,7 @@ function FolderCard({
aria-label={folder.name}
className="relative block aspect-video w-full overflow-hidden rounded-lg bg-[var(--surface-2)] text-left ring-1 ring-[var(--border)] transition duration-200 hover:bg-[var(--surface-3)] hover:ring-[var(--border-strong)]"
>
- {posters.length > 0 ? (
- /* as many cells as covers (one fills the face, three put the first beside the other two): no blank cells */
- <div className={`absolute inset-3 grid gap-1.5 ${posters.length === 1 ? 'grid-cols-1' : posters.length === 2 ? 'grid-cols-2' : 'grid-cols-2 grid-rows-2'}`}>
- {posters.slice(0, 4).map((cover, i) => (
- <div key={cover.id} className={`relative overflow-hidden rounded-[5px] bg-[var(--surface-3)] ${posters.length === 3 && i === 0 ? 'row-span-2' : ''}`}>
- <MiniPoster id={cover.id} url={cover.poster} />
- </div>
- ))}
- </div>
- ) : (
- <div className="absolute inset-0 flex items-center justify-center">
- <FolderGlyph className="w-[34%] transition-transform duration-200 group-hover:-translate-y-0.5" />
- </div>
- )}
+ <FolderFace posters={posters} />
{/* the count: dark glass over covers; on the plain face a dark patch is too heavy, so the face's own style */}
<span
className={`absolute bottom-2 right-2 rounded-full px-1.5 py-0.5 text-[10.5px] font-medium tabular-nums ${
@@ -982,6 +1000,7 @@ function MiniPoster({ id, url }: { id: string; url?: string }) {
function FolderListRow({
folder,
count,
+ posters,
renaming,
onOpen,
onStartRename,
@@ -996,12 +1015,10 @@ function FolderListRow({
<button
type="button"
onClick={onOpen}
- className="relative block aspect-video w-28 shrink-0 overflow-hidden rounded-md bg-[var(--surface-2)] ring-1 ring-[var(--border)] transition hover:bg-[var(--surface-3)] sm:w-36"
+ className="group relative block aspect-video w-28 shrink-0 overflow-hidden rounded-md bg-[var(--surface-2)] ring-1 ring-[var(--border)] transition hover:bg-[var(--surface-3)] sm:w-36"
aria-label={folder.name}
>
- <span className="absolute inset-0 flex items-center justify-center">
- <FolderGlyph className="w-[34%]" />
- </span>
+ <FolderFace posters={posters} small />
</button>
<div className="min-w-0 flex-1">
{renaming ? (
@@ -1073,34 +1090,45 @@ function FolderMenu({ onRename, onDelete }: { onRename: () => void; onDelete: ()
);
}
-/** Inside a folder: "← All / folder name count …". Double-click the name to rename. */
+/**
+ * Inside a folder, in the title's place: "← Projects / Clients / Acme count …", each folder above it a way back to
+ * it, the arrow one level up. Double-click the name to rename.
+ */
function FolderCrumb({
folder,
+ above,
count,
- onBack,
+ onGo,
onRename,
onDelete,
}: {
folder: ProjectFolder;
+ /** the folders it is in, the outermost first */
+ above: ProjectFolder[];
count: number;
- onBack: () => void;
+ /** go to a folder of the trail (null: all projects) */
+ onGo: (folderId: string | null) => void;
onRename: (name: string) => void;
onDelete: () => void;
}) {
const t = useT();
const [renaming, setRenaming] = React.useState(false);
+ const step = 'inline-flex h-8 min-w-0 items-center rounded-lg px-1.5 text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]';
return (
- <div className="mt-5 flex items-center gap-2">
- <button
- type="button"
- onClick={onBack}
- className="inline-flex h-8 items-center gap-1.5 rounded-lg px-2 text-[13px] text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
- >
- <ArrowLeft size={14} />
- {t('projects.folderAll')}
+ <h2 className="mr-auto flex min-w-0 items-center gap-1 text-[17px] font-semibold tracking-[-0.01em]">
+ <button type="button" onClick={() => onGo(above.length ? above[above.length - 1]!.id : null)} aria-label={t('projects.folderUp')}
+ className="-ml-1.5 inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]">
+ <ArrowLeft size={15} />
</button>
- <span className="text-[var(--text-faint)]">/</span>
- <Folder size={15} strokeWidth={1.9} className="text-[var(--text-faint)]" />
+ <button type="button" onClick={() => onGo(null)} className={`${step} shrink-0`}>{t('nav.projects')}</button>
+ {above.map((up) => (
+ <React.Fragment key={up.id}>
+ <span className="shrink-0 font-normal text-[var(--text-faint)]">/</span>
+ <button type="button" onClick={() => onGo(up.id)} className={`${step} max-w-[160px]`}><span className="truncate">{up.name}</span></button>
+ </React.Fragment>
+ ))}
+ <span className="shrink-0 font-normal text-[var(--text-faint)]">/</span>
+ <Folder size={16} strokeWidth={1.9} className="shrink-0 text-[var(--text-faint)]" />
{renaming ? (
<InlineNameInput
initial={folder.name}
@@ -1109,21 +1137,21 @@ function FolderCrumb({
if (name && name !== folder.name) onRename(name);
}}
onCancel={() => setRenaming(false)}
- className="h-8 w-[240px] rounded-lg border border-[var(--text)] bg-[var(--surface)] px-2.5 text-[14px] font-semibold text-[var(--text)] outline-none"
+ className="h-8 w-[220px] rounded-lg border border-[var(--text)] bg-[var(--surface)] px-2.5 text-[15px] font-semibold text-[var(--text)] outline-none"
/>
) : (
<button
type="button"
onDoubleClick={() => setRenaming(true)}
- className="truncate text-[14px] font-semibold text-[var(--text)]"
+ className="min-w-0 truncate text-[var(--text)]"
title={t('projects.renameFolder')}
>
{folder.name}
</button>
)}
- <span className="text-[12.5px] tabular-nums text-[var(--text-faint)]">{count}</span>
+ <span className="shrink-0 text-[12.5px] font-normal tabular-nums text-[var(--text-faint)]">{count}</span>
<FolderMenu onRename={() => setRenaming(true)} onDelete={onDelete} />
- </div>
+ </h2>
);
}
@@ -1198,6 +1226,18 @@ function FolderPicker({
}) {
const t = useT();
const [creating, setCreating] = React.useState(false);
+ const tree = React.useMemo(() => {
+ const out: { folder: ProjectFolder; depth: number }[] = [];
+ const walk = (parent: string | null, depth: number) => {
+ for (const f of folders) {
+ if (parentOf(f, folders) !== parent || out.some((o) => o.folder.id === f.id)) continue;
+ out.push({ folder: f, depth });
+ walk(f.id, depth + 1);
+ }
+ };
+ walk(null, 0);
+ return out;
+ }, [folders]);
React.useEffect(() => {
/* this Escape closes the picker, not the popover under it */
const onKey = (event: KeyboardEvent) => {
@@ -1251,8 +1291,9 @@ function FolderPicker({
<span className="min-w-0 flex-1 truncate text-[13.5px] text-[var(--text)]">{t('projects.noFolder')}</span>
{current === null ? <Check size={15} className="shrink-0 text-[var(--text)]" /> : null}
</button>
- {folders.map((folder) => (
- <button key={folder.id} type="button" onClick={() => onPick(folder.id)} className={row(current === folder.id)}>
+ {/* as a tree: each folder under the one it is in, a step in */}
+ {tree.map(({ folder, depth }) => (
+ <button key={folder.id} type="button" onClick={() => onPick(folder.id)} className={row(current === folder.id)} style={{ paddingLeft: 10 + depth * 18 }}>
<span className={`${tile} bg-[var(--surface-3)] text-[var(--text-dim)]`}>
<Folder size={16} strokeWidth={1.7} />
</span>
diff --git a/packages/openfilm/studio/ui/src/components/SelectionToolbar.tsx b/packages/openfilm/studio/ui/src/components/SelectionToolbar.tsx
index c75ecb4..c12be18 100644
--- a/packages/openfilm/studio/ui/src/components/SelectionToolbar.tsx
+++ b/packages/openfilm/studio/ui/src/components/SelectionToolbar.tsx
@@ -7,8 +7,8 @@
* · **Beside it, never over it** (lib/selection-toolbar placeToolbar): above, else below, inside the area it belongs
* to, and clear of what its owner says it must not cover (the other clips on the timeline); placed again on every
* render of its owner, so it follows a scroll or a moved frame.
- * · **Once the selection settles.** It waits SETTLE_MS after the selection last changed (a marquee, a click that
- * becomes a drag) and stays away while `hidden` (dragging, trimming, cropping, typing, playing).
+ * · **At once.** It shows with the selection's own frame, in the same paint, and stays away while `hidden` (a
+ * marquee, dragging, trimming, cropping, typing, playing): its owner says when the selection is still moving.
* · **Esc puts it away** until the selection changes.
* · **On body**, like the menus: the timeline and the picture clip what spills out of them. Presses on it reach
* neither (they would select or drag what is under it in the component tree), and take no focus (Space plays).
@@ -20,9 +20,6 @@ import { createPortal } from 'react-dom';
import { Tooltip } from '@/components/Tooltip';
import { placeToolbar, type ScreenBox, type ToolbarPlacement } from '@/lib/selection-toolbar';
-/** How long the selection must stay the same before the bar shows. */
-const SETTLE_MS = 180;
-
export interface SelectionTool {
id: string;
label: string;
@@ -42,14 +39,14 @@ export type SelectionToolEntry = SelectionTool | { id: string; separator: true }
export function SelectionToolbar({
selection, measure, hidden = false, lead, label, tools, ariaLabel,
}: {
- /** What is selected, as a key (null: nothing). A new key waits to settle again; Esc hides the bar until it changes. */
+ /** What is selected, as a key (null: nothing). Esc hides the bar until it changes. */
selection: string | null;
/**
* Where the selection is on screen and the area the bar stays in (and the room between, when not the usual; what it
* must not cover); null when it cannot be seen.
*/
measure: () => { anchor: ScreenBox; bounds: ScreenBox; gap?: number; avoid?: readonly ScreenBox[] } | null;
- /** Kept away for now (a drag, playback): shown again once it settles after. */
+ /** Kept away for now (a drag, playback): shown again when it ends. */
hidden?: boolean;
/** The first button, always: "Add to chat" (none without a chat). */
lead?: SelectionTool | null;
@@ -60,20 +57,13 @@ export function SelectionToolbar({
ariaLabel: string;
}) {
const ref = React.useRef<HTMLDivElement | null>(null);
- const [ready, setReady] = React.useState(false);
const [dismissed, setDismissed] = React.useState<string | null>(null);
const [pos, setPos] = React.useState<ToolbarPlacement | null>(null);
const [, setTick] = React.useState(0);
- React.useEffect(() => {
- setReady(false);
- if (!selection || hidden) return undefined;
- const timer = window.setTimeout(() => setReady(true), SETTLE_MS);
- return () => window.clearTimeout(timer);
- }, [selection, hidden]);
React.useEffect(() => { if (dismissed && dismissed !== selection) setDismissed(null); }, [dismissed, selection]);
- const shown = ready && !hidden && selection != null && dismissed !== selection && (Boolean(lead) || tools.length > 0);
+ const shown = !hidden && selection != null && dismissed !== selection && (Boolean(lead) || tools.length > 0);
React.useEffect(() => {
if (!shown) return undefined;
@@ -124,8 +114,8 @@ export function SelectionToolbar({
style={{
left: pos?.left ?? 0,
top: pos?.top ?? 0,
+ /* shown at once, where it goes: a rise would trail the click */
visibility: pos ? 'visible' : 'hidden',
- animation: pos ? 'openfilm-rise 0.12s ease-out both' : undefined,
}}
>
{lead ? <ToolbarButton tool={lead} side={side} /> : null}
diff --git a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx b/packages/openfilm/studio/ui/src/components/SourcePreview.tsx
index c62fa25..4f7a394 100644
--- a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx
+++ b/packages/openfilm/studio/ui/src/components/SourcePreview.tsx
@@ -7,7 +7,7 @@
* marks go), and `,` inserts it at the film's playhead, `.` overwrites there (lib/media-place).
*/
import React from 'react';
-import { ArrowDownToLine, BetweenHorizontalStart } from 'lucide-react';
+import { Expand } from 'lucide-react';
import { useT } from '@/i18n';
import { STILL_DROP_MS } from '@/lib/asset-timeline';
import type { SourceRange } from '@/lib/media-place';
@@ -118,11 +118,10 @@ function Scrubber({ time, duration, onSeek, label, marks }: { time: number; dura
}
/** The source's own transport: its scrub line, then the bar the film's viewer has (time, play, and its name). */
-function SourceBar({ time, duration, playing, onToggle, onSeek, name, disabled, marks, onPlace }: {
- time: number; duration: number; playing: boolean; onToggle: () => void; onSeek: (sec: number) => void; name: string; disabled?: boolean;
+function SourceBar({ time, duration, playing, onToggle, onSeek, disabled, marks, onFullscreen }: {
+ time: number; duration: number; playing: boolean; onToggle: () => void; onSeek: (sec: number) => void; disabled?: boolean;
marks?: Marks;
- /** Put the part marked on the film (the `,` and `.` keys' buttons). */
- onPlace?: (mode: 'insert' | 'overwrite') => void;
+ onFullscreen: () => void;
}) {
const t = useT();
const marked = marks && (marks.in != null || marks.out != null)
@@ -136,29 +135,20 @@ function SourceBar({ time, duration, playing, onToggle, onSeek, name, disabled,
totalMs={disabled ? 0 : duration * 1000}
playing={playing}
onPlayPause={onToggle}
- frame={(
- <span className="flex min-w-0 items-center gap-1">
- <span className="min-w-0 truncate text-[12px] text-[var(--text-dim)]">{name}</span>
- {marked ? <span data-source-range="" className="shrink-0 text-[11px] tabular-nums text-[var(--accent)]">{marked}</span> : null}
- {onPlace ? <>
- <Tooltip label={t('media.insertSource')} shortcut=",">
- <button type="button" aria-label={t('media.insertSource')} onMouseDown={(e) => e.preventDefault()} onClick={() => onPlace('insert')} className={PANE_BTN}>
- <BetweenHorizontalStart size={PANE_ICON} />
- </button>
- </Tooltip>
- <Tooltip label={t('media.overwriteSource')} shortcut=".">
- <button type="button" aria-label={t('media.overwriteSource')} onMouseDown={(e) => e.preventDefault()} onClick={() => onPlace('overwrite')} className={PANE_BTN}>
- <ArrowDownToLine size={PANE_ICON} />
- </button>
- </Tooltip>
- </> : null}
- </span>
- )}
+ onFullscreen={onFullscreen}
+ /* the part marked with I and O, while there is one (`,` and `.` put it on the film) */
+ frame={marked ? <span data-source-range="" className="shrink-0 text-[11px] tabular-nums text-[var(--accent)]">{marked}</span> : undefined}
/>
</div>
);
}
+/** The preview full screen, or back (the same button). */
+function toggleFullscreen(el: HTMLElement | null) {
+ if (document.fullscreenElement) void document.exitFullscreen().catch(() => {});
+ else void el?.requestFullscreen?.().catch(() => {});
+}
+
export interface SourcePreviewProps {
file: WorkspaceResource;
sources: MediaSources;
@@ -168,12 +158,17 @@ export interface SourcePreviewProps {
}
export function SourcePreview(props: SourcePreviewProps) {
- /* a web page is previewed on its own: its own timeline from 0, driven here through Studio's bridge */
- return props.file.kind === 'mg' ? <PagePreview {...props} /> : <MediaPreviewPane {...props} />;
+ /* a web page is previewed on its own: its own timeline from 0, driven here through Studio's bridge. Each file is a
+ preview of its own (keyed by its path): another one picked starts at 0, paused, with nothing of the last one's
+ clock (a frame of its playback could land after a reset and carry its time over) */
+ return props.file.kind === 'mg'
+ ? <PagePreview key={props.file.path} {...props} />
+ : <MediaPreviewPane key={props.file.path} {...props} />;
}
function MediaPreviewPane({ file, sources, onClose, onPlace }: SourcePreviewProps) {
const t = useT();
+ const rootRef = React.useRef<HTMLDivElement>(null);
const mediaRef = React.useRef<HTMLVideoElement & HTMLAudioElement>(null);
const [playing, setPlaying] = React.useState(false);
const [time, setTime] = React.useState(0);
@@ -185,7 +180,6 @@ function MediaPreviewPane({ file, sources, onClose, onPlace }: SourcePreviewProp
React.useEffect(() => { setPlaying(false); setTime(0); setFailed(false); setDuration((file.durationMs ?? 0) / 1000); }, [file.path, file.durationMs]);
/* a still has no part to mark: `,` and `.` put it whole */
const marks = useSourceKeys(file.path, timed ? time : 0, timed ? duration : 0, onPlace);
- const place = onPlace ? (mode: 'insert' | 'overwrite') => onPlace(mode, timed ? rangeOf(marks, duration) : null) : undefined;
const toggle = React.useCallback(() => {
const media = mediaRef.current;
@@ -225,7 +219,7 @@ function MediaPreviewPane({ file, sources, onClose, onPlace }: SourcePreviewProp
};
return (
- <div className="absolute inset-0 z-20 flex flex-col bg-[var(--dock-pane)]">
+ <div ref={rootRef} className="absolute inset-0 z-20 flex flex-col bg-[var(--dock-pane)]">
<div className="relative flex min-h-0 flex-1 items-center justify-center px-3 py-2.5" onClick={timed ? toggle : undefined}>
{failed ? (
<p className="text-[12.5px] text-[var(--text-muted)]">{t('media.cannotPreview')}</p>
@@ -237,6 +231,8 @@ function MediaPreviewPane({ file, sources, onClose, onPlace }: SourcePreviewProp
/* a poster that fails to load covers the first frame in black: only when there is one */
poster={sources.poster?.(file)}
playsInline
+ /* picked to be seen: it plays from the start at once (the click that picked it lets the sound play) */
+ autoPlay
preload="auto"
className="h-full w-full object-contain"
{...mediaEvents}
@@ -247,7 +243,7 @@ function MediaPreviewPane({ file, sources, onClose, onPlace }: SourcePreviewProp
<div className="relative h-[42%] w-full max-w-[920px] overflow-hidden rounded-md">
<MediaPreview file={file} sources={sources} />
{duration > 0 ? <span className="pointer-events-none absolute inset-y-0 w-px bg-white/90" style={{ left: `${(time / duration) * 100}%` }} /> : null}
- <audio key={file.path} ref={mediaRef} src={src} preload="auto" {...mediaEvents} />
+ <audio key={file.path} ref={mediaRef} src={src} preload="auto" autoPlay {...mediaEvents} />
</div>
) : (
<p className="text-[12.5px] text-[var(--text-muted)]">{t('media.cannotPreview')}</p>
@@ -260,21 +256,17 @@ function MediaPreviewPane({ file, sources, onClose, onPlace }: SourcePreviewProp
playing={playing}
onToggle={toggle}
onSeek={(v) => { const m = mediaRef.current; if (m) m.currentTime = v; setTime(v); }}
- name={file.name}
marks={marks}
- {...(place ? { onPlace: place } : {})}
+ onFullscreen={() => toggleFullscreen(rootRef.current)}
/>
) : (
<div className="flex h-8 shrink-0 items-center gap-2 px-3 text-[12px] text-[var(--text-muted)]">
<span className="min-w-0 flex-1 truncate">{file.w && file.h ? `${file.w} × ${file.h}` : ''}</span>
- <span className="min-w-0 max-w-[30%] truncate text-[var(--text-dim)]">{file.name}</span>
- {place ? (
- <Tooltip label={t('media.insertSource')} shortcut=",">
- <button type="button" aria-label={t('media.insertSource')} onMouseDown={(e) => e.preventDefault()} onClick={() => place('insert')} className={PANE_BTN}>
- <BetweenHorizontalStart size={PANE_ICON} />
- </button>
- </Tooltip>
- ) : null}
+ <Tooltip label={t('viewer.fullscreen')}>
+ <button type="button" aria-label={t('viewer.fullscreen')} onMouseDown={(e) => e.preventDefault()} onClick={() => toggleFullscreen(rootRef.current)} className={PANE_BTN}>
+ <Expand size={PANE_ICON} />
+ </button>
+ </Tooltip>
</div>
)}
</div>
@@ -287,6 +279,7 @@ function MediaPreviewPane({ file, sources, onClose, onPlace }: SourcePreviewProp
*/
function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
const t = useT();
+ const rootRef = React.useRef<HTMLDivElement>(null);
const frameRef = React.useRef<HTMLIFrameElement>(null);
const boxRef = React.useRef<HTMLDivElement>(null);
const clockRef = React.useRef({ base: 0, at: 0 });
@@ -301,8 +294,6 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
const [time, setTime] = React.useState(0);
const [scale, setScale] = React.useState(1);
- React.useEffect(() => { setSize(null); setFailed(false); setPlaying(false); setTime(0); }, [file.path]);
-
const draw = React.useCallback((at: number) => {
if (!origin) return;
frameRef.current?.contentWindow?.postMessage({ source: 'openfilm-studio', type: 'seek', seq: ++seq.current, t: Math.max(0, at) }, origin);
@@ -337,7 +328,6 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
/* a page without a duration has no part to mark: it goes with the length a drop gives it */
const timedPage = Boolean(size?.duration);
const marks = useSourceKeys(file.path, timedPage ? time : 0, timedPage ? duration : 0, onPlace);
- const place = onPlace ? (mode: 'insert' | 'overwrite') => onPlace(mode, timedPage ? rangeOf(marks, duration) : null) : undefined;
const play = React.useCallback(() => {
if (!size) return;
const from = time >= duration - 0.05 ? 0 : time;
@@ -345,6 +335,13 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
setPlaying(true);
}, [time, duration, size]);
const pause = React.useCallback(() => setPlaying(false), []);
+ /* picked to be seen: it plays from the start once the page is ready (once: a pause stays a pause) */
+ const started = React.useRef(false);
+ React.useEffect(() => {
+ if (!size || started.current) return;
+ started.current = true;
+ play();
+ }, [size, play]);
const toggle = React.useCallback(() => (playing ? pause() : play()), [playing, play, pause]);
React.useEffect(() => {
@@ -374,7 +371,7 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
}, [onClose, toggle]);
return (
- <div className="absolute inset-0 z-20 flex flex-col bg-[var(--dock-pane)]">
+ <div ref={rootRef} className="absolute inset-0 z-20 flex flex-col bg-[var(--dock-pane)]">
<div ref={boxRef} className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden px-3 py-2.5" onClick={toggle}>
{/* nothing to play it on (no surface for this page) is the same as a page that failed */}
{failed || !surface ? <p className="text-[12.5px] text-[var(--text-muted)]">{t('media.cannotPreview')}</p> : (
@@ -396,10 +393,9 @@ function PagePreview({ file, sources, onClose, onPlace }: SourcePreviewProps) {
playing={playing}
onToggle={toggle}
onSeek={(v) => { setPlaying(false); setTime(v); draw(v); }}
- name={file.name}
disabled={!size}
marks={marks}
- {...(place ? { onPlace: place } : {})}
+ onFullscreen={() => toggleFullscreen(rootRef.current)}
/>
</div>
);
diff --git a/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx b/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx
index 38d895f..7c69e2b 100644
--- a/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx
+++ b/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx
@@ -12,7 +12,7 @@
* shown or hidden with its button in the toolbar (kept on this machine).
*/
import React from 'react';
-import { Captions, Combine, Pencil, Plus, Scissors, Trash2 } from 'lucide-react';
+import { Captions, Combine, EyeOff, Pencil, Plus, Scissors, Trash2 } from 'lucide-react';
import { useT } from '@/i18n';
import { shortcutHint } from '@/lib/shortcut-hint';
import {
@@ -62,6 +62,10 @@ function setShown(on: boolean): void {
try { localStorage.setItem(SHOWN_KEY, on ? '1' : '0'); } catch { /* this session only */ }
for (const fn of shownListeners) fn();
}
+/** "Hide the row", in the row's menus: where it comes back is said under it. */
+const hideRowItem = (t: (key: string) => string): ContextMenuEntry => ({
+ id: 'hide', label: t('subtitleRow.hide'), note: t('subtitleRow.hideNote'), icon: <EyeOff size={14} />, onSelect: () => setShown(false),
+});
export function useSubtitleRowShown(): [boolean, (on: boolean) => void] {
const on = React.useSyncExternalStore((fn) => { shownListeners.add(fn); return () => { shownListeners.delete(fn); }; }, readShown, () => true);
return [on, setShown];
@@ -92,11 +96,22 @@ export function SubtitleRowToggle() {
);
}
-/** The row's head, in the timeline's head column: its name, and a cue added at the playhead. */
+/**
+ * The row's head, in the timeline's head column: its name, and a cue added at the playhead. Its right-click menu adds
+ * one too, or hides the row (it comes back from the subtitle panel's "Edit on timeline").
+ */
export function SubtitleRowHead({ onAdd }: { onAdd: () => void }) {
const t = useT();
+ const [menu, setMenu] = React.useState<{ x: number; y: number } | null>(null);
+ const items: ContextMenuEntry[] = [
+ { id: 'add', label: t('subtitleRow.add'), icon: <Plus size={14} />, onSelect: onAdd },
+ { id: 'sep', separator: true },
+ hideRowItem(t),
+ ];
return (
- <div className="flex items-center justify-between gap-1 border-b pl-2 pr-1" style={{ height: SUBTITLE_ROW_H, borderColor: 'var(--tl-line)' }}>
+ <div className="flex items-center justify-between gap-1 border-b pl-2 pr-1" style={{ height: SUBTITLE_ROW_H, borderColor: 'var(--tl-line)' }}
+ data-subtitle-row-head=""
+ onContextMenu={(e) => { e.preventDefault(); e.stopPropagation(); setMenu({ x: e.clientX, y: e.clientY }); }}>
<span className="truncate text-[10.5px] font-medium" style={{ color: 'var(--tl-text)' }}>{t('subtitleRow.name')}</span>
<Tooltip side="bottom" label={t('subtitleRow.add')}>
<button type="button" onClick={onAdd} onMouseDown={(e) => e.preventDefault()} aria-label={t('subtitleRow.add')}
@@ -104,6 +119,7 @@ export function SubtitleRowHead({ onAdd }: { onAdd: () => void }) {
<Plus size={13} />
</button>
</Tooltip>
+ {menu ? <ContextMenu x={menu.x} y={menu.y} items={items} onClose={() => setMenu(null)} /> : null}
</div>
);
}
@@ -297,7 +313,11 @@ export const SubtitleRow = React.forwardRef<SubtitleRowHandle, {
const at = playheadMs();
if (!cue) {
setSelected(null);
- setMenu({ x: e.clientX, y: e.clientY, items: [{ id: 'add', label: t('subtitleRow.add'), icon: <Plus size={14} />, onSelect: () => addAt(at) }] });
+ setMenu({ x: e.clientX, y: e.clientY, items: [
+ { id: 'add', label: t('subtitleRow.add'), icon: <Plus size={14} />, onSelect: () => addAt(at) },
+ { id: 'sep', separator: true },
+ hideRowItem(t),
+ ] });
return;
}
setSelected(cueKey(cue));
diff --git a/packages/openfilm/studio/ui/src/components/Timeline.tsx b/packages/openfilm/studio/ui/src/components/Timeline.tsx
index 187850c..804c7e1 100644
--- a/packages/openfilm/studio/ui/src/components/Timeline.tsx
+++ b/packages/openfilm/studio/ui/src/components/Timeline.tsx
@@ -152,8 +152,8 @@ import { cutNear, transitionSpan, type CutRef, type FilmTransition, type Transit
/** Track head column: kind badge + lock + hide + original sound. */
const HEAD_W = 108;
-/** The head column's width when a track has a name: room for the name beside its badge. */
-const HEAD_NAMED_W = 168;
+/** A row at least this tall shows its track's name under the badge (a lower one says it on hover). */
+const HEAD_NAME_MIN_H = 34;
/** The room solo's S takes in a head. */
const HEAD_SOLO_W = 24;
/* the head toggles' icons: at 10 px lock and eye are indistinguishable dots on Retina */
@@ -1459,9 +1459,7 @@ export const Timeline = React.memo(function Timeline({
const [renaming, setRenaming] = React.useState<number | null>(null);
const renamingRef = React.useRef(renaming);
renamingRef.current = renaming;
- /* a named track widens the heads, so its name fits beside its badge */
- const named = renaming != null || tracks.some((tr) => tr.docIndex != null && Boolean(trackNames?.get(tr.docIndex)));
- const headW = (named ? HEAD_NAMED_W : HEAD_W) + (solo ? HEAD_SOLO_W : 0);
+ const headW = HEAD_W + (solo ? HEAD_SOLO_W : 0);
/* picking clips lets the gap go; so does an edit that fills or moves it */
React.useEffect(() => { if (selected.length) setGap(null); }, [selected.length]);
React.useEffect(() => {
@@ -2173,6 +2171,8 @@ export const Timeline = React.memo(function Timeline({
const lit = selectedLanes.has(track.lane);
const targeted = targetLane === track.lane;
const renamingHere = renaming != null && renaming === track.docIndex && track.index === 1;
+ /* typing a name always has its field; a name given shows when the row has room for it */
+ const nameLine = renamingHere || (Boolean(given) && h >= HEAD_NAME_MIN_H);
/* the track a pill hovered in the app's chat points at */
const chatLit = chatTrack != null && track.docIndex === chatTrack;
return (
@@ -2195,7 +2195,9 @@ export const Timeline = React.memo(function Timeline({
style={{
marginTop: GAP,
height: h,
- gridTemplateColumns: named ? `minmax(0,1fr) 24px 24px 24px${solo ? ' 24px' : ''}` : `repeat(${solo ? 5 : 4}, minmax(0, 1fr))`,
+ gridTemplateColumns: `repeat(${solo ? 5 : 4}, minmax(0, 1fr))`,
+ /* a name goes on a line of its own under the badge and the toggles: the heads keep their width */
+ ...(nameLine ? { gridTemplateRows: 'auto auto', alignContent: 'center', rowGap: 3 } : {}),
background: laneTone(track, lit),
/* the targeted track: an accent bar down its left edge */
boxShadow: [chatLit ? CHAT_RING : '', targeted ? 'inset 2px 0 0 var(--tl-accent)' : ''].filter(Boolean).join(', ') || undefined,
@@ -2203,7 +2205,7 @@ export const Timeline = React.memo(function Timeline({
cursor: canReorder ? (liftingHead ? 'grabbing' : 'grab') : undefined,
}}
>
- <span className={`flex min-w-0 items-center gap-1 ${named ? 'w-full justify-self-stretch pl-0.5' : ''}`}>
+ <span className="flex min-w-0 items-center gap-1">
{track.badge ? (
<span
className="flex items-center justify-center rounded-[3px] font-semibold tabular-nums"
@@ -2228,25 +2230,6 @@ export const Timeline = React.memo(function Timeline({
<LaneIcon size={TYPE_BOX} />
</span>
)}
- {renamingHere ? (
- <input
- autoFocus
- defaultValue={given ?? ''}
- aria-label={t('timeline.renameTrack')}
- placeholder={track.badge ?? ''}
- maxLength={40}
- onPointerDown={(e) => e.stopPropagation()}
- onKeyDown={(e) => {
- e.stopPropagation();
- if (e.key === 'Enter') { onRenameTrack?.(track.docIndex!, e.currentTarget.value); setRenaming(null); }
- if (e.key === 'Escape') setRenaming(null);
- }}
- onBlur={(e) => { if (renamingRef.current === track.docIndex) { onRenameTrack?.(track.docIndex!, e.currentTarget.value); setRenaming(null); } }}
- className="h-[18px] min-w-0 flex-1 rounded-[3px] bg-[var(--bg)] px-1 text-[11px] text-[var(--text)] outline-none ring-1 ring-[var(--tl-accent)]"
- />
- ) : given ? (
- <span className="min-w-0 truncate text-[11px] font-medium" style={{ color: TL.text }} data-track-name="">{given}</span>
- ) : null}
</span>
{onEditBlocks ? <>
<TrackHeadButton
@@ -2282,10 +2265,30 @@ export const Timeline = React.memo(function Timeline({
{solo ? (track.role === 'mg' || track.docIndex == null ? <span aria-hidden /> : (
<SoloButton on={solo.tracks.has(track.docIndex)} onToggle={(only) => solo.onToggle(track.docIndex!, only)} />
)) : null}
+ {/* the track's name, on its own line under the badge and the toggles */}
+ {nameLine && renamingHere ? (
+ <input
+ autoFocus
+ defaultValue={given ?? ''}
+ aria-label={t('timeline.renameTrack')}
+ placeholder={track.badge ?? ''}
+ maxLength={40}
+ onPointerDown={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === 'Enter') { onRenameTrack?.(track.docIndex!, e.currentTarget.value); setRenaming(null); }
+ if (e.key === 'Escape') setRenaming(null);
+ }}
+ onBlur={(e) => { if (renamingRef.current === track.docIndex) { onRenameTrack?.(track.docIndex!, e.currentTarget.value); setRenaming(null); } }}
+ className="col-span-full h-[16px] w-full min-w-0 justify-self-stretch rounded-[3px] bg-[var(--bg)] px-1 text-[11px] text-[var(--text)] outline-none ring-1 ring-[var(--tl-accent)]"
+ />
+ ) : nameLine && given ? (
+ <span className="col-span-full w-full min-w-0 justify-self-stretch truncate px-1 text-[10.5px] font-medium leading-[14px]" style={{ color: TL.text }} data-track-name="">{given}</span>
+ ) : null}
{onResizeTrack && track.docIndex != null ? <TrackResizeHandle height={h} onResize={(height, done) => onResizeTrack(track, height, done)} /> : null}
</div>
);
- }), [tracks, t, laneOrder, onEditBlocks, startLaneReorder, toggleTrack, selectedLanes, openHeadMenu, chatTrack, trackNames, targetLane, renaming, named, onRenameTrack, solo, onResizeTrack]);
+ }), [tracks, t, laneOrder, onEditBlocks, startLaneReorder, toggleTrack, selectedLanes, openHeadMenu, chatTrack, trackNames, targetLane, renaming, onRenameTrack, solo, onResizeTrack]);
/* row backgrounds are fixed to the view and only follow vertical scroll; the clips move horizontally above them */
const laneSkins = React.useMemo(() => tracks.map((track) => (
diff --git a/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx b/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx
index 15f8fe5..c2e787f 100644
--- a/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx
+++ b/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx
@@ -18,6 +18,11 @@ import React from 'react';
import { createPortal } from 'react-dom';
import { useT } from '@/i18n';
+import { studioHost } from '@/lib/host';
+import { MenuSelect } from '@/components/MenuSelect';
+import { CustomFrame } from '@/components/FramePicker';
+import { FRAME_RATES } from '@/lib/timecode';
+import { api } from '@/api';
import {
CODEC_LABEL,
EXPORT_ALPHA_CODECS,
@@ -156,7 +161,8 @@ function saveSettings(s: Settings): void {
const SHORT_EDGES = [480, 720, 1080, 1440, 2160];
const STILL_EDGES = [720, 1080, 1440, 2160];
-const FPS_CHOICES = [24, 25, 30, 50, 60];
+/** A video's rates: the project's list (lib/timecode), one spec for both. */
+const FPS_CHOICES = FRAME_RATES;
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'];
@@ -164,7 +170,6 @@ 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];
-const NLE_FPS_CHOICES = [24, 25, 29.97, 30, 50, 60];
const VIDEO_SRC = /\.(mp4|m4v|mov|webm|mkv|avi|ogv)$/i;
/** Whether this machine's ffmpeg makes a codec (unknown until the server answers: assumed yes). */
@@ -482,6 +487,24 @@ export function ExportCenter(props: ExportCenterProps) {
patch('folder', next === defaultFolder ? '' : next);
setFolderDraft(null);
};
+ /* the app's own folder dialog where there is an app (lib/host.ts `folders`); in a browser, the path typed */
+ /* the system's folder dialog: the app's own where there is an app (lib/host.ts `folders`), else the one Studio opens
+ on this computer for the page; only where neither can, the path is typed */
+ const [picking, setPicking] = React.useState(false);
+ const changeFolder = async () => {
+ if (picking) return;
+ setPicking(true);
+ try {
+ const ask = { title: t('exportCenter.pickTitle'), button: t('exportCenter.pickButton'), ...(folder ? { at: folder } : {}) };
+ const pick = studioHost?.folders?.pick;
+ const picked = pick ? await pick(ask) : await api.pickFolder(ask.title, ask.at);
+ if (picked) patch('folder', picked === defaultFolder ? '' : picked);
+ } catch {
+ setFolderDraft(folder);
+ } finally {
+ setPicking(false);
+ }
+ };
if (!open || typeof document === 'undefined') return null;
@@ -503,8 +526,10 @@ export function ExportCenter(props: ExportCenterProps) {
onClick={(e) => e.stopPropagation()}
>
{/* left: destinations */}
- <nav className="flex w-[212px] shrink-0 flex-col gap-0.5 border-r border-[var(--border-soft)] bg-[var(--surface-2)] p-3">
- <h2 className="px-2 pb-2 pt-1 text-[15px] font-semibold tracking-tight text-[var(--text)]">{t('exportCenter.title')}</h2>
+ {/* the list scrolls when the window is short; the note under it stays whole */}
+ <nav className="flex min-h-0 w-[212px] shrink-0 flex-col border-r border-[var(--border-soft)] bg-[var(--surface-2)]">
+ <h2 className="shrink-0 px-5 pb-2 pt-4 text-[15px] font-semibold tracking-tight text-[var(--text)]">{t('exportCenter.title')}</h2>
+ <div className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto px-3 pb-2">
{DESTS.map((d) => {
const on = dest === d.id;
return (
@@ -527,7 +552,8 @@ export function ExportCenter(props: ExportCenterProps) {
</button>
);
})}
- <div className="mt-auto px-2 pt-3 text-[10.5px] leading-relaxed text-[var(--text-faint)]">
+ </div>
+ <div className="shrink-0 border-t border-[var(--border-soft)] px-5 py-3 text-[10.5px] leading-relaxed text-[var(--text-faint)]">
{t('exportCenter.engineDesktop')}
</div>
</nav>
@@ -652,13 +678,12 @@ export function ExportCenter(props: ExportCenterProps) {
</Field>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<Field label={t('exportCenter.fps')}>
- <Chips<number | 'source'>
- value={s.video.fps === projectFps ? 'source' : s.video.fps}
- options={[
- { value: 'source' as const, label: `${projectFps}`, sub: t('exportCenter.fpsProject') },
- ...FPS_CHOICES.filter((f) => f !== projectFps).map((f) => ({ value: f, label: `${f}` })),
- ]}
- onChange={(fps) => patch('video', { fps })}
+ <FpsSelect
+ label={t('exportCenter.fps')}
+ value={fpsFor(s.video.fps)}
+ rates={FPS_CHOICES}
+ own={{ fps: projectFps, note: t('exportCenter.fpsProject') }}
+ onPick={(fps) => patch('video', { fps: fps === projectFps ? 'source' : fps })}
/>
</Field>
{!(videoCodec.startsWith('prores') || videoCodec === 'png') && (
@@ -752,7 +777,13 @@ export function ExportCenter(props: ExportCenterProps) {
</Field>
)}
<Field label={t('exportCenter.fps')}>
- <Chips value={s.alpha.fps} options={FPS_CHOICES.map((f) => ({ value: f, label: `${f}` }))} onChange={(fps) => patch('alpha', { fps })} />
+ <FpsSelect
+ label={t('exportCenter.fps')}
+ value={s.alpha.fps}
+ rates={FPS_CHOICES}
+ own={{ fps: projectFps, note: t('exportCenter.fpsProject') }}
+ onPick={(fps) => patch('alpha', { fps })}
+ />
</Field>
</div>
{alphaCodec !== 'png' && (
@@ -765,13 +796,12 @@ export function ExportCenter(props: ExportCenterProps) {
{dest === 'nle' && (
<>
<Field label={t('exportCenter.fps')}>
- <Chips<number | 'source'>
- value={s.nle.fps === 'source' && !nleSourceFps ? 30 : s.nle.fps}
- options={[
- ...(nleSourceFps ? [{ value: 'source' as const, label: `${nleSourceFps}`, sub: t('exportCenter.fpsSource') }] : []),
- ...NLE_FPS_CHOICES.filter((f) => f !== nleSourceFps).map((f) => ({ value: f, label: `${f}` })),
- ]}
- onChange={(fps) => patch('nle', { fps })}
+ <FpsSelect
+ label={t('exportCenter.fps')}
+ value={s.nle.fps === 'source' ? (nleSourceFps ?? 30) : s.nle.fps}
+ rates={NLE_FPS}
+ own={nleSourceFps ? { fps: nleSourceFps, note: t('exportCenter.fpsSource') } : null}
+ onPick={(fps) => patch('nle', { fps: fps === nleSourceFps ? 'source' : fps })}
/>
</Field>
<Field label={t('exportCenter.nleAudio')}>
@@ -1031,60 +1061,67 @@ export function ExportCenter(props: ExportCenterProps) {
</div>
</div>
- {/* bottom: where it goes, the summary, the primary button */}
- <div className="shrink-0 border-t border-[var(--border-soft)] px-5 py-3.5">
- <div className="mb-3 flex items-center gap-2 text-[12px]">
- <FolderOpen size={14} className="shrink-0 text-[var(--text-faint)]" />
- <span className="shrink-0 text-[var(--text-muted)]">{t('exportCenter.saveTo')}</span>
- {folderDraft != null ? (
- <input
- autoFocus
- value={folderDraft}
- spellCheck={false}
- aria-label={t('exportCenter.saveTo')}
- onChange={(e) => setFolderDraft(e.target.value)}
- onFocus={(e) => e.currentTarget.select()}
- onBlur={commitFolder}
- onKeyDown={(e) => {
- if (e.key === 'Enter') { e.preventDefault(); commitFolder(); }
- if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setFolderDraft(null); }
- }}
- className="h-6 min-w-0 flex-1 rounded-md border border-[var(--border)] bg-[var(--bg)] px-1.5 font-mono text-[11.5px] text-[var(--text)] outline-none focus:border-[var(--text-faint)]"
- />
- ) : (
- <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-[var(--text)]" title={folder}>{folder || '—'}</span>
- )}
- {folderDraft == null && (
- <button
- type="button"
- onClick={() => setFolderDraft(folder)}
- className="shrink-0 rounded-md px-2 py-1 text-[12px] font-medium text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)]"
- >
- {t('exportCenter.change')}
- </button>
- )}
- </div>
- <div className="flex items-center gap-3">
- <div className="min-w-0 flex-1 text-[12px] leading-relaxed">
+ {/* bottom: where it goes (the folder, a click changes it), what comes out, and the primary button */}
+ <div className="flex shrink-0 flex-wrap items-center gap-x-4 gap-y-3 border-t border-[var(--border-soft)] bg-[color-mix(in_srgb,var(--surface-2)_45%,transparent)] px-5 py-3.5">
+ {folderDraft != null ? (
+ <input
+ autoFocus
+ value={folderDraft}
+ spellCheck={false}
+ aria-label={t('exportCenter.saveTo')}
+ onChange={(e) => setFolderDraft(e.target.value)}
+ onFocus={(e) => e.currentTarget.select()}
+ onBlur={commitFolder}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') { e.preventDefault(); commitFolder(); }
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setFolderDraft(null); }
+ }}
+ className="h-10 min-w-[200px] flex-1 rounded-lg border border-[var(--border)] bg-[var(--bg)] px-3 font-mono text-[12px] text-[var(--text)] outline-none focus:border-[var(--text-faint)]"
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={() => void changeFolder()}
+ disabled={picking}
+ title={folder}
+ aria-label={`${t('exportCenter.saveTo')}: ${folder || '—'}. ${t('exportCenter.change')}`}
+ className="group -ml-2 flex min-w-0 max-w-[340px] flex-1 items-center gap-2.5 rounded-lg px-2 py-1.5 text-left transition hover:bg-[var(--bg-hover)] disabled:opacity-60"
+ >
+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-[var(--surface-2)] text-[var(--text-muted)] ring-1 ring-[var(--border)] transition group-hover:text-[var(--text)]">
+ {picking ? <Loader2 size={15} className="animate-spin" /> : <FolderOpen size={15} />}
+ </span>
+ <span className="flex min-w-0 flex-col">
+ <span className="flex min-w-0 items-baseline gap-1.5">
+ <span className="shrink-0 text-[11px] text-[var(--text-faint)]">{t('exportCenter.saveTo')}</span>
+ <span className="truncate text-[13px] font-medium text-[var(--text)]">{folderName(folder) || '—'}</span>
+ </span>
+ <span className="truncate text-[11px] text-[var(--text-faint)] group-hover:text-[var(--text-muted)]">{t('exportCenter.change')}</span>
+ </span>
+ </button>
+ )}
+ <div className="ml-auto flex min-w-0 items-center gap-4">
+ <div className="min-w-0 text-right text-[12px] leading-snug">
{result ? (
<span className={result.ok ? 'text-[var(--ok)]' : 'text-[var(--err)]'}>{result.text}</span>
) : emptyReason ? (
<span className="text-[var(--text-faint)]">{emptyReason}</span>
) : (
- <span className="text-[var(--text-muted)]">
+ <>
{/* a project is not a length of film: its size only */}
- {dest === 'project'
- ? (estText ? `${t('exportCenter.approx')} ${estText}` : '')
- : t('exportCenter.summary').replace('{n}', String(fileCount)).replace('{dur}', formatFilmTime(outMs))}
- {dest !== 'project' && estText ? ` · ${t('exportCenter.approx')} ${estText}` : ''}
- </span>
+ {dest !== 'project' ? (
+ <span className="block text-[var(--text-muted)] tabular-nums">
+ {t('exportCenter.summary').replace('{n}', String(fileCount)).replace('{dur}', formatFilmTime(outMs))}
+ </span>
+ ) : null}
+ {estText ? <span className="block text-[11px] text-[var(--text-faint)] tabular-nums">{`${t('exportCenter.approx')} ${estText}`}</span> : null}
+ </>
)}
</div>
<button
type="button"
onClick={() => void queue(requests)}
disabled={disabled}
- className="flex h-10 shrink-0 items-center gap-2 rounded-xl bg-[var(--text)] px-4 text-[13.5px] font-medium text-[var(--bg)] transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
+ className="flex h-10 shrink-0 items-center gap-2 rounded-xl bg-[var(--text)] px-6 text-[13.5px] font-medium text-[var(--bg)] transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
>
{working ? <Loader2 size={14} className="animate-spin" /> : null}
{primaryLabel}
@@ -1100,6 +1137,11 @@ export function ExportCenter(props: ExportCenterProps) {
/* ── small parts ────────────────────────────────────────────────────────── */
+/** 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;
+}
+
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex flex-col gap-2">
@@ -1141,13 +1183,37 @@ function OptionCard({ on, disabled, title, desc, onClick }: {
);
}
+/**
+ * A frame rate, from an editor's list: the film's own (or its footage's) is in it whatever it is, said beside its
+ * number ("30 fps · project").
+ */
+function FpsSelect({ label, value, rates, own, onPick }: {
+ label: string;
+ value: number;
+ rates: readonly number[];
+ own: { fps: number; note: string } | null;
+ onPick: (fps: number) => void;
+}) {
+ 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))}
+ />
+ );
+}
+
function Chips<V extends string | number>({ value, options, onChange }: {
value: V;
options: readonly { value: V; label: string; sub?: string }[];
onChange: (v: V) => void;
}) {
return (
- <div className="flex flex-wrap gap-1.5">
+ <div className="flex flex-wrap items-start gap-1.5">
{options.map((o) => {
const on = o.value === value;
return (
@@ -1277,7 +1343,7 @@ function FrameField({ value, fill, current, stage, onChange, onFill, t }: {
return (
<Field label={t('exportCenter.frame')}>
<div className="flex flex-wrap gap-1.5">
- {FILM_FRAME_IDS.map((f) => {
+ {[...FILM_FRAME_IDS, ...(FILM_FRAME_IDS.includes(resolved) ? [] : [resolved])].map((f) => {
const on = resolved === f;
return (
<button
@@ -1295,6 +1361,8 @@ function FrameField({ value, fill, current, stage, onChange, onFill, t }: {
);
})}
</div>
+ <CustomFrame value={resolved} onPick={(f) => onChange(f === current ? 'current' : f)}
+ className="-mx-2 max-w-[260px] rounded-lg" />
{differs && (
<Segmented
value={fill}
diff --git a/packages/openfilm/studio/ui/src/components/useBlockDrag.ts b/packages/openfilm/studio/ui/src/components/useBlockDrag.ts
index f75617d..ebc01d3 100644
--- a/packages/openfilm/studio/ui/src/components/useBlockDrag.ts
+++ b/packages/openfilm/studio/ui/src/components/useBlockDrag.ts
@@ -25,6 +25,8 @@ import {
flushShiftMs,
groupLaneShift,
moveDestFor,
+ moveEditMode,
+ rangeOverlaps,
snapTargetsFor,
SNAP_THRESHOLD_PX,
trimFence,
@@ -384,7 +386,6 @@ export function useBlockDrag(opts: {
/* a move: the clip follows the hand; where it lands, and what it does to what is there, is the plan's */
const offsetY = ev.clientY - startY + scrolledY;
const hit = latest.current.laneHitAtY?.(ev.clientY) ?? { lane: homeLaneIndex, band: 'body' as const };
- const editMode: EditMode = p.magnet !== altNow ? 'insert' : 'overwrite';
const out = applyDrag(geom, 'move', deltaMs, targets, pxPerMs, block.room, crowd);
const grouped = crowd.length > 0 && homeLaneIndex >= 0;
const shift = grouped
@@ -408,9 +409,16 @@ export function useBlockDrag(opts: {
* snapping on, for one clip, overwriting.
*/
const destLane = drop.action === 'move' ? singleLanes.find((l) => l.docIndex === drop.trackIndex) : singleLanes[homeLaneIndex];
- const settle = !grouped && snapping && editMode === 'overwrite' && drop.action !== 'insert'
+ const flush = !grouped && snapping && drop.action !== 'insert'
? flushShiftMs({ startMs: out.startMs, endMs: out.endMs }, destLane?.occupied ?? [], SNAP_THRESHOLD_PX / pxPerMs)
: null;
+ /* along its own track (alone, or with its linked clips, none changing track), onto another clip: it goes in
+ between instead of cutting it (moveEditMode) */
+ const alongOwnTrack = grouped ? shift.ok && shift.delta === 0 : drop.action === 'stay';
+ const wouldLand = { startMs: out.startMs + (flush?.shiftMs ?? 0), endMs: out.endMs + (flush?.shiftMs ?? 0) };
+ const overlaps = alongOwnTrack && rangeOverlaps(wouldLand, singleLanes[homeLaneIndex]?.occupied ?? []);
+ const editMode: EditMode = moveEditMode({ magnet: p.magnet, alt: altNow, overlaps });
+ const settle = editMode === 'overwrite' ? flush : null;
const to = new Map<string, TrackDest>();
if (drop.action === 'move') to.set(block.clipId!, drop.trackIndex);
if (drop.action === 'insert') to.set(block.clipId!, { insert: drop.at });
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index f34583a..8056e0a 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -46,16 +46,18 @@ export const en = {
desktop: {
title: 'OpenFilm for desktop',
tagline: 'Your agent and your film, side by side.',
- intro: 'The same Studio as an app of its own, with your agent in a chat beside the film. Ask, watch each change land, and fix anything by hand.',
+ intro: 'Studio as a desktop app, with your agent in a chat beside the film and wired into every part of it. Ask, watch each change land, and fix anything by hand.',
worksWith: 'Works with',
orOwnKey: 'or your own API key',
features: {
- chat: { title: 'Talk beside the film', body: 'Claude Code, Codex, Gemini CLI and the others, in the same window. Each change shows in the picture as it lands.' },
- point: { title: 'Point at anything', body: 'Put a clip, a layer or a moment in your message. Click one in the chat to jump to it.' },
- drop: { title: 'Drop in your media', body: 'Drag footage, pictures or sound into the chat: they go straight into the film’s folder.' },
- setup: { title: 'Nothing to set up', body: 'No terminal. It finds the agents on your computer and fetches the tools films need by itself.' },
- history: { title: 'Every conversation kept', body: 'Each film keeps its chats, so you and your agent pick up where you left off.' },
- launch: { title: 'Opens with a double-click', body: 'On your last film, with smoother playback, and it updates itself.' },
+ sync: { title: 'Two-way with the editor', body: 'Put a clip, a layer, a region of the picture or a media file in your message, and click any clip your agent names to jump to it in Studio.' },
+ live: { title: 'Changes land live', body: 'Every edit shows on the picture and the timeline as it’s written. Adjust it by hand, or step back in Version history.' },
+ drop: { title: 'Drop in your media', body: 'Drag footage, pictures or sound into the chat: they go straight into the film’s folder, ready to use.' },
+ agents: { title: 'Any agent, one switch away', body: 'Claude Code, Codex, Gemini CLI, Copilot, Cursor and more, found on your computer. Switch in the chat, or use your own API key.' },
+ speed: { title: 'Faster preview and export', body: 'A pinned rendering engine for smooth playback, and exports on your computer’s hardware video encoder when it has one.' },
+ setup: { title: 'No terminal, no dependencies', body: 'No Node, npm or package versions to manage: ffmpeg and the renderer are built in and tested with Studio.' },
+ updates: { title: 'Always up to date', body: 'Updates download in the background and install on restart, never in the middle of an export or a reply.' },
+ history: { title: 'Every film keeps its chats', body: 'It opens on your last film with its conversations kept, so you and your agent pick up where you left off.' },
},
picture: {
clip: 'Title · 0:02–0:06',
@@ -73,12 +75,16 @@ export const en = {
gone: 'Studio has stopped. Run this in a terminal, or ask your agent to open OpenFilm again: this page reconnects by itself.',
goneApp: 'Studio has stopped. Quit and reopen the OpenFilm app to bring it back.',
copied: 'Copied',
+ lockedTitle: 'This browser isn’t signed in to Studio',
+ lockedBody: 'Studio is running, but it only lets in a browser that opened it once with its key. Open the full address `openfilm open` (or `pnpm dev`) printed, the one with ?key= in it; after that, this browser can use Studio’s address as it is.',
+ lockedHow: 'To get it again, run',
},
projects: {
newProject: 'New project',
localProjectFailed: 'Couldn’t create the project. Please retry.',
revealFolder: `Reveal in ${FILES}`,
folderAll: 'All',
+ folderUp: 'Up one level',
untitledFolder: 'Untitled folder',
folderCount: '{n} projects',
folderCountOne: '1 project',
@@ -105,7 +111,7 @@ export const en = {
agentRunningDeleteMany: 'An agent is running in {n} of these projects. Stop it first, then delete them.',
removeFromList: 'Remove from list',
removeTitle: 'Remove from the list?',
- removeDesc: 'Its folder is no longer there, so it is only taken off the list. Nothing on disk changes.',
+ removeDesc: 'Its folder is already gone, and everything a project keeps (versions, chats) was in it, so nothing is left to delete. This takes it off the list.',
removeAlso: 'Projects whose folder is gone are only taken off the list.',
getFromGitHub: 'Get from GitHub…',
importFrom: 'Import from',
@@ -191,7 +197,7 @@ export const en = {
sortNewest: 'Newest',
sortOldest: 'Oldest',
sortDuration: 'Longest',
- sortTitle: 'Title',
+ sortTitle: 'Name (A–Z)',
viewLabel: 'View',
viewCards: 'Card view',
viewList: 'List view',
@@ -332,6 +338,8 @@ export const en = {
rangePart: 'A part',
saveTo: 'Save to',
change: 'Change…',
+ pickTitle: 'Choose where to save exports',
+ pickButton: 'Choose',
summary: '{n} file(s) · {dur}',
approx: 'about',
emptyFilm: 'The film is empty — add a clip first.',
@@ -677,6 +685,11 @@ export const en = {
close: 'Close',
results: 'Results',
moveFailed: 'Could not move it there.',
+ moveAskTitle: 'Some paths in it can’t be updated',
+ moveAskBody: 'Studio rewrites the links it can read when a page moves. These are made while the page runs, so they will still point at the old place: check them after the move, or ask your agent to fix them.',
+ moveAskConfirm: 'Move anyway',
+ viewGrid: 'Show as a grid',
+ viewList: 'Show as a list',
moveTaken: '{folder} already has a file named “{name}”. Rename one of them first.',
emptyFolder: 'This folder is empty',
deleteFolderTitle: 'Delete the folder "{name}"?',
@@ -730,10 +743,16 @@ export const en = {
loopFilm: "Loop",
play: 'Play',
pause: 'Pause',
- frame: 'Delivery frame',
- frameNative: 'Native',
+ frameCustom: 'Custom',
+ ratioOriginal: 'Fit (original)',
+ ratioPhone: '5.8″ phone',
+ ratioHint: { wide: '(YouTube)', tall: '(TikTok)' },
+ frameCustomW: 'Width',
+ frameCustomH: 'Height',
+ frameCustomApply: 'Use this ratio',
+ frameCustomRange: 'From 1:4 to 4:1',
canvas: 'Aspect ratio',
- canvasNote: "Sets this film's canvas. Nothing has been made yet — switch freely.",
+ canvasNote: 'The film’s canvas. Another shape keeps its short side, and the film is scaled into it whole, centered.',
fullscreen: 'Full screen',
},
inspector: {
@@ -960,8 +979,12 @@ export const en = {
film: 'Film',
stage: 'Stage',
stageShape: 'Stage shape',
- deliveryFrame: 'Delivery frame',
- stageFixed: 'The stage stays as the film was made: a delivery frame fits it into another shape on export.',
+ stageFixed: 'Another shape keeps the canvas’s short side, and the film is scaled into it whole, centered. Then ask your agent to lay it out again for the new canvas.',
+ redesignOpen: 'Ask your agent to lay it out for this canvas',
+ redesignBody: 'Paste these words in the chat: your agent lays out every page and clip again for the canvas as it is now.',
+ redesignAsk: 'This film’s canvas is now {ratio} ({size}). Lay out every page and clip again for it, and check each scene with look.',
+ redesignCopy: 'Copy the request',
+ redesignCopied: 'Copied: paste it in the chat',
filmInfo: 'Contents',
tracks: 'Tracks',
clipsCount: 'Clips',
@@ -1016,8 +1039,8 @@ export const en = {
subtitleLineGo: 'Go to {time}',
subtitleLineInLanguage: 'The line at {time}, in {lang}',
subtitleLineUntranslated: 'Not translated yet',
- subtitleLinesMakeOne: 'Make subtitles for a voice clip with no transcript',
- subtitleLinesMake: 'Make subtitles for {n} clips with no transcript',
+ subtitleLinesMakeOne: 'Make subtitles for a voice clip whose transcript is missing or out of date',
+ subtitleLinesMake: 'Make subtitles for {n} clips whose transcript is missing or out of date',
subtitleStyle: 'Subtitle style',
subtitleLanguageGroup: 'Subtitle language',
subtitleLanguageOriginal: 'Original',
@@ -1216,6 +1239,8 @@ export const en = {
hideRow: 'Hide the subtitle row on the timeline',
name: 'Subtitles',
add: 'Add a subtitle at the playhead',
+ hide: 'Hide subtitle row',
+ hideNote: 'Turn it back on in Subtitle style › Edit on timeline.',
split: 'Split at the playhead',
splitWhere: 'Put the playhead inside the subtitle, away from its edges',
merge: 'Merge with the next',
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index 74b1f83..78b495f 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -45,16 +45,18 @@ export const es: Words = {
desktop: {
title: 'OpenFilm para escritorio',
tagline: 'Tu agente y tu película, uno al lado del otro.',
- intro: 'El mismo Studio como una app propia, con tu agente en un chat junto a la película. Pide, mira cómo llega cada cambio y corrige lo que quieras a mano.',
+ intro: 'Studio como app de escritorio, con tu agente en un chat junto a la película y conectado a cada parte del editor. Pide, mira cómo llega cada cambio y retoca lo que quieras a mano.',
worksWith: 'Funciona con',
orOwnKey: 'o tu propia clave de API',
features: {
- chat: { title: 'Habla junto a la película', body: 'Claude Code, Codex, Gemini CLI y los demás, en la misma ventana. Cada cambio aparece en la imagen en cuanto llega.' },
- point: { title: 'Señala lo que sea', body: 'Pon un clip, una capa o un momento en tu mensaje. Haz clic en uno en el chat para ir hasta él.' },
- drop: { title: 'Suelta tus medios', body: 'Arrastra metraje, imágenes o sonido al chat: van directos a la carpeta de la película.' },
- setup: { title: 'Nada que configurar', body: 'Sin terminal. Encuentra los agentes de tu ordenador y consigue sola las herramientas que necesitan las películas.' },
- history: { title: 'Cada conversación, guardada', body: 'Cada película guarda sus chats, así tú y tu agente seguís donde lo dejasteis.' },
- launch: { title: 'Se abre con doble clic', body: 'En tu última película, con una reproducción más fluida, y se actualiza sola.' },
+ sync: { title: 'Conectado al editor en ambos sentidos', body: 'Pon un clip, una capa, una zona de la imagen o un archivo en tu mensaje, y haz clic en cualquier clip que nombre tu agente para ir a él en Studio.' },
+ live: { title: 'Cambios en directo', body: 'Cada edición aparece en la imagen y en la línea de tiempo en cuanto se escribe. Ajústala a mano o vuelve atrás en el historial de versiones.' },
+ drop: { title: 'Suelta tus medios', body: 'Arrastra metraje, imágenes o sonido al chat: van directos a la carpeta de la película, listos para usar.' },
+ agents: { title: 'Cualquier agente, a un clic', body: 'Claude Code, Codex, Gemini CLI, Copilot, Cursor y más, detectados en tu ordenador. Cámbialos en el chat o usa tu propia clave de API.' },
+ speed: { title: 'Vista previa y exportación más rápidas', body: 'Un motor de renderizado fijo para una reproducción fluida, y exportaciones con el codificador de vídeo por hardware de tu ordenador cuando lo tiene.' },
+ setup: { title: 'Sin terminal ni dependencias', body: 'Nada de Node, npm ni versiones de paquetes: ffmpeg y el renderizador vienen incluidos y probados con Studio.' },
+ updates: { title: 'Siempre al día', body: 'Las actualizaciones se descargan en segundo plano y se instalan al reiniciar, nunca en mitad de una exportación o una respuesta.' },
+ history: { title: 'Cada película guarda sus chats', body: 'Se abre en tu última película con sus conversaciones, para que tú y tu agente sigáis donde lo dejasteis.' },
},
picture: {
clip: 'Título · 0:02–0:06',
@@ -72,12 +74,16 @@ export const es: Words = {
gone: 'Studio se ha detenido. Ejecuta esto en una terminal o pide a tu agente que vuelva a abrir OpenFilm: esta página se reconecta sola.',
goneApp: 'Studio se ha detenido. Cierra y vuelve a abrir la app OpenFilm para recuperarlo.',
copied: 'Copiado',
+ lockedTitle: 'Este navegador no ha entrado en Studio',
+ lockedBody: 'Studio está en marcha, pero solo deja entrar a un navegador que lo abrió una vez con su clave. Abre la dirección completa que mostró `openfilm open` (o `pnpm dev`), la que lleva ?key=; después, este navegador puede usar la dirección de Studio tal cual.',
+ lockedHow: 'Para obtenerla de nuevo, ejecuta',
},
projects: {
newProject: 'Nuevo proyecto',
localProjectFailed: 'No se pudo crear el proyecto. Inténtalo de nuevo.',
revealFolder: `Mostrar en ${FILES}`,
folderAll: 'Todos',
+ folderUp: 'Subir un nivel',
untitledFolder: 'Carpeta sin título',
folderCount: '{n} proyectos',
folderCountOne: '1 proyecto',
@@ -104,7 +110,7 @@ export const es: Words = {
agentRunningDeleteMany: 'Un agente está trabajando en {n} de estos proyectos. Detenlo primero y luego elimínalos.',
removeFromList: 'Quitar de la lista',
removeTitle: '¿Quitar de la lista?',
- removeDesc: 'Su carpeta ya no existe, así que solo se quita de la lista. No cambia nada en el disco.',
+ removeDesc: 'Su carpeta ya no existe, y todo lo que guarda un proyecto (versiones, chats) estaba en ella, así que no queda nada que borrar. Esto lo quita de la lista.',
removeAlso: 'Los proyectos cuya carpeta ya no existe solo se quitan de la lista.',
getFromGitHub: 'Obtener de GitHub…',
importFrom: 'Importar desde',
@@ -190,7 +196,7 @@ export const es: Words = {
sortNewest: 'Más recientes',
sortOldest: 'Más antiguos',
sortDuration: 'Más largos',
- sortTitle: 'Título',
+ sortTitle: 'Nombre (A–Z)',
viewLabel: 'Vista',
viewCards: 'Vista de tarjetas',
viewList: 'Vista de lista',
@@ -331,6 +337,8 @@ export const es: Words = {
rangePart: 'Una parte',
saveTo: 'Guardar en',
change: 'Cambiar…',
+ pickTitle: 'Elige dónde guardar las exportaciones',
+ pickButton: 'Elegir',
summary: '{n} archivo(s) · {dur}',
approx: 'aprox.',
emptyFilm: 'La película está vacía: añade primero un clip.',
@@ -676,6 +684,11 @@ export const es: Words = {
close: 'Cerrar',
results: 'Resultados',
moveFailed: 'No se pudo mover ahí.',
+ moveAskTitle: 'Algunas rutas no se pueden actualizar',
+ moveAskBody: 'Al mover una página, Studio reescribe los enlaces que puede leer. Estos se construyen mientras la página se ejecuta, así que seguirán apuntando al sitio anterior: revísalos después o pide a tu agente que los corrija.',
+ moveAskConfirm: 'Mover igualmente',
+ viewGrid: 'Ver en cuadrícula',
+ viewList: 'Ver en lista',
moveTaken: '{folder} ya tiene un archivo llamado “{name}”. Cambia antes el nombre de uno de ellos.',
emptyFolder: 'Esta carpeta está vacía',
deleteFolderTitle: '¿Eliminar la carpeta "{name}"?',
@@ -729,10 +742,16 @@ export const es: Words = {
loopFilm: "Bucle",
play: 'Reproducir',
pause: 'Pausa',
- frame: 'Encuadre de entrega',
- frameNative: 'Nativo',
+ frameCustom: 'Personalizado',
+ ratioOriginal: 'Ajustar (original)',
+ ratioPhone: 'Móvil 5,8″',
+ ratioHint: { wide: '(YouTube)', tall: '(TikTok)' },
+ frameCustomW: 'Ancho',
+ frameCustomH: 'Alto',
+ frameCustomApply: 'Usar esta proporción',
+ frameCustomRange: 'De 1:4 a 4:1',
canvas: 'Relación de aspecto',
- canvasNote: 'Define el lienzo de esta película. Aún no se hizo nada: cambia con libertad.',
+ canvasNote: 'El lienzo de la película. Otra forma mantiene su lado corto y la película se escala entera dentro, centrada.',
fullscreen: 'Pantalla completa',
},
inspector: {
@@ -959,8 +978,12 @@ export const es: Words = {
film: 'Película',
stage: 'Escenario',
stageShape: 'Forma del escenario',
- deliveryFrame: 'Marco de entrega',
- stageFixed: 'El escenario queda como se hizo la película: un marco de entrega la ajusta a otra forma al exportar.',
+ stageFixed: 'Otra forma mantiene el lado corto del lienzo y la película se escala entera dentro, centrada. Después pide a tu agente que la recomponga para el nuevo lienzo.',
+ redesignOpen: 'Pedir al agente que la componga para este lienzo',
+ redesignBody: 'Pega estas palabras en el chat: tu agente vuelve a componer cada página y clip para el lienzo actual.',
+ redesignAsk: 'El lienzo de esta película ahora es {ratio} ({size}). Vuelve a componer cada página y clip para él y revisa cada escena con look.',
+ redesignCopy: 'Copiar la petición',
+ redesignCopied: 'Copiada: pégala en el chat',
filmInfo: 'Contenido',
tracks: 'Pistas',
clipsCount: 'Clips',
@@ -1015,8 +1038,8 @@ export const es: Words = {
subtitleLineGo: 'Ir a {time}',
subtitleLineInLanguage: 'La línea en {time}, en {lang}',
subtitleLineUntranslated: 'Aún sin traducir',
- subtitleLinesMakeOne: 'Crear subtítulos para un clip de voz sin transcripción',
- subtitleLinesMake: 'Crear subtítulos para {n} clips sin transcripción',
+ subtitleLinesMakeOne: 'Crear subtítulos para un clip de voz sin transcripción o con una desactualizada',
+ subtitleLinesMake: 'Crear subtítulos para {n} clips sin transcripción o con una desactualizada',
subtitleStyle: 'Estilo de subtítulos',
subtitleLanguageGroup: 'Idioma de los subtítulos',
subtitleLanguageOriginal: 'Original',
@@ -1215,6 +1238,8 @@ export const es: Words = {
hideRow: 'Ocultar la fila de subtítulos de la línea de tiempo',
name: 'Subtítulos',
add: 'Añadir un subtítulo en el cabezal',
+ hide: 'Ocultar la pista de subtítulos',
+ hideNote: 'Vuelve a mostrarla en Estilo de subtítulos › Editar en la línea de tiempo.',
split: 'Dividir en el cabezal',
splitWhere: 'Pon el cabezal dentro del subtítulo, lejos de sus bordes',
merge: 'Unir con el siguiente',
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index dc6f6c9..849d6b7 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -45,16 +45,18 @@ export const ja: Words = {
desktop: {
title: 'OpenFilm デスクトップ版',
tagline: 'エージェントと映像を、並べて。',
- intro: '同じ Studio を独立したアプリとして。映像の隣に、あなたのエージェントと話せるチャットがあります。頼んで、変更が反映されるのを見て、どこでも手で直せます。',
+ intro: 'Studio をデスクトップアプリに。エージェントとのチャットが映像の隣にあり、エディターのあらゆる部分とつながっています。頼んで、変更を見届け、手でも直せます。',
worksWith: '対応',
orOwnKey: 'または自分の API キー',
features: {
- chat: { title: '映像の隣で会話', body: 'Claude Code、Codex、Gemini CLI なども同じウィンドウで。変更はその場でプレビューに反映されます。' },
- point: { title: 'なんでも指し示せる', body: 'クリップ、レイヤー、ある瞬間をメッセージに入れられます。チャット内のものをクリックすると、その場所へ移動します。' },
- drop: { title: '素材をドロップ', body: '映像、画像、サウンドをチャットにドラッグすると、そのまま映像のフォルダーに入ります。' },
- setup: { title: '設定は不要', body: 'ターミナルは不要。パソコンにあるエージェントを見つけ、映像づくりに必要なツールも自動で用意します。' },
- history: { title: '会話はすべて残る', body: '映像ごとにチャットが残るので、エージェントと前回の続きから始められます。' },
- launch: { title: 'ダブルクリックで起動', body: '前回の映像が開き、再生はより滑らかに、アップデートも自動です。' },
+ sync: { title: 'エディターと双方向に連携', body: 'クリップ、レイヤー、画面の範囲、素材ファイルをメッセージに入れられます。エージェントが挙げたクリップはクリックで Studio のその場所へ。' },
+ live: { title: '変更はその場で反映', body: '編集は書き込まれた瞬間にプレビューとタイムラインに表示。手で微調整も、バージョン履歴で戻すこともできます。' },
+ drop: { title: '素材はドロップするだけ', body: '映像、画像、サウンドをチャットにドラッグすると、映像のフォルダーに入りすぐ使えます。' },
+ agents: { title: '主要なエージェントを自由に切り替え', body: 'Claude Code、Codex、Gemini CLI、Copilot、Cursor など、パソコンにあるものを自動で検出。チャットで切り替えたり、自分の API キーを使ったりできます。' },
+ speed: { title: 'プレビューも書き出しも速く', body: '固定バージョンのレンダリングエンジンで再生は滑らか。ハードウェアのビデオエンコーダーがあれば書き出しに使います。' },
+ setup: { title: 'ターミナルも依存関係の管理も不要', body: 'Node や npm、パッケージのバージョン管理は不要。ffmpeg とレンダラーを内蔵し、Studio と一緒にテスト済みです。' },
+ updates: { title: 'いつも最新', body: 'アップデートはバックグラウンドで届き、再起動時にインストール。書き出しや返信の途中で止まることはありません。' },
+ history: { title: '映像ごとに会話を保存', body: '前回の映像が会話ごと開くので、エージェントと続きから始められます。' },
},
picture: {
clip: 'タイトル · 0:02–0:06',
@@ -72,12 +74,16 @@ export const ja: Words = {
gone: 'Studio が停止しました。ターミナルでこのコマンドを実行するか、エージェントに OpenFilm を開き直してもらってください。このページは自動で再接続します。',
goneApp: 'Studio が停止しました。OpenFilm アプリを終了して開き直すと復旧します。',
copied: 'コピーしました',
+ lockedTitle: 'このブラウザーは Studio にサインインしていません',
+ lockedBody: 'Studio は動いていますが、キー付きのアドレスで一度開いたブラウザーしか受け付けません。`openfilm open`(開発中は `pnpm dev`)が表示した ?key= 付きの完全なアドレスを開いてください。一度開けば、このブラウザーは Studio のアドレスをそのまま使えます。',
+ lockedHow: 'アドレスをもう一度得るには',
},
projects: {
newProject: '新規プロジェクト',
localProjectFailed: 'プロジェクトを作成できませんでした。もう一度お試しください。',
revealFolder: `${FILES}で表示`,
folderAll: 'すべて',
+ folderUp: '1 つ上へ',
untitledFolder: '名称未設定フォルダー',
folderCount: '{n} 件のプロジェクト',
folderCountOne: '1 件のプロジェクト',
@@ -104,7 +110,7 @@ export const ja: Words = {
agentRunningDeleteMany: '{n} 件のプロジェクトでエージェントが実行中です。先に停止してから削除してください。',
removeFromList: 'リストから削除',
removeTitle: 'リストから削除しますか?',
- removeDesc: 'フォルダーがすでに存在しないため、リストから外すだけです。ディスク上のものは何も変わりません。',
+ removeDesc: 'フォルダーはすでになく、プロジェクトが保存するもの(バージョン履歴やチャット)はすべてその中にあったため、削除すべきものは残っていません。リストから外します。',
removeAlso: 'フォルダーがなくなったプロジェクトは、リストから外すだけです。',
getFromGitHub: 'GitHub から取得…',
importFrom: 'インポート元',
@@ -190,7 +196,7 @@ export const ja: Words = {
sortNewest: '新しい順',
sortOldest: '古い順',
sortDuration: '長い順',
- sortTitle: 'タイトル',
+ sortTitle: '名前(A–Z)',
viewLabel: '表示',
viewCards: 'カード表示',
viewList: 'リスト表示',
@@ -331,6 +337,8 @@ export const ja: Words = {
rangePart: '一部',
saveTo: '保存先',
change: '変更…',
+ pickTitle: '書き出しの保存先を選択',
+ pickButton: '選択',
summary: '{n} ファイル · {dur}',
approx: '約',
emptyFilm: '映像が空です — 先にクリップを追加してください。',
@@ -676,6 +684,11 @@ export const ja: Words = {
close: '閉じる',
results: '結果',
moveFailed: 'そこへ移動できませんでした。',
+ moveAskTitle: '一部のパスは自動で更新できません',
+ moveAskBody: 'ページを移動すると、Studio は読み取れるリンクを書き換えます。次のものは実行時に組み立てられるため、古い場所を指したままになります。移動後に確認するか、エージェントに直してもらってください。',
+ moveAskConfirm: '移動する',
+ viewGrid: 'グリッドで表示',
+ viewList: 'リストで表示',
moveTaken: '{folder} にはすでに「{name}」という名前のファイルがあります。先にどちらかの名前を変更してください。',
emptyFolder: 'このフォルダーは空です',
deleteFolderTitle: 'フォルダー「{name}」を削除しますか?',
@@ -729,10 +742,16 @@ export const ja: Words = {
loopFilm: "ループ再生",
play: '再生',
pause: '一時停止',
- frame: '納品フレーム',
- frameNative: 'ネイティブ',
+ frameCustom: 'カスタム',
+ ratioOriginal: 'フィット(オリジナル)',
+ ratioPhone: '5.8 インチ',
+ ratioHint: { wide: '(YouTube)', tall: '(TikTok)' },
+ frameCustomW: '幅',
+ frameCustomH: '高さ',
+ frameCustomApply: 'この比率を使う',
+ frameCustomRange: '1:4 から 4:1 まで',
canvas: 'アスペクト比',
- canvasNote: 'この映像のキャンバスを設定します。まだ何も作られていないので、自由に切り替えられます。',
+ canvasNote: '映像のキャンバスです。比率を変えると短辺はそのままで、元の映像が全体が収まるよう縮小され中央に置かれます。',
fullscreen: '全画面表示',
},
inspector: {
@@ -959,8 +978,12 @@ export const ja: Words = {
film: 'フィルム',
stage: 'ステージ',
stageShape: 'ステージの比率',
- deliveryFrame: '書き出しフレーム',
- stageFixed: 'ステージは作ったときのままです。書き出しフレームで別の比率に収めます。',
+ stageFixed: '比率を変えると短辺はそのままで、元の映像が全体が収まるよう縮小され中央に置かれます。そのあとエージェントに新しいキャンバスで組み直してもらえます。',
+ redesignOpen: 'このキャンバスで組み直してもらう',
+ redesignBody: 'この文をチャットに貼り付けると、エージェントが今のキャンバスに合わせてすべてのページとクリップを組み直します。',
+ redesignAsk: 'この映像のキャンバスは {ratio}({size})になりました。これに合わせてすべてのページとクリップを組み直し、look で各シーンを確認してください。',
+ redesignCopy: '依頼文をコピー',
+ redesignCopied: 'コピーしました。チャットに貼り付けてください',
filmInfo: '内容',
tracks: 'トラック',
clipsCount: 'クリップ',
@@ -1015,8 +1038,8 @@ export const ja: Words = {
subtitleLineGo: '{time} へ移動',
subtitleLineInLanguage: '{time} の行({lang})',
subtitleLineUntranslated: '未翻訳',
- subtitleLinesMakeOne: '書き起こしのない音声クリップの字幕を作成',
- subtitleLinesMake: '書き起こしのない {n} 個のクリップの字幕を作成',
+ subtitleLinesMakeOne: '書き起こしがない、または古い音声クリップの字幕を作成',
+ subtitleLinesMake: '書き起こしがない、または古い {n} 個のクリップの字幕を作成',
subtitleStyle: '字幕スタイル',
subtitleLanguageGroup: '字幕の言語',
subtitleLanguageOriginal: 'オリジナル',
@@ -1215,6 +1238,8 @@ export const ja: Words = {
hideRow: 'タイムラインの字幕行を隠す',
name: '字幕',
add: '再生ヘッドの位置に字幕を追加',
+ hide: '字幕トラックを隠す',
+ hideNote: '「字幕スタイル › タイムラインで編集」から再び表示できます。',
split: '再生ヘッドで分割',
splitWhere: '再生ヘッドを字幕の内側、端から離れた位置に置いてください',
merge: '次の字幕と結合',
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 6270493..be82c99 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -45,16 +45,18 @@ export const ko: Words = {
desktop: {
title: '데스크톱용 OpenFilm',
tagline: '에이전트와 영상을 나란히.',
- intro: '같은 Studio를 독립된 앱으로. 영상 옆에서 내 에이전트와 채팅할 수 있습니다. 요청하고, 모든 변경이 반영되는 것을 지켜보고, 무엇이든 직접 고치세요.',
+ intro: 'Studio를 데스크톱 앱으로. 에이전트와의 대화가 영상 옆에 있고 편집기의 모든 부분과 연결됩니다. 요청하고, 변경을 지켜보고, 직접 고칠 수도 있습니다.',
worksWith: '지원',
orOwnKey: '또는 내 API 키',
features: {
- chat: { title: '영상 옆에서 대화', body: 'Claude Code, Codex, Gemini CLI 등을 같은 창에서. 변경은 반영되는 즉시 화면에 나타납니다.' },
- point: { title: '무엇이든 가리키기', body: '클립, 레이어 또는 한 순간을 메시지에 넣으세요. 채팅에서 클릭하면 그 위치로 이동합니다.' },
- drop: { title: '미디어 끌어다 놓기', body: '영상, 이미지, 사운드를 채팅에 끌어다 놓으면 바로 영상 폴더에 들어갑니다.' },
- setup: { title: '설정할 것 없음', body: '터미널이 필요 없습니다. 컴퓨터에 있는 에이전트를 찾고, 영상에 필요한 도구도 알아서 준비합니다.' },
- history: { title: '모든 대화 보관', body: '영상마다 대화가 남아 있어, 에이전트와 지난번에 멈춘 곳부터 이어 갑니다.' },
- launch: { title: '더블 클릭으로 실행', body: '마지막 영상이 바로 열리고, 더 부드럽게 재생되며, 자동으로 업데이트됩니다.' },
+ sync: { title: '편집기와 양방향 연결', body: '클립, 레이어, 화면 영역, 미디어 파일을 메시지에 넣으세요. 에이전트가 언급한 클립은 클릭 한 번으로 Studio의 해당 위치로 이동합니다.' },
+ live: { title: '변경 사항 실시간 반영', body: '모든 편집이 작성되는 즉시 화면과 타임라인에 나타납니다. 직접 다듬거나 버전 기록에서 되돌릴 수 있습니다.' },
+ drop: { title: '미디어는 끌어다 놓기만', body: '영상, 이미지, 사운드를 채팅에 끌어다 놓으면 바로 영상 폴더에 들어가 쓸 수 있습니다.' },
+ agents: { title: '주요 에이전트를 자유롭게 전환', body: 'Claude Code, Codex, Gemini CLI, Copilot, Cursor 등 컴퓨터에 있는 에이전트를 자동으로 찾습니다. 채팅에서 바꾸거나 내 API 키를 쓸 수 있습니다.' },
+ speed: { title: '더 빠른 미리보기와 내보내기', body: '고정된 렌더링 엔진으로 재생이 부드럽고, 하드웨어 비디오 인코더가 있으면 내보내기에 사용합니다.' },
+ setup: { title: '터미널도, 의존성 관리도 필요 없음', body: 'Node, npm, 패키지 버전을 관리할 필요가 없습니다. ffmpeg와 렌더러가 내장되어 Studio와 함께 테스트되었습니다.' },
+ updates: { title: '항상 최신 상태', body: '업데이트는 백그라운드에서 받아 재시작할 때 설치되며, 내보내기나 답변 도중에는 끼어들지 않습니다.' },
+ history: { title: '영상마다 대화 보관', body: '마지막 영상이 대화와 함께 열려, 에이전트와 멈춘 곳에서 이어 갑니다.' },
},
picture: {
clip: '타이틀 · 0:02–0:06',
@@ -72,12 +74,16 @@ export const ko: Words = {
gone: 'Studio가 멈췄습니다. 터미널에서 이 명령을 실행하거나 에이전트에게 OpenFilm을 다시 열어 달라고 하세요. 이 페이지는 자동으로 다시 연결됩니다.',
goneApp: 'Studio가 멈췄습니다. OpenFilm 앱을 종료했다가 다시 열면 복구됩니다.',
copied: '복사됨',
+ lockedTitle: '이 브라우저는 Studio에 로그인되어 있지 않습니다',
+ lockedBody: 'Studio는 실행 중이지만, 키가 붙은 주소로 한 번 연 브라우저만 받아들입니다. `openfilm open`(개발 중에는 `pnpm dev`)이 출력한 ?key= 가 붙은 전체 주소를 여세요. 한 번 열면 이 브라우저는 Studio 주소를 그대로 쓸 수 있습니다.',
+ lockedHow: '주소를 다시 받으려면 실행',
},
projects: {
newProject: '새 프로젝트',
localProjectFailed: '프로젝트를 만들지 못했습니다. 다시 시도하세요.',
revealFolder: `${FILES}에서 보기`,
folderAll: '전체',
+ folderUp: '한 단계 위로',
untitledFolder: '제목 없는 폴더',
folderCount: '프로젝트 {n}개',
folderCountOne: '프로젝트 1개',
@@ -104,7 +110,7 @@ export const ko: Words = {
agentRunningDeleteMany: '{n}개 프로젝트에서 에이전트가 실행 중입니다. 먼저 중지한 다음 삭제하세요.',
removeFromList: '목록에서 제거',
removeTitle: '목록에서 제거할까요?',
- removeDesc: '폴더가 더 이상 없으므로 목록에서만 제거됩니다. 디스크에는 아무 변화가 없습니다.',
+ removeDesc: '폴더가 이미 없고, 프로젝트가 보관하는 모든 것(버전 기록, 대화)은 그 안에 있었으므로 지울 파일이 남아 있지 않습니다. 목록에서 제거합니다.',
removeAlso: '폴더가 없어진 프로젝트는 목록에서만 제거됩니다.',
getFromGitHub: 'GitHub에서 가져오기…',
importFrom: '가져오기',
@@ -190,7 +196,7 @@ export const ko: Words = {
sortNewest: '최신순',
sortOldest: '오래된 순',
sortDuration: '길이순',
- sortTitle: '제목',
+ sortTitle: '이름(가나다순)',
viewLabel: '보기',
viewCards: '카드 보기',
viewList: '목록 보기',
@@ -331,6 +337,8 @@ export const ko: Words = {
rangePart: '일부 구간',
saveTo: '저장 위치',
change: '변경…',
+ pickTitle: '내보내기 저장 위치 선택',
+ pickButton: '선택',
summary: '파일 {n}개 · {dur}',
approx: '약',
emptyFilm: '영상이 비어 있습니다. 먼저 클립을 추가하세요.',
@@ -676,6 +684,11 @@ export const ko: Words = {
close: '닫기',
results: '결과',
moveFailed: '그곳으로 옮길 수 없습니다.',
+ moveAskTitle: '일부 경로는 자동으로 바꿀 수 없습니다',
+ moveAskBody: '페이지를 옮기면 Studio가 읽을 수 있는 링크를 고쳐 씁니다. 아래 항목은 실행 중에 만들어지므로 이전 위치를 계속 가리킵니다. 옮긴 뒤 확인하거나 에이전트에게 고쳐 달라고 하세요.',
+ moveAskConfirm: '그래도 옮기기',
+ viewGrid: '격자로 보기',
+ viewList: '목록으로 보기',
moveTaken: '{folder}에 이미 “{name}”(이)라는 파일이 있습니다. 먼저 둘 중 하나의 이름을 바꾸세요.',
emptyFolder: '이 폴더는 비어 있습니다',
deleteFolderTitle: '“{name}” 폴더를 삭제할까요?',
@@ -729,10 +742,16 @@ export const ko: Words = {
loopFilm: "반복 재생",
play: '재생',
pause: '일시 정지',
- frame: '출력 프레임',
- frameNative: '원본',
+ frameCustom: '사용자 지정',
+ ratioOriginal: '맞춤(원본)',
+ ratioPhone: '5.8인치',
+ ratioHint: { wide: '(YouTube)', tall: '(TikTok)' },
+ frameCustomW: '너비',
+ frameCustomH: '높이',
+ frameCustomApply: '이 비율 사용',
+ frameCustomRange: '1:4부터 4:1까지',
canvas: '화면 비율',
- canvasNote: '이 영상의 캔버스를 설정합니다. 아직 아무것도 만들지 않았으니 자유롭게 바꾸세요.',
+ canvasNote: '영상의 캔버스입니다. 비율을 바꾸면 짧은 변은 그대로이고, 원래 화면이 전체가 들어가도록 비율대로 줄어 가운데에 놓입니다.',
fullscreen: '전체 화면',
},
inspector: {
@@ -959,8 +978,12 @@ export const ko: Words = {
film: '필름',
stage: '스테이지',
stageShape: '스테이지 비율',
- deliveryFrame: '내보내기 프레임',
- stageFixed: '스테이지는 만든 그대로 유지됩니다. 내보내기 프레임이 다른 비율에 맞춥니다.',
+ stageFixed: '비율을 바꾸면 짧은 변은 그대로이고, 원래 화면이 전체가 들어가도록 비율대로 줄어 가운데에 놓입니다. 그다음 에이전트에게 새 캔버스에 맞게 다시 배치해 달라고 하세요.',
+ redesignOpen: '이 캔버스에 맞게 다시 배치해 달라고 하기',
+ redesignBody: '이 문장을 채팅에 붙여 넣으면 에이전트가 지금 캔버스에 맞게 모든 페이지와 클립을 다시 배치합니다.',
+ redesignAsk: '이 영상의 캔버스가 이제 {ratio}({size})입니다. 여기에 맞게 모든 페이지와 클립을 다시 배치하고 look으로 각 장면을 확인해 줘.',
+ redesignCopy: '요청 복사',
+ redesignCopied: '복사됨: 채팅에 붙여 넣으세요',
filmInfo: '내용',
tracks: '트랙',
clipsCount: '클립',
@@ -1015,8 +1038,8 @@ export const ko: Words = {
subtitleLineGo: '{time}(으)로 이동',
subtitleLineInLanguage: '{time}의 자막, {lang}',
subtitleLineUntranslated: '아직 번역되지 않음',
- subtitleLinesMakeOne: '대본이 없는 음성 클립 1개의 자막 만들기',
- subtitleLinesMake: '대본이 없는 클립 {n}개의 자막 만들기',
+ subtitleLinesMakeOne: '대본이 없거나 오래된 음성 클립 1개의 자막 만들기',
+ subtitleLinesMake: '대본이 없거나 오래된 클립 {n}개의 자막 만들기',
subtitleStyle: '자막 스타일',
subtitleLanguageGroup: '자막 언어',
subtitleLanguageOriginal: '원문',
@@ -1215,6 +1238,8 @@ export const ko: Words = {
hideRow: '타임라인의 자막 줄 숨기기',
name: '자막',
add: '재생 헤드 위치에 자막 추가',
+ hide: '자막 트랙 숨기기',
+ hideNote: '‘자막 스타일 › 타임라인에서 편집’에서 다시 켤 수 있습니다.',
split: '재생 헤드에서 분할',
splitWhere: '재생 헤드를 자막 안쪽, 양 끝에서 떨어진 곳에 두세요',
merge: '다음 자막과 병합',
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index 60a5b3c..5761dc4 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -46,16 +46,18 @@ export const zhCN: Words = {
desktop: {
title: 'OpenFilm 桌面版',
tagline: '智能体与影片,并排在一起。',
- intro: '同一个 Studio,成为独立的应用,影片旁边就是和你的智能体的对话。提出要求,看着每处改动落地,也可以随手亲自修改。',
+ intro: '把 Studio 做成桌面应用,智能体的对话就在影片旁边,并和编辑器的每个部分打通。提出要求,看着改动落地,也可以随手亲自修改。',
worksWith: '支持',
orOwnKey: '或你自己的 API key',
features: {
- chat: { title: '在影片旁对话', body: 'Claude Code、Codex、Gemini CLI 等都能在同一个窗口里用。每处改动都会即时出现在画面中。' },
- point: { title: '指哪改哪', body: '把一个片段、一个图层或某个时刻放进消息里。点击对话中的引用即可跳转过去。' },
- drop: { title: '拖入你的素材', body: '把视频、图片或声音拖进对话:它们会直接进入影片的文件夹。' },
- setup: { title: '无需任何配置', body: '不用终端。它会找到你电脑上的智能体,并自动准备好做片需要的工具。' },
- history: { title: '对话都会保留', body: '每部影片都保留自己的对话,你和智能体随时接着上次继续。' },
- launch: { title: '双击即可打开', body: '打开就是上次的影片,播放更流畅,还会自动更新。' },
+ sync: { title: '与编辑器双向联动', body: '把片段、图层、画面区域或素材文件放进消息;智能体提到的任何片段,点一下就跳到 Studio 里对应的位置。' },
+ live: { title: '改动实时呈现', body: '每处修改写下时就出现在画面和时间线上。可以亲手微调,也可以在版本历史里退回。' },
+ drop: { title: '素材直接拖进来', body: '把视频、图片或声音拖进对话,直接进入影片的文件夹,马上能用。' },
+ agents: { title: '主流智能体随心切换', body: 'Claude Code、Codex、Gemini CLI、Copilot、Cursor 等,自动发现你电脑上已有的。在对话里随时切换,也可以用自己的 API key。' },
+ speed: { title: '预览和导出更快更稳', body: '内置固定版本的渲染引擎,播放更流畅;电脑有硬件视频编码器时,导出会用它加速。' },
+ setup: { title: '无需终端,无需管理依赖', body: '不用装 Node、npm,也不用管包的版本:ffmpeg 和渲染器都已内置,并和 Studio 一起测试过。' },
+ updates: { title: '始终保持最新', body: '更新在后台下载,重启时安装,绝不会打断正在进行的导出或回复。' },
+ history: { title: '每部影片都留着对话', body: '打开就是上次的影片,对话都在,你和智能体接着上次继续。' },
},
picture: {
clip: '标题 · 0:02–0:06',
@@ -73,12 +75,16 @@ export const zhCN: Words = {
gone: 'Studio 已停止运行。在终端运行下面这条命令,或让智能体重新打开 OpenFilm,这个页面会自动重新连上。',
goneApp: 'Studio 已停止运行。退出并重新打开 OpenFilm 应用即可恢复。',
copied: '已复制',
+ lockedTitle: '这个浏览器还没有登录 Studio',
+ lockedBody: 'Studio 正在运行,但只接受用带 key 的地址打开过一次的浏览器。请打开 `openfilm open`(开发时是 `pnpm dev`)打印的完整地址,也就是带 ?key= 的那个;打开一次之后,这个浏览器就能直接用 Studio 的地址了。',
+ lockedHow: '想重新拿到地址,运行',
},
projects: {
newProject: '新建项目',
localProjectFailed: '无法创建项目,请重试。',
revealFolder: `在${FILES}中显示`,
folderAll: '全部',
+ folderUp: '返回上一级',
untitledFolder: '未命名文件夹',
folderCount: '{n} 个项目',
folderCountOne: '1 个项目',
@@ -105,7 +111,7 @@ export const zhCN: Words = {
agentRunningDeleteMany: '其中 {n} 个项目里有 Agent 正在运行,请先停止,再删除。',
removeFromList: '从列表中移除',
removeTitle: '从列表中移除?',
- removeDesc: '它的文件夹已不存在,因此只会从列表中移除,磁盘上的内容不会有任何变化。',
+ removeDesc: '它的文件夹已经不在了,项目的一切(版本历史、对话)都存在那个文件夹里,所以没有残留文件需要删除。这里只是把它从列表中移除。',
removeAlso: '文件夹已不存在的项目只会从列表中移除。',
getFromGitHub: '从 GitHub 获取…',
importFrom: '导入自',
@@ -191,7 +197,7 @@ export const zhCN: Words = {
sortNewest: '最新',
sortOldest: '最早',
sortDuration: '时长最长',
- sortTitle: '标题',
+ sortTitle: '名称(A–Z)',
viewLabel: '视图',
viewCards: '卡片视图',
viewList: '列表视图',
@@ -332,6 +338,8 @@ export const zhCN: Words = {
rangePart: '部分',
saveTo: '保存到',
change: '更改…',
+ pickTitle: '选择导出的保存位置',
+ pickButton: '选择',
summary: '{n} 个文件 · {dur}',
approx: '约',
emptyFilm: '影片是空的——请先添加一个片段。',
@@ -677,6 +685,11 @@ export const zhCN: Words = {
close: '关闭',
results: '结果',
moveFailed: '无法移动到那里。',
+ moveAskTitle: '有些路径无法自动更新',
+ moveAskBody: '移动网页时,Studio 会改写它能读到的链接。下面这些是页面运行时才拼出来的,移动后仍会指向旧位置:移动后请检查,或让智能体修正。',
+ moveAskConfirm: '仍然移动',
+ viewGrid: '网格显示',
+ viewList: '列表显示',
moveTaken: '{folder} 中已有名为“{name}”的文件。请先重命名其中一个。',
emptyFolder: '此文件夹为空',
deleteFolderTitle: '删除文件夹“{name}”?',
@@ -730,10 +743,16 @@ export const zhCN: Words = {
loopFilm: "循环播放",
play: '播放',
pause: '暂停',
- frame: '交付画幅',
- frameNative: '原生',
+ frameCustom: '自定义',
+ ratioOriginal: '适应(原始)',
+ ratioPhone: '5.8 寸',
+ ratioHint: { wide: '(YouTube)', tall: '(抖音)' },
+ frameCustomW: '宽',
+ frameCustomH: '高',
+ frameCustomApply: '使用这个比例',
+ frameCustomRange: '范围 1:4 到 4:1',
canvas: '画面比例',
- canvasNote: '设置此影片的画布。目前还什么都没做——可以随意切换。',
+ canvasNote: '影片的画布。换比例时画布短边不变,原画面等比缩放、完整放进新画布并居中。',
fullscreen: '全屏',
},
inspector: {
@@ -960,8 +979,12 @@ export const zhCN: Words = {
film: '影片',
stage: '画布',
stageShape: '画布比例',
- deliveryFrame: '导出画框',
- stageFixed: '画布保持影片制作时的样子:导出画框会把它放进另一种比例。',
+ stageFixed: '换比例时画布短边不变,原画面等比缩放、完整放进新画布并居中。之后可以让智能体按新画布重新排版。',
+ redesignOpen: '让智能体按这个画布重新排版',
+ redesignBody: '把下面这句话粘贴到对话里,智能体会按当前画布重新排版每个页面和片段。',
+ redesignAsk: '这部影片的画布现在是 {ratio}({size})。请按这个画布重新排版每个页面和片段,并用 look 检查每一幕。',
+ redesignCopy: '复制这句话',
+ redesignCopied: '已复制,粘贴到对话里即可',
filmInfo: '内容',
tracks: '轨道',
clipsCount: '片段',
@@ -1016,8 +1039,8 @@ export const zhCN: Words = {
subtitleLineGo: '跳转到 {time}',
subtitleLineInLanguage: '{time} 处的字幕({lang})',
subtitleLineUntranslated: '尚未翻译',
- subtitleLinesMakeOne: '为一个没有文字稿的人声片段生成字幕',
- subtitleLinesMake: '为 {n} 个没有文字稿的片段生成字幕',
+ subtitleLinesMakeOne: '为一个文字稿缺失或已过期的人声片段生成字幕',
+ subtitleLinesMake: '为 {n} 个文字稿缺失或已过期的片段生成字幕',
subtitleStyle: '字幕样式',
subtitleLanguageGroup: '字幕语言',
subtitleLanguageOriginal: '原文',
@@ -1216,6 +1239,8 @@ export const zhCN: Words = {
hideRow: '隐藏时间线上的字幕行',
name: '字幕',
add: '在播放头处添加字幕',
+ hide: '隐藏字幕行',
+ hideNote: '可在“字幕样式 › 在时间线上编辑”中重新打开。',
split: '在播放头处拆分',
splitWhere: '把播放头放到字幕中间,离开它的两端',
merge: '与下一条合并',
diff --git a/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts b/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts
new file mode 100644
index 0000000..03dcf3f
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts
@@ -0,0 +1,35 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { canvasFor, fitToCanvas } from './canvas-fit.ts';
+
+test('another shape keeps the canvas short side (1920×1080 made 3:4 is 1080×1440)', () => {
+ assert.deepEqual(canvasFor({ w: 1920, h: 1080 }, '3:4'), { w: 1080, h: 1440 });
+ assert.deepEqual(canvasFor({ w: 1920, h: 1080 }, '9:16'), { w: 1080, h: 1920 });
+ assert.deepEqual(canvasFor({ w: 1080, h: 1920 }, '16:9'), { w: 1920, h: 1080 });
+ assert.deepEqual(canvasFor({ w: 1920, h: 1080 }, '2.35:1'), { w: 2538, h: 1080 });
+});
+
+test('the film is scaled whole into the new canvas, centered, as an editor does: a full-frame video, a placed title', () => {
+ const from = { w: 1920, h: 1080 }, to = { w: 1080, h: 1440 };
+ const out = fitToCanvas([
+ { id: 'v', kind: 'video', own: { w: 1920, h: 1080 } },
+ { id: 't', kind: 'still', own: { w: 400, h: 200 }, box: { x: 760, y: 0, w: 400, h: 200 } },
+ { id: 's', kind: 'sound' },
+ ], from, to);
+ /* k = 1080 / 1920: the video spans the width, centered in height */
+ assert.deepEqual(out.find((c) => c.id === 'v')?.box, { x: 0, y: 416, w: 1080, h: 608 });
+ assert.deepEqual(out.find((c) => c.id === 't')?.box, { x: 428, y: 416, w: 225, h: 113 });
+ assert.equal(out.some((c) => c.id === 's'), false);
+});
+
+test('a page laid out at the canvas keeps the old canvas as its size, so it is scaled as a video is', () => {
+ const from = { w: 1920, h: 1080 }, to = { w: 1080, h: 1440 };
+ const out = fitToCanvas([
+ { id: 'free', kind: 'page', own: from, reflows: true },
+ { id: 'sized', kind: 'page', own: { w: 800, h: 600 } },
+ { id: 'given', kind: 'page', own: { w: 1280, h: 720 }, reflows: true, size: { w: 1280, h: 720 } },
+ ], from, to);
+ assert.deepEqual(out.find((c) => c.id === 'free'), { id: 'free', box: { x: 0, y: 416, w: 1080, h: 608 }, size: { w: 1920, h: 1080 } });
+ assert.equal(out.find((c) => c.id === 'sized')?.size, undefined);
+ assert.equal(out.find((c) => c.id === 'given')?.size, undefined);
+});
diff --git a/packages/openfilm/studio/ui/src/lib/canvas-fit.ts b/packages/openfilm/studio/ui/src/lib/canvas-fit.ts
new file mode 100644
index 0000000..e22a5b6
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/canvas-fit.ts
@@ -0,0 +1,55 @@
+/**
+ * A film's canvas changing shape, as an editor's (CapCut's) does: the canvas takes the new shape with its short side
+ * kept (a 1920×1080 film made 3:4 is 1080×1440), and every picture on it is scaled by one factor, the largest that
+ * keeps the old canvas whole inside the new one, about the middle: the film shows as it was, smaller or larger,
+ * centered, with room around it. Nothing is cut. What a picture is drawn as (film-doc's pictureRect) is written as its
+ * box, so a video that filled the old canvas (no box of its own) keeps that place rather than filling the new one.
+ * A page that sets no size of its own is laid out at the canvas's: it is given the old canvas as its `size`, so it is
+ * scaled as a video is rather than laid out again in the new shape.
+ */
+import { pictureRect } from '../../../../src/film-doc.mjs';
+import { frameRatioOf, type FilmFrameId } from './film-frame.ts';
+import type { FilmBox, FilmSrcKind } from './film.ts';
+
+type Size = { w: number; h: number };
+
+/** Even sizes: H.264 samples chroma in 2×2 blocks and refuses odd dimensions. At most 8192 a side. */
+const even = (n: number) => Math.max(2, Math.min(8192, Math.round(n / 2) * 2));
+
+/** The canvas in another shape, its short side kept (a typed size is taken as it is elsewhere). */
+export function canvasFor(stage: Size, frame: FilmFrameId): Size {
+ const ratio = frame === 'native' ? null : frameRatioOf(frame);
+ if (ratio == null) return { w: even(stage.w), h: even(stage.h) };
+ const short = Math.min(stage.w, stage.h);
+ return ratio >= 1 ? { w: even(short * ratio), h: even(short) } : { w: even(short), h: even(short / ratio) };
+}
+
+/**
+ * A picture clip as the fit needs it: its kind, its picture's own size (unknown: the old canvas), its box if any, and
+ * for a page, whether it sets no size of its own (`reflows`) and the `size` its clip gives it.
+ */
+export interface CanvasClip { id: string; kind: FilmSrcKind | null; own?: Size | null; box?: FilmBox | null; reflows?: boolean; size?: Size | null }
+
+/** A clip on the new canvas: its box, and for a page laid out at the old canvas, that size. */
+export interface CanvasFit { id: string; box: FilmBox; size?: Size }
+
+/**
+ * Each picture clip's box on the new canvas `to` (the old one is `from`): scaled by min(to.w / from.w, to.h / from.h)
+ * about the middle of each canvas. Sounds have no picture and are left out.
+ */
+export function fitToCanvas(clips: readonly CanvasClip[], from: Size, to: Size): CanvasFit[] {
+ const k = Math.min(to.w / from.w, to.h / from.h);
+ const out: CanvasFit[] = [];
+ for (const clip of clips) {
+ if (!clip.kind || clip.kind === 'sound') continue;
+ const own = clip.own && clip.own.w > 0 && clip.own.h > 0 ? clip.own : from;
+ const at = pictureRect(clip.kind, own, from, clip.box ?? undefined);
+ const w = at.w * k, h = at.h * k;
+ const cx = (at.x + at.w / 2 - from.w / 2) * k + to.w / 2;
+ const cy = (at.y + at.h / 2 - from.h / 2) * k + to.h / 2;
+ const box: FilmBox = { x: Math.round(cx - w / 2), y: Math.round(cy - h / 2), w: Math.round(w), h: Math.round(h) };
+ if (at.r) box.r = at.r;
+ out.push(clip.kind === 'page' && clip.reflows && !clip.size ? { id: clip.id, box, size: { w: from.w, h: from.h } } : { id: clip.id, box });
+ }
+ return out;
+}
diff --git a/packages/openfilm/studio/ui/src/lib/film-frame.test.ts b/packages/openfilm/studio/ui/src/lib/film-frame.test.ts
new file mode 100644
index 0000000..636f2fd
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/film-frame.test.ts
@@ -0,0 +1,25 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { FILM_FRAME_IDS, customFilmFrame, filmFrameBox, frameRatioOf, parseFilmFrame } from './film-frame.ts';
+
+test('every preset is a ratio W:H, cinema ones included', () => {
+ for (const id of FILM_FRAME_IDS) if (id !== 'native') assert.ok(frameRatioOf(id), id);
+ assert.ok(Math.abs(frameRatioOf('2.39:1')! - 2.39) < 1e-9);
+});
+
+test('a custom ratio is kept between 1:4 and 4:1; anything else is not a frame', () => {
+ assert.equal(customFilmFrame(2.39, 1), '2.39:1');
+ assert.equal(customFilmFrame(5, 4), '5:4');
+ assert.equal(customFilmFrame(9, 1), null);
+ assert.equal(customFilmFrame(0, 1), null);
+ assert.equal(parseFilmFrame('7:5'), '7:5');
+ assert.equal(parseFilmFrame('1:9'), 'native');
+ assert.equal(parseFilmFrame('wide'), 'native');
+});
+
+test('a 16:9 film framed 2.39:1 keeps its height, the frame wider for bars at its sides', () => {
+ const box = filmFrameBox({ w: 1920, h: 1080 }, '2.39:1');
+ assert.equal(box.h, 1080);
+ assert.equal(box.w, 2582);
+});
+
diff --git a/packages/openfilm/studio/ui/src/lib/film-frame.ts b/packages/openfilm/studio/ui/src/lib/film-frame.ts
index 0fccbea..420daaa 100644
--- a/packages/openfilm/studio/ui/src/lib/film-frame.ts
+++ b/packages/openfilm/studio/ui/src/lib/film-frame.ts
@@ -8,30 +8,43 @@
* Two ways to fit it: `contain` (default) scales and centers with bars and never crops; `cover` fills the box and
* crops the overflow, so the edges are really gone — a choice, never the default.
*
- * The frame is a delivery preference, not part of the film: it is kept per project in this browser's localStorage
- * (unlike the subtitle style, which lives in the project folder's `.film/subtitles.json`) and sent along with an
- * export.
+ * The frame is the export's choice, not part of the film: picked in the export dialog for one export (the film's own
+ * shape is its canvas, which the viewer's ratio button changes).
*/
-/** A delivery frame. `native` = no frame, the film at its own size. */
-export type FilmFrameId = 'native' | '16:9' | '9:16' | '1:1' | '4:5' | '4:3' | '21:9';
+/**
+ * A delivery frame: `native` (no frame, the film at its own size), or a ratio written `W:H` ("16:9", "2.39:1"): one of
+ * the presets, or any other the person types, from 1:4 to 4:1.
+ */
+export type FilmFrameId = 'native' | `${number}:${number}`;
+/** The presets, as editors offer them: video and social shapes first, then photo and cinema ones. */
export const FILM_FRAME_IDS: FilmFrameId[] = [
- 'native', '16:9', '9:16', '1:1', '4:5', '4:3', '21:9',
+ 'native', '16:9', '9:16', '1:1', '4:5', '4:3', '3:4', '3:2', '2:3', '21:9', '2.39:1', '1.85:1', '2:1',
];
-/** Width ÷ height of each frame. `native` has none: it follows the film. */
-const FRAME_RATIO: Record<Exclude<FilmFrameId, 'native'>, number> = {
- '16:9': 16 / 9,
- '9:16': 9 / 16,
- '1:1': 1,
- '4:5': 4 / 5,
- '4:3': 4 / 3,
- '21:9': 21 / 9,
-};
+/** How far a frame may go from square, either way (a custom one past it is refused). */
+export const FRAME_RATIO_LIMIT = 4;
+const RATIO = /^(\d{1,4}(?:\.\d{1,3})?):(\d{1,4}(?:\.\d{1,3})?)$/;
+
+/** Width ÷ height of a frame written `W:H`, or null when it is not one (or too far from square). */
+export function frameRatioOf(frame: string): number | null {
+ const m = RATIO.exec(frame);
+ if (!m) return null;
+ const ratio = Number(m[1]) / Number(m[2]);
+ return Number.isFinite(ratio) && ratio >= 1 / FRAME_RATIO_LIMIT && ratio <= FRAME_RATIO_LIMIT ? ratio : null;
+}
+
+/** A frame from a typed width and height ("2.39" and "1"), or null when they make none. */
+export function customFilmFrame(w: number, h: number): FilmFrameId | null {
+ const num = (n: number) => String(Math.round(n * 1000) / 1000);
+ if (!(w > 0) || !(h > 0)) return null;
+ const id = `${num(w)}:${num(h)}`;
+ return frameRatioOf(id) != null ? id as FilmFrameId : null;
+}
export function filmFrameRatio(frame: FilmFrameId, stage: { w: number; h: number }): number {
- return frame === 'native' ? stage.w / Math.max(1, stage.h) : FRAME_RATIO[frame];
+ return (frame === 'native' ? null : frameRatioOf(frame)) ?? stage.w / Math.max(1, stage.h);
}
/** Even sizes: H.264 samples chroma in 2×2 blocks and refuses odd dimensions. */
@@ -60,10 +73,10 @@ export function filmFrameBox(
): FilmFrameBox {
const sw = Math.max(1, stage.w);
const sh = Math.max(1, stage.h);
- if (frame === 'native') {
+ const ratio = frame === 'native' ? null : frameRatioOf(frame);
+ if (ratio == null) {
return { w: even(sw), h: even(sh), inner: { w: sw, h: sh, left: 0, top: 0, scale: 1 } };
}
- const ratio = FRAME_RATIO[frame];
/* the frame must hold the film both ways: take the larger */
const byWidth = { w: sw, h: sw / ratio };
const byHeight = { w: sh * ratio, h: sh };
@@ -84,8 +97,9 @@ export function filmFrameBox(
/** Whether the frame has the film's own shape (then framing it changes nothing). */
export function filmFrameIsNative(stage: { w: number; h: number }, frame: FilmFrameId): boolean {
- if (frame === 'native') return true;
- return Math.abs(stage.w / Math.max(1, stage.h) - FRAME_RATIO[frame]) < 0.01;
+ const ratio = frame === 'native' ? null : frameRatioOf(frame);
+ if (ratio == null) return true;
+ return Math.abs(stage.w / Math.max(1, stage.h) - ratio) < 0.01;
}
/**
@@ -98,8 +112,8 @@ export function filmFrameStage(
stage: { w: number; h: number },
frame: FilmFrameId,
): { w: number; h: number } {
- if (frame === 'native') return { w: even(stage.w), h: even(stage.h) };
- const ratio = FRAME_RATIO[frame];
+ const ratio = frame === 'native' ? null : frameRatioOf(frame);
+ if (ratio == null) return { w: even(stage.w), h: even(stage.h) };
return ratio >= 1
? { w: even(HD * ratio), h: even(HD) }
: { w: even(HD), h: even(HD / ratio) };
@@ -111,27 +125,7 @@ export function filmFrameOf(stage: { w: number; h: number }): FilmFrameId {
}
export function parseFilmFrame(raw: unknown): FilmFrameId {
- return typeof raw === 'string' && (FILM_FRAME_IDS as string[]).includes(raw)
+ return typeof raw === 'string' && (raw === 'native' || frameRatioOf(raw) != null)
? raw as FilmFrameId
: 'native';
}
-
-/**
- * Where the delivery frame is kept: per project ("this one goes vertical" is true of one film, not of every film the
- * person opens), and only in this browser — changing it should not make a version.
- */
-const FRAME_KEY = 'openfilm.frame';
-
-export function readFilmFrame(projectId: string): FilmFrameId {
- try {
- return parseFilmFrame(localStorage.getItem(`${FRAME_KEY}.${projectId}`));
- } catch {
- return 'native';
- }
-}
-
-export function writeFilmFrame(projectId: string, frame: FilmFrameId): void {
- try {
- localStorage.setItem(`${FRAME_KEY}.${projectId}`, frame);
- } catch { /* storage off (private window): the choice lasts this session only */ }
-}
diff --git a/packages/openfilm/studio/ui/src/lib/film-shape.test.ts b/packages/openfilm/studio/ui/src/lib/film-shape.test.ts
index 90b6d3f..07463c3 100644
--- a/packages/openfilm/studio/ui/src/lib/film-shape.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/film-shape.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { filmShape, type ClipSpan } from './film-shape.ts';
+import { filmShape, spanShows, type ClipSpan } from './film-shape.ts';
import { layoutTracks } from './timeline-layout.ts';
import type { FilmDoc } from './film.ts';
@@ -37,3 +37,13 @@ test('where the preview placed a clip, its span stands; a still keeps the length
const spans: ClipSpan[] = [{ id: 'a', src: 'assets/a.mp4', at: 0, end: 9, native: 9 }];
assert.deepEqual(blocks(film, spans, media).map((b) => b.slice(0, 3)), [['a', 0, 9000], ['logo', 9000, 11_000]]);
});
+
+/* a layer selected on the picture lets go once the playhead leaves its clip (components/FilmStageSelect) */
+test('a clip shows from its start up to, not including, its end', () => {
+ const span = { at: 2, end: 6 };
+ assert.equal(spanShows(span, 1990), false);
+ assert.equal(spanShows(span, 2000), true);
+ assert.equal(spanShows(span, 5999), true);
+ assert.equal(spanShows(span, 6100), false);
+ assert.equal(spanShows(span, 5160), true);
+});
diff --git a/packages/openfilm/studio/ui/src/lib/film-shape.ts b/packages/openfilm/studio/ui/src/lib/film-shape.ts
index 4a7e165..bc455f3 100644
--- a/packages/openfilm/studio/ui/src/lib/film-shape.ts
+++ b/packages/openfilm/studio/ui/src/lib/film-shape.ts
@@ -11,10 +11,17 @@ import type { TimelineFilm, TimelineBlock } from './timeline-layout.ts';
/** Where the preview says a clip is: seconds on the film, and its source's own length (none for a still) and size. */
export type ClipSpan = {
id: string; src: string; at: number; end: number; native: number | null; w?: number; h?: number;
+ /** a page that sets no size of its own: laid out at its clip's `size`, else the stage's */
+ reflows?: true;
/** a picture's look, as the film's CSS makes it (see clip-look) */
look?: ClipLook;
};
+/** Whether a clip is on screen at `timeMs` (its span is in seconds; a few ms either side for rounding). */
+export const spanShows = (span: Pick<ClipSpan, 'at' | 'end'>, timeMs: number): boolean => (
+ timeMs >= span.at * 1000 - 5 && timeMs < span.end * 1000 + 5
+);
+
/** What probing a media file told: whether a video carries sound, and the file's own length (s). */
export type MediaFacts = ReadonlyMap<string, { audio?: boolean; duration?: number }>;
diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.ts
index b7d49a8..dfc26d6 100644
--- a/packages/openfilm/studio/ui/src/lib/host.ts
+++ b/packages/openfilm/studio/ui/src/lib/host.ts
@@ -100,9 +100,13 @@ export interface StudioHost {
/**
* The app picks folders, and knows where a dropped one is: the Projects list gets "Open…", which asks the app for a
* folder to open as a project (`pick`: null when the person cancelled), and opens a folder dropped on it (`pathOf`:
- * its full path, '' when the app cannot tell).
+ * its full path, '' when the app cannot tell). The export's "Save to" asks with its own words and the folder it
+ * starts in (`title`, `button`, `at`).
*/
- folders?: { pick: () => Promise<string | null>; pathOf: (file: File) => string };
+ folders?: {
+ pick: (options?: { title?: string; button?: string; at?: string }) => Promise<string | null>;
+ pathOf: (file: File) => string;
+ };
}
/** A question about spending, worded for the person (see `asks`). */
diff --git a/packages/openfilm/studio/ui/src/lib/project-folders.test.ts b/packages/openfilm/studio/ui/src/lib/project-folders.test.ts
index 159491f..2217e3b 100644
--- a/packages/openfilm/studio/ui/src/lib/project-folders.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/project-folders.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { folderCounts, folderPosters, visibleProjects, type ListedProject } from './project-folders.ts';
+import { folderCounts, folderPosters, folderTrail, parentOf, visibleProjects, type ListedProject } from './project-folders.ts';
const folders = [{ id: 'f', name: 'Ads', createdAt: 1 }];
const projects: ListedProject[] = [
@@ -39,3 +39,20 @@ test('folder cards: how many each holds, and its newest covers, four at most', (
/* a project without a poster still has its cell (its own face), not a gap or a blank */
assert.deepEqual(folderPosters(projects).deleted, [{ id: 'd' }]);
});
+
+test('folders in folders: the trail to one, and a folder counts what its folders hold', () => {
+ const tree = [
+ { id: 'clients', name: 'Clients', createdAt: 1 },
+ { id: 'acme', name: 'Acme', createdAt: 2, parentId: 'clients' },
+ { id: 'lost', name: 'Lost', createdAt: 3, parentId: 'gone' },
+ ];
+ assert.deepEqual(folderTrail(tree, 'acme').map((f) => f.id), ['clients', 'acme']);
+ assert.deepEqual(folderTrail(tree, null), []);
+ assert.equal(parentOf(tree[2]!, tree), null);
+ const inside = [
+ { id: 'a', name: 'A', openedAt: 1, folderId: 'acme' },
+ { id: 'b', name: 'B', openedAt: 2, folderId: 'clients', poster: 'b.jpg' },
+ ];
+ assert.deepEqual(folderCounts(inside, tree), { acme: 1, clients: 2 });
+ assert.deepEqual(folderPosters(inside, tree).clients?.map((c) => c.id), ['b', 'a']);
+});
diff --git a/packages/openfilm/studio/ui/src/lib/project-folders.ts b/packages/openfilm/studio/ui/src/lib/project-folders.ts
index 4ec3ed2..4309812 100644
--- a/packages/openfilm/studio/ui/src/lib/project-folders.ts
+++ b/packages/openfilm/studio/ui/src/lib/project-folders.ts
@@ -7,7 +7,8 @@
* PUT { folderId } /api/projects/:id/folder (null: no folder)
*/
-export type ProjectFolder = { id: string; name: string; createdAt: number };
+/** `parentId`: the folder it is in (none, or one that is gone: the top level). */
+export type ProjectFolder = { id: string; name: string; createdAt: number; parentId?: string };
/** What of a project the list sorts, files and searches by. */
export type ListedProject = {
@@ -35,7 +36,7 @@ async function call<T>(path: string, method = 'GET', json?: unknown): Promise<T>
export const folderApi = {
list: () => call<{ folders: ProjectFolder[] }>('folders').then((r) => r.folders),
- create: (name: string) => call<{ folder: ProjectFolder }>('folders', 'POST', { name }).then((r) => r.folder),
+ create: (name: string, parentId: string | null = null) => call<{ folder: ProjectFolder }>('folders', 'POST', { name, ...(parentId ? { parentId } : {}) }).then((r) => r.folder),
rename: (id: string, name: string) => call<{ folder: ProjectFolder }>(`folders/${encodeURIComponent(id)}`, 'PATCH', { name }).then((r) => r.folder),
/** takes the folder off the list; resolves to the ids of the projects that were in it */
remove: (id: string) => call<{ projects: string[] }>(`folders/${encodeURIComponent(id)}`, 'DELETE').then((r) => r.projects),
@@ -72,10 +73,32 @@ export function visibleProjects<P extends ListedProject>(
});
}
-/** How many projects each folder holds. */
-export function folderCounts(projects: readonly ListedProject[]): Record<string, number> {
+/** The folder a folder is in, or null (the top level, or its parent is gone). */
+export function parentOf(folder: ProjectFolder, folders: readonly ProjectFolder[]): string | null {
+ return folder.parentId && folders.some((f) => f.id === folder.parentId) ? folder.parentId : null;
+}
+
+/** A folder and the folders it is in, the outermost first (the breadcrumb). A loop is cut where it comes back. */
+export function folderTrail(folders: readonly ProjectFolder[], id: string | null): ProjectFolder[] {
+ const trail: ProjectFolder[] = [];
+ const seen = new Set<string>();
+ for (let at = folders.find((f) => f.id === id); at && !seen.has(at.id); at = folders.find((f) => f.id === parentOf(at!, folders))) {
+ seen.add(at.id);
+ trail.unshift(at);
+ }
+ return trail;
+}
+
+/** The folders that hold `id`, itself first: a project in it counts for each of them. */
+const holders = (folders: readonly ProjectFolder[], id: string) => folderTrail(folders, id).map((f) => f.id).reverse();
+
+/** How many projects each folder holds, those of the folders inside it too. */
+export function folderCounts(projects: readonly ListedProject[], folders: readonly ProjectFolder[] = []): Record<string, number> {
const counts: Record<string, number> = {};
- for (const p of projects) if (p.folderId) counts[p.folderId] = (counts[p.folderId] ?? 0) + 1;
+ for (const p of projects) {
+ if (!p.folderId) continue;
+ for (const id of folders.length ? holders(folders, p.folderId) : [p.folderId]) counts[id] = (counts[id] ?? 0) + 1;
+ }
return counts;
}
@@ -83,13 +106,15 @@ export function folderCounts(projects: readonly ListedProject[]): Record<string,
* The small covers on each folder's card: its newest projects, up to four, each with its poster when it has one (a
* cover without one shows that project's own face, as its card does).
*/
-export function folderPosters(projects: readonly ListedProject[]): Record<string, { id: string; poster?: string }[]> {
+export function folderPosters(projects: readonly ListedProject[], folders: readonly ProjectFolder[] = []): Record<string, { id: string; poster?: string }[]> {
const out: Record<string, { id: string; poster?: string }[]> = {};
const newest = [...projects].sort((a, b) => (b.createdAt ?? b.openedAt) - (a.createdAt ?? a.openedAt));
for (const p of newest) {
if (!p.folderId) continue;
- const list = (out[p.folderId] ??= []);
- if (list.length < 4) list.push(p.poster ? { id: p.id, poster: p.poster } : { id: p.id });
+ for (const id of folders.length ? holders(folders, p.folderId) : [p.folderId]) {
+ const list = (out[id] ??= []);
+ if (list.length < 4) list.push(p.poster ? { id: p.id, poster: p.poster } : { id: p.id });
+ }
}
return out;
}
diff --git a/packages/openfilm/studio/ui/src/lib/timecode.ts b/packages/openfilm/studio/ui/src/lib/timecode.ts
index a08a24b..d789ee6 100644
--- a/packages/openfilm/studio/ui/src/lib/timecode.ts
+++ b/packages/openfilm/studio/ui/src/lib/timecode.ts
@@ -18,8 +18,11 @@ import { useSyncExternalStore } from 'react';
/** The frame rate before a project says otherwise, and the grid the ruler's steps are counted in. */
export const DISPLAY_FPS = 30;
-/** The rates a project can be set to, as editors name them. */
-export const FRAME_RATES = [23.976, 24, 25, 29.97, 30, 50, 59.94, 60] as const;
+/**
+ * The rates a project can be set to and a video exported at, as editors name them: Premiere's and DaVinci Resolve's
+ * common ones (the NTSC 23.976, 29.97 and 59.94 are what cameras and phones record), and 120 for high frame rate.
+ */
+export const FRAME_RATES = [23.976, 24, 25, 29.97, 30, 48, 50, 59.94, 60, 120] as const;
/** A rate as it really is: the NTSC ones are 24000/1001, 30000/1001 and 60000/1001. */
export function exactRate(fps: number): number {
diff --git a/packages/openfilm/studio/ui/src/lib/timeline-drag.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-drag.test.ts
index 216471b..541d65a 100644
--- a/packages/openfilm/studio/ui/src/lib/timeline-drag.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/timeline-drag.test.ts
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { applyDrag, dragLifted, editsForMoves, groupLaneShift, moveDestFor, snapTargetsFor, trimFence, type DropLane } from './timeline-drag.ts';
+import { applyDrag, dragLifted, editsForMoves, groupLaneShift, moveDestFor, moveEditMode, snapTargetsFor, trimFence, type DropLane } from './timeline-drag.ts';
/* Clips on one track do not overlap (SPEC): every gesture that writes a time keeps it that way. */
@@ -180,3 +180,13 @@ test('a press becomes a drag past the threshold: a click on a cut (a few px of j
assert.equal(dragLifted('trim-end', 1, 0), true, 'an edge follows at once');
assert.equal(dragLifted('slip', 4, 0), false);
});
+
+/* a clip let go onto a neighbor on its own track goes in between (as an editor's main track does), never cuts it */
+test('a move onto another clip of its track inserts; into free room it stays put; ⌥ the other way', () => {
+ assert.equal(moveEditMode({ magnet: false, alt: false, overlaps: true }), 'insert');
+ assert.equal(moveEditMode({ magnet: false, alt: false, overlaps: false }), 'overwrite');
+ assert.equal(moveEditMode({ magnet: false, alt: true, overlaps: true }), 'overwrite');
+ assert.equal(moveEditMode({ magnet: false, alt: true, overlaps: false }), 'insert');
+ assert.equal(moveEditMode({ magnet: true, alt: false, overlaps: false }), 'insert');
+ assert.equal(moveEditMode({ magnet: true, alt: true, overlaps: true }), 'overwrite');
+});
diff --git a/packages/openfilm/studio/ui/src/lib/timeline-drag.ts b/packages/openfilm/studio/ui/src/lib/timeline-drag.ts
index 7de2f9f..89c2483 100644
--- a/packages/openfilm/studio/ui/src/lib/timeline-drag.ts
+++ b/packages/openfilm/studio/ui/src/lib/timeline-drag.ts
@@ -462,6 +462,17 @@ export interface DropLane {
occupied?: readonly { startMs: number; endMs: number }[];
}
+/**
+ * How a move is put down. The magnet decides (insert: it goes in between and what follows moves along; overwrite: it
+ * covers what is there), ⌥ held the other way. But a clip let go onto another clip of its own track goes in between
+ * with the magnet off too, as an editor's main track does: dropped on a neighbor it means "put it here", never "cut the
+ * neighbor"; ⌥ still overwrites then. Let go in free room, it stays where it was put. `overlaps`: the clip, where it
+ * would land (flush against a neighbor if it looks flush), covers part of another clip on its own track.
+ */
+export function moveEditMode({ magnet, alt, overlaps }: { magnet: boolean; alt: boolean; overlaps: boolean }): 'insert' | 'overwrite' {
+ return (magnet || overlaps) !== alt ? 'insert' : 'overwrite';
+}
+
export function rangeOverlaps(
range: { startMs: number; endMs: number },
others: readonly { startMs: number; endMs: number }[],