The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Studio: a timeline like CapCut's, an inspector like Figma's, linked media, proxies and 剪映 drafts (#26)
riverisbuildinge0a80d515fa1
diff --git a/.changeset/canvas-in-place.md b/.changeset/canvas-in-place.mdnew file mode 100644index 0000000..1cf7e5d--- /dev/null+++ b/.changeset/canvas-in-place.md@@ -0,0 +1,6 @@+---+"openfilm": patch+---++Studio: a canvas change is applied to the picture in place, without loading the film again, so the film no longer jumps to the top left before it settles in the middle. Dragging the canvas's width or height in the inspector changes the picture as the mark moves. The picture no longer shows a light hairline along its right and bottom edges in the dark theme.+Studio's address keeps its key (`?key=…`), so an address copied from the address bar opens Studio in any browser on this computer, or in an agent's preview, without being signed out. The picture is clipped to its own box, so no line shows along its edges. The inspector is open whenever a project opens. A canvas change fits each picture to the new canvas on its own, as CapCut does, so a portrait photo on one clip no longer shrinks 16:9 footage on another. Dragging the canvas's width or height shows the size and shape on the picture and in the inspector as it moves (Custom unless it is a preset). A click on a page's empty part selects the whole page, so a page smaller than the canvas can be moved and sized on the picture. A canvas side typed or dragged stays from 16 to 8192 px and within 1:4 to 4:1. With a whole page in hand, a click on something in it selects that (a drag still moves the page). ⌘A (Ctrl+A) selects every layer on the picture; Shift-click and a drag on empty space select several, as before. Everything a click can select is outlined under the pointer: a page's layers, a whole page by its empty part, a video or a still, with a clip in hand too. A marquee around whole clips on the picture (by the part on the canvas) selects those clips, as Figma takes the frames it goes around; one inside a page selects its layers, as before. While a marquee is drawn, what letting go would select is outlined as it goes. Several clips selected have one frame around them all, and a drag on one of them moves them all, written in one step. The frame around several clips can be dragged anywhere inside it, empty space too, and its corners scale them all in proportion; its size shows below it. Several clips' frame also turns (its corner rings, Shift in 15° steps) and, for videos, stretches from its sides; the arrow keys move them all. Several layers selected show their shared looks in the inspector (type, appearance, adjustments, effects), and let go when the timeline is pressed or the playhead leaves their clip, as one layer does. A clip selected on the timeline away from the playhead has no frame on the picture until the playhead reaches it. A new mask has a hard edge (no feather). The inspector's menus (blend mode, font weight) and the export's range ends open Studio's own dark menu instead of the system's light list. The inspector follows Figma's: several things' X, Y, W and H are their bounds, typed to move or scale them together; Appearance has corner radius, one for all or each corner its own; Fill is a section of its own (a line's color, a box's background, with + and −); Stroke is too, drawn as an outline that adds nothing to the box, inside, centered or outside the edge; Effects add an inner shadow, a layer blur and a background blur beside the drop shadow and faded edges; type can be underlined or struck through. Under a mask, a crop or faded edges, which cut away what is past the edge, the stroke offers Inside only (a stroke already placed otherwise shows where it is, with a note). Setting one corner keeps the others; removing a fill leaves the layer see-through (not the page's own fill back) and still selectable; an SVG shape's fill can be set; an image's Fit button fits it. A clip that plays all of its file shows its in point grayed out, with a note to shorten it first. The Mask button on the picture's selection bar opens a menu of shapes (the one on now checked): the one picked is put on the clip, its handles on the picture. Where a mask or a crop cuts the picture away, nothing is found under the pointer: a clip's, a layer's own, or a parent's that clips what overflows it; a click there reaches what is under it, as in Photoshop and Figma.diff --git a/.changeset/close-gap-alone.md b/.changeset/close-gap-alone.mdnew file mode 100644index 0000000..5033368--- /dev/null+++ b/.changeset/close-gap-alone.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: "Close gap" always closes the gap picked, including the empty time before a track's first clip. With sync lock on, when a clip on another track leaves no room to move everything together, the gap closes on its own track alone and a notice says so. It used to do nothing.diff --git a/.changeset/export-jianying.md b/.changeset/export-jianying.mdnew file mode 100644index 0000000..a31b314--- /dev/null+++ b/.changeset/export-jianying.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Export › Editing project is for one app at a time, each by its own name: 剪映 (CapCut outside Chinese), Premiere Pro or DaVinci Resolve. For 剪映 or CapCut the timeline goes straight into the app's drafts folder and opens there as a project, ready to keep cutting: web pages as clips with alpha, footage placed where it is in the film with its own sound, other sounds with their levels and fades, and subtitles as a text track. When that app is on the computer it is the choice the dialog starts with; Premiere Pro and DaVinci Resolve get the XML, each with its own import steps. The draft is for whichever of 剪映 and CapCut is on the computer (by language only when both or neither are), named as it is in every language. Every file of the draft is in the app's media panel, as if imported there.diff --git a/.changeset/export-sizes-folder-order.md b/.changeset/export-sizes-folder-order.mdnew file mode 100644index 0000000..1cdb0af--- /dev/null+++ b/.changeset/export-sizes-folder-order.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Export: a frame comes out in its exact shape, so 16:9 is 1920 × 1080 (and 4K 3840 × 2160) around any film, not 1918 × 1080 around a 2:1 one. "Change…" for where exports go opens the folder dialog in front, and the file dialog for importing media too: on macOS they opened behind the browser, so nothing seemed to happen. If macOS doesn't let Studio ask Finder, you can type the folder instead. The export list starts with Video file, then Editing project (what was Editing software), then Social platforms.diff --git a/.changeset/fetch-progress.md b/.changeset/fetch-progress.mdnew file mode 100644index 0000000..08835e3--- /dev/null+++ b/.changeset/fetch-progress.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: getting a film from GitHub works like a download. A public repository comes over https, without git, so its size is known from the start: the bar shows how much of how much has come, how fast, and how long is left, and a dropped connection is tried again. Opening an example shows just its download and Cancel. Cancel stops it at once and leaves nothing behind (before, it started again straight away). A private repository, or one on GitLab, still comes through git. A download is stopped only when nothing has come for two minutes, not after ten minutes in all, so a big film on a slow line gets there.diff --git a/.changeset/folder-dialog-start.md b/.changeset/folder-dialog-start.mdnew file mode 100644index 0000000..abcbd4b--- /dev/null+++ b/.changeset/folder-dialog-start.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++"Change…" for where exports go no longer opens a folder dialog that closes at once: the dialog starts in the folder shown, or the nearest one above it that is there yet (the exports folder is made by the first export), and Finder is no longer asked to find that folder itself. The same for importing and linking media. The export dialog's choices are a capsule inside a capsule, an even gap all round, and the layout menu's rows round as the menu does. The export's custom frame is one more chip in the row of frames, its width and height capsules inside it.diff --git a/.changeset/jianying-tested.md b/.changeset/jianying-tested.mdnew file mode 100644index 0000000..2699b25--- /dev/null+++ b/.changeset/jianying-tested.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: the timeline follows CapCut (剪映 v11.6, tested side by side) in a few more places. ⌘B with nothing selected splits the main track's clip under the playhead, and after a split the right half is the one selected. Turning the main-track magnet on closes the gaps already on the main track. A click on the ruler or the empty timeline while playing pauses again. After Q the playhead goes to the start of the trimmed clip. On the main track with the magnet on, dragging where two clips meet trims one of them and closes up what follows, as CapCut has no roll there.diff --git a/.changeset/main-track-linkage.md b/.changeset/main-track-linkage.mdnew file mode 100644index 0000000..144c516--- /dev/null+++ b/.changeset/main-track-linkage.md@@ -0,0 +1,6 @@+---+"openfilm": patch+---++Studio: the timeline works like CapCut's. The magnet is now the main-track magnet, on by default: the main track (the lowest picture track) stays closed up, so a clip put down there inserts, a delete or a clip dragged off it closes the gap, and trims ripple. Other tracks stay free: a clip put down there overwrites and a delete leaves a gap.+A new Linkage switch, on by default, carries titles, B-roll and sound with the main-track clip they start over when that clip moves, is deleted, trimmed or sped up. A long clip under several shots, such as a music bed, stays where it is, and a carried clip that would run into another moves to a free track. Sync lock is still there for Premiere habits, now off by default. ⌘B and Q / W with nothing selected act on the main track.diff --git a/.changeset/media-linked.md b/.changeset/media-linked.mdnew file mode 100644index 0000000..1c09a11--- /dev/null+++ b/.changeset/media-linked.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: media kept elsewhere can stay there. Upload offers "Import files…" (a copy in the project, cloned where the disk can: at once, and no room taken), "Link files…" and "Link a folder…" (a link in assets/ to where the media is kept, a NAS or another disk). In the app, a file dropped from Finder is copied on the computer rather than sent through the page. A linked file or folder is marked; one that cannot be reached (the NAS is off) says "Not found". Its menu has "Show original", "Relink…" and "Copy into project"; deleting a link never touches the original. Studio follows a link out of a project only to a place the person linked on this computer, so a project from elsewhere cannot reach their other files; the preview, `openfilm look` and `openfilm render` read linked media, and nothing is written there.diff --git a/.changeset/media-pane-picking.md b/.changeset/media-pane-picking.mdnew file mode 100644index 0000000..766a320--- /dev/null+++ b/.changeset/media-pane-picking.md@@ -0,0 +1,8 @@+---+"openfilm": patch+---++Studio: a still or video dropped on the timeline keeps its own shape, as large as the canvas holds and centered, so its box is the picture and needs no crop. A phone's portrait video is read at the size it is shown.+The media pane takes any kind of file (a PDF, a document, a model): what Studio cannot play shows with its icon and ending, under a new "Other" filter. Several files and folders can be picked at once (⌘-click, ⇧-click, a box dragged over empty space, ⌘A) and moved or deleted together; every file and folder has "Move to" on its right-click menu.+A web page that sets no size of its own keeps the size it shows alone (1920 × 1080) when dropped, scaled whole into the canvas, instead of being laid out again in the canvas's shape. A page put in a media folder keeps its poster and plays as a page. The list view shows each file's type, dimensions, size and length as the pane widens; the tiles lose their "+" (drag a file to the timeline, or press Enter); the filter and sort menus close when their button is clicked again. The top bar fills its width: narrowing, Upload becomes its icon first, then the search field shortens, and only at the narrowest is the search a button that opens over the bar.+An import shows a card for each file where it goes, its own progress inside (a picture shows itself while it is sent), in place of the bar above the media; a folder it goes into shows the progress on its cover.diff --git a/.changeset/media-proxies.md b/.changeset/media-proxies.mdnew file mode 100644index 0000000..c6c3333--- /dev/null+++ b/.changeset/media-proxies.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: heavy footage plays from a proxy, as in CapCut. Footage past 1080p, or slow to decode (ProRes, HEVC, 10-bit), gets a lighter copy made in the background (H.264, the same frames at the same times, a key frame every half second), and the preview plays it once it is ready; the media pane shows it being made, then marks it. Settings → General → Playback turns proxies off and sets their size (540p, 720p by default, 1080p). The film's sound, `openfilm render` and every export read the originals; a video's length and size are always the original's.diff --git a/.changeset/no-cover-off-main.md b/.changeset/no-cover-off-main.mdnew file mode 100644index 0000000..20834a8--- /dev/null+++ b/.changeset/no-cover-off-main.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: with the main-track magnet on, clips on the other tracks never cover each other, as in CapCut. A clip dragged, pasted, duplicated or dropped from the media pane where another one already is goes to the nearest free track of its kind, or a new one opens for it, instead of cutting what was there. Nudging with ⌥← / ⌥→ stops at a neighbor. Hold Alt while dropping to overwrite anyway.diff --git a/.changeset/no-fixed-transitions.md b/.changeset/no-fixed-transitions.mdnew file mode 100644index 0000000..240c395--- /dev/null+++ b/.changeset/no-fixed-transitions.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: the timeline no longer offers fixed transitions. A click or right-click on a cut opens no menu (dragging it still rolls the cut), and a clip's menu has no "transition at its start / end". Transitions are your agent's to write; ones a film already has are still drawn, and can be made longer or shorter or removed. Fade in and fade out stay in the clip's menu.diff --git a/.changeset/scrub-like-capcut.md b/.changeset/scrub-like-capcut.mdnew file mode 100644index 0000000..60289d3--- /dev/null+++ b/.changeset/scrub-like-capcut.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: a click on the ruler or the empty timeline while the film plays moves the playhead and playing goes on, as in CapCut; dragging the playhead still pauses. With snapping on, the dragged playhead snaps to clip edges and markers, and a clip dragged onto the playhead shows the snap guide there too.diff --git a/.changeset/text-line-breaks.md b/.changeset/text-line-breaks.mdnew file mode 100644index 0000000..708e9a8--- /dev/null+++ b/.changeset/text-line-breaks.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++A `text` override keeps line breaks: on an element of words alone, or of lines between `<br>`s, it replaces all of the words, a `<br>` at each line break (SPEC §1). In Studio, a double-click on such a line types in it in place, its lines and width kept; Shift+Enter breaks a line, Enter keeps the words, Esc gives them up.diff --git a/.changeset/trim-source-end.md b/.changeset/trim-source-end.mdnew file mode 100644index 0000000..6202875--- /dev/null+++ b/.changeset/trim-source-end.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: a trim that reaches the end of the clip's media says so beside the edge ("End of the media"), so it is clear why the edge stops. The snapping switch's tip now says what it snaps to: clip edges, the playhead and markers.diff --git a/.changeset/unshown-video-frame.md b/.changeset/unshown-video-frame.mdnew file mode 100644index 0000000..17ebd95--- /dev/null+++ b/.changeset/unshown-video-frame.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++A video frame that is decoded but never shown (a seek made just after its file loaded) is sought again, so a render, an export or `look` no longer takes the clip's first frame for the one asked for.diff --git a/packages/openfilm/SPEC.md b/packages/openfilm/SPEC.mdindex 50a68c7..9979835 100644--- a/packages/openfilm/SPEC.md+++ b/packages/openfilm/SPEC.md@@ -76,8 +76,8 @@ where, and CSS that says how each looks. A page draws a shot.selector), on a page clip only, tweaks an element of the page, applied by the host after each frame: optional `n`(which match, from 1), `t` (translate px), `s` (scale), `r` (rotate degrees) as the independent CSS transformproperties so they compose with the page's own animation, `style` (CSS properties, applied with priority), `text`- (replaces the element's own text: all of it when it has no child elements; with inline children, its first run of- text, the children kept), `lock` (`true`: an editor keeps the element from being selected or moved; it changes+ (replaces the element's own text: all of it when it has no child elements or only `<br>`s, a line break in `text`+ being a `<br>`; with other inline children, its first run of text, the children kept), `lock` (`true`: an editor keeps the element from being selected or moved; it changesnothing in the picture). An entry without `at`, at most one, on any clip, is the clip's own: `fade: [in, out]`,seconds (0 or more, to the millisecond, together no longer than the clip): its picture's opacity and its sound'sgain ramp linearly from 0 to 1 over its first `in` seconds and from 1 to 0 over its last `out` seconds, times itsdiff --git a/packages/openfilm/src/host.d.mts b/packages/openfilm/src/host.d.mtsindex e76eac0..e7db23e 100644--- a/packages/openfilm/src/host.d.mts+++ b/packages/openfilm/src/host.d.mts@@ -12,7 +12,8 @@ export declare function closeBrowsers(): Promise<void>;export interface PageNetwork { allow?: readonly string[]; fetch?(url: string, headers: Record<string, string>): Promise<{ status: number; headers: Record<string, string>; body: Buffer }> }export declare class FrameError extends Error {}/** A page's facts once ready: its length (null: it has no end), and its viewport (its own size, or 1920 × 1080 when it says none). */-export interface FilmMeta { duration: number | null; width: number; height: number; sounds: FilmSound[] }+/** `sized`: the page sets its own width and height (without, it is laid out at its clip's size or the stage's). */+export interface FilmMeta { duration: number | null; width: number; height: number; sized: boolean; sounds: FilmSound[] }/** One sound of the film as the built-in timeline plays it: `src` a path on the film's origin, placed at film second `at`, its source seconds [from, to). */export interface FilmSound { clip: string; src: string; at: number; from: number; to?: number; volume: number; speed: number }export declare class FilmPage {@@ -25,4 +26,4 @@ export declare class FilmPage {close(): Promise<void>;}/** Serves one request for the files of `root` at `path`; false when the path leaves the folder. */-export declare function folderFiles(root: string, opts?: { inject?: string; timelineInject?: string; headers?: Record<string, string> }): (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse, path: string, query?: URLSearchParams) => boolean;+export declare function folderFiles(root: string, opts?: { inject?: string; timelineInject?: string; headers?: Record<string, string>; swap?: (file: string) => string | null }): (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse, path: string, query?: URLSearchParams) => boolean;diff --git a/packages/openfilm/src/host.mjs b/packages/openfilm/src/host.mjsindex 4882220..5c88706 100644--- a/packages/openfilm/src/host.mjs+++ b/packages/openfilm/src/host.mjs@@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url';import { extname, join, normalize, resolve, sep } from 'node:path';import { chromium } from 'playwright-core';import { DEFAULT_STAGE, FILM_FILE, readFilmFile } from './film-doc.mjs';+import { readableLink } from './media-links.mjs';// Media seeks that land inside the frame they name. A plain `video.currentTime = t` at a frame boundary otherwise// shows the previous frame about a third of the time. Every page that draws a film by seeking video runs it first,@@ -57,7 +58,8 @@ const TYPES = {* `headers` go on every response (a host adds its own policy); the film (film.html) is played by the built-in* timeline, and gets `timelineInject` instead of `inject` (a host that drives it, like Studio, adds its bridge there). Returns false when the path is not inside* `root`, or leads out of it through a link.- * `swap(file)` may name another file to serve in a file's place (a render's fast-seeking copy of a video, seekable.mjs).+ * `swap(file)` may name another file to serve in a file's place (a render's fast-seeking copy of a video, seekable.mjs;+ * the preview's proxy of heavy footage, studio/server/proxies.mjs); not for `?film-facts`, which asks what the file is.* @param {string} root @param {{ inject?: string, timelineInject?: string, headers?: Record<string, string>, swap?: (file: string) => string | null }} [options]*/export function folderFiles(root, { inject = `<script>${HOST_FLAG}</script>`, timelineInject = inject, headers: extraHeaders = {}, swap } = {}) {@@ -89,11 +91,13 @@ export function folderFiles(root, { inject = `<script>${HOST_FLAG}</script>`, ticonst asked = normalize(join(root, rel));if (asked !== root && !asked.startsWith(root + sep)) return false;try { statSync(asked); } catch { res.writeHead(404, extraHeaders).end('not found'); return true; }- // a link out of the folder is not followed: a film from elsewhere can bring one to any of the person's files+ // a link out of the folder is not followed: a film from elsewhere can bring one to any of the person's files. Only+ // media the person linked is (src/media-links.mjs)let inRoot = false;- try { inRoot = within(realpathSync(root), realpathSync(asked)); } catch { /* gone meanwhile */ }+ try { inRoot = within(realpathSync(root), realpathSync(asked)) || readableLink(root, asked); } catch { /* gone meanwhile */ }if (!inRoot) return false;- const file = swap?.(asked) ?? asked;+ /* what a file is (its length and size: `film-facts`) is the file's own, never its copy's */+ const file = (query?.has('film-facts') ? null : swap?.(asked)) ?? asked;let stat;try { stat = statSync(file); } catch { res.writeHead(404, extraHeaders).end('not found'); return true; }if (stat.isDirectory()) { res.writeHead(302, { ...extraHeaders, location: `${path}/` }).end(); return true; }@@ -127,14 +131,14 @@ export function folderFiles(root, { inject = `<script>${HOST_FLAG}</script>`, ticonst within = (folder, path) => path === folder || path.startsWith(folder.endsWith(sep) ? folder : folder + sep);-/** The file an address names inside `root` (not through a link out of it), or null. */+/** The file an address names inside `root` (not through a link out of it, but for media the person linked), or null. */function fileInRoot(root, address) {let rel;try { rel = decodeURIComponent(address); } catch { return null; }if (!rel.startsWith('/') || rel.includes('\\') || rel.includes('\0')) return null;const file = normalize(join(root, rel));if (!file.startsWith(root + sep)) return null;- try { return within(realpathSync(root), realpathSync(file)) && statSync(file).isFile() ? file : null; } catch { return null; }+ try { return (within(realpathSync(root), realpathSync(file)) || readableLink(root, file)) && statSync(file).isFile() ? file : null; } catch { return null; }}/** @type {Map<string, Promise<number | null>>} */@@ -335,7 +339,7 @@ export class FilmPage {/* a page without a size of its own, opened on its own, is 1920 × 1080 (inside a film it is the stage's); onewithout a duration has no end (null) */const sized = a.width != null || a.height != null;- return { duration: a.duration ?? null, width: sized ? a.width : 1920, height: sized ? a.height : 1080,+ return { duration: a.duration ?? null, width: sized ? a.width : 1920, height: sized ? a.height : 1080, sized,/* an edit's sound, from the built-in timeline (a single page has none) */sounds: window.__filmSounds?.() ?? [] };}), readyMs, `film.ready did not finish within ${readyMs / 1000} s`).catch(async (e) => {diff --git a/packages/openfilm/src/media-links.mjs b/packages/openfilm/src/media-links.mjsnew file mode 100644index 0000000..3476440--- /dev/null+++ b/packages/openfilm/src/media-links.mjs@@ -0,0 +1,68 @@+// @ts-check+/**+ * Media kept elsewhere (a NAS, another disk), linked into a project rather than copied: a link in its assets/ folder+ * that points at the file or folder, so the film names it by a project path like any other.+ *+ * A link out of a project is followed only to a place the person linked on this computer, kept in Studio's home+ * (`links.json`): a project from elsewhere (a download, a zip) can carry a link to any of the person's files, and the+ * pages in it are code that could read what it reaches. Only reading goes through a link; nothing is written there.+ */+import { mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, isAbsolute, join, relative, sep } from 'node:path';++/** Studio's home: OPENFILM_HOME, else ~/.openfilm (studio/server/projects.mjs studioHome). */+const home = () => process.env.OPENFILM_HOME || join(homedir(), '.openfilm');+const file = () => join(home(), 'links.json');++/** @type {{ at: string, mtime: number, places: string[] } | null} */+let kept = null;++/** The places the person linked, as real paths. */+export function linkedPlaces() {+ const at = file();+ let mtime = -1;+ try { mtime = statSync(at).mtimeMs; } catch { /* none yet */ }+ if (kept && kept.at === at && kept.mtime === mtime) return kept.places;+ /** @type {string[]} */+ let places = [];+ try {+ const raw = JSON.parse(readFileSync(at, 'utf8'));+ places = Array.isArray(raw?.places) ? raw.places.filter((/** @type {unknown} */ p) => typeof p === 'string' && isAbsolute(p)) : [];+ } catch { /* none, or unreadable: none */ }+ kept = { at, mtime, places };+ return places;+}++/** Remember places the person linked (files or folders, followed to where they really are). @param {string[]} paths */+export function addLinkedPlaces(paths) {+ const places = new Set(linkedPlaces());+ for (const path of paths) {+ try { places.add(realpathSync.native(path)); } catch { /* gone meanwhile: nothing to allow */ }+ }+ const at = file();+ mkdirSync(dirname(at), { recursive: true });+ const tmp = `${at}.${process.pid}.tmp`;+ writeFileSync(tmp, `${JSON.stringify({ places: [...places].sort() }, null, 2)}\n`, { mode: 0o600 });+ renameSync(tmp, at);+ kept = null;+}++/** Whether `real` (a real path) is a place the person linked, or inside one. @param {string} real */+export function linkAllowed(real) {+ return linkedPlaces().some((place) => {+ const back = relative(place, real);+ return !back || (back.split(sep)[0] !== '..' && !isAbsolute(back));+ });+}++/**+ * Whether a project path that leads out of the project may be read: it is in the project's assets/ folder, and where+ * it really leads is a place the person linked. `abs` is the path as written; the project is `root`.+ * @param {string} root @param {string} abs+ */+export function readableLink(root, abs) {+ const back = relative(root, abs);+ if (back.split(sep)[0] !== 'assets' || back.startsWith('..') || isAbsolute(back)) return false;+ try { return linkAllowed(realpathSync.native(abs)); } catch { return false; }+}diff --git a/packages/openfilm/src/timeline.mjs b/packages/openfilm/src/timeline.mjsindex aa9e7c8..ca3c27c 100644--- a/packages/openfilm/src/timeline.mjs+++ b/packages/openfilm/src/timeline.mjs@@ -9,11 +9,15 @@ const own = new URL(location.href);own.searchParams.set('film-host', '0');const ownText = await (await fetch(own, { cache: 'no-store' })).text();const read = readFilmFile(ownText);-/* what the tracks are not (the stage, the styles): changed, the film is loaded again, not changed in place */-const head = filmHead(ownText);+/* what the tracks and the stage are not (the styles, the fonts): changed, the film is loaded again, not changed in+ place. The stage is the viewport's size, and changes in place (see change) */+const VIEWPORT = /<meta\b[^>]*\bname\s*=\s*["']?viewport\b[^>]*>/i;+const styleOf = (text) => text.replace(VIEWPORT, '');+const head = styleOf(filmHead(ownText));if (!read.doc) throw new Error(read.problems.length === 1 ? read.problems[0] : `film.html has ${read.problems.length} problems:\n ${read.problems.join('\n ')}`);let doc = read.doc;-const stage = doc.stage;+/* the stage, the same object while the film is shown: an edit of its size changes it in place (see reshape) */+const stage = { ...doc.stage };Object.assign(document.body.style, { width: stage.w + 'px', height: stage.h + 'px', margin: '0', overflow: 'hidden', position: 'relative' });/* the clips' elements, in the order the file has them (the reading above checked that is all a track holds) */const CLIP_TAGS = new Set(['iframe', 'video', 'img', 'audio']);@@ -33,7 +37,10 @@ async function limited(fn) {try { return await fn(); } finally { loadsBusy--; loadsWaiting.shift()?.(); }}-/** Each media file's own length and picture size, read once (the clips of one recording share it); null: unreadable. */+/**+ * Each media file's own length and picture size, read once (the clips of one recording share it); null: unreadable.+ * Asked as `?film-facts`: a host that plays a lighter copy in a file's place (a proxy) answers this with the file.+ */const factsBySrc = new Map();function factsOf(src) {const href = url(src).href;@@ -45,7 +52,9 @@ function factsOf(src) {const done = (facts) => { m.removeAttribute('src'); m.load(); ok(facts); };m.onloadedmetadata = () => done({ duration: m.duration, w: m.videoWidth, h: m.videoHeight });m.onerror = () => done(null);- m.src = href;+ const facts = new URL(href);+ facts.searchParams.set('film-facts', '1');+ m.src = facts.href;})));}return factsBySrc.get(href);@@ -151,23 +160,36 @@ function override(c, list = []) {}if (o.text != null) {const saved = (touch(el, 'translate'), c.touched.get(el));- const parts = [...el.childNodes].filter((n) => n.nodeType === 3 && n.data.trim());- saved.texts ??= el.childElementCount === 0 ? el.textContent : parts.map((n) => [n, n.data]);- /* a heading with inline parts (`Quiet<br><em>you</em>`): its own words change, the parts stay */- if (el.childElementCount === 0) { if (el.textContent !== o.text) el.textContent = o.text; }- else parts.forEach((n, k) => { n.data = k ? '' : o.text; });+ if ([...el.children].every((ch) => ch.localName === 'br')) {+ /* words alone, or lines between <br>s: all of them change, a <br> at each line break (SPEC §1) */+ saved.nodes ??= [...el.childNodes];+ if (linesOf(el) !== o.text) {+ const doc = el.ownerDocument;+ el.replaceChildren(...o.text.split('\n').flatMap((line, k) => (k ? [doc.createElement('br'), doc.createTextNode(line)] : [doc.createTextNode(line)])));+ }+ } else {+ const parts = [...el.childNodes].filter((n) => n.nodeType === 3 && n.data.trim());+ saved.texts ??= parts.map((n) => [n, n.data]);+ /* a heading with other inline parts (`Quiet<br><em>you</em>`): its own words change, the parts stay */+ parts.forEach((n, k) => { n.data = k ? '' : o.text; });+ }}}}}+/** An element's words with a line break for each <br>, as a `text` override writes them. */+function linesOf(el) {+ return [...el.childNodes].map((n) => (n.nodeType === 3 ? n.data : n.localName === 'br' ? '\n' : '')).join('');+}+/** Put back what a clip's tweaks changed (before a changed list is applied, or when it is taken away). */function restore(c) {for (const [el, saved] of c.touched) {for (const [prop, [value, priority]] of saved.props) {if (value) el.style.setProperty(prop, value, priority); else el.style.removeProperty(prop);}- if (typeof saved.texts === 'string') el.textContent = saved.texts;+ if (saved.nodes) el.replaceChildren(...saved.nodes);else if (saved.texts) for (const [node, data] of saved.texts) node.data = data;}c.touched = new Map();@@ -175,6 +197,8 @@ function restore(c) {}const SAME_TIME = 1e-4; // s: a video's currentTime is kept to the microsecond, so a time set is read back a hair off+const PRESENT_MS = 1000; // how long a sought frame may take to be on screen before the seek is made again+const SEEK_TRIES = 3;/*** Put a video on the frame at `t` and wait until that frame is the one on screen. `seeked` fires when the decoder@@ -198,22 +222,35 @@ async function showVideoAt(v, t, frame = null) {with a quarter frame to spare for footage whose frames are not all as long; without the frame's length, the oldframe is the one nearer where the video was than where it is sought (a frame there would look the same) */const right = (m) => (frame ? m <= t + 0.002 && t + 0.001 - m < frame * 1.25 : sought || Math.abs(m - t) <= Math.abs(m - before));- const presented = typeof v.requestVideoFrameCallback === 'function'- ? new Promise((done) => {- const next = () => v.requestVideoFrameCallback((now, meta) => { if (right(meta.mediaTime)) done(); else next(); });- next();- setTimeout(done, 3000);- })- : null;- v.currentTime = t;- await new Promise((done) => {- if (!v.seeking && v.readyState >= 2) { done(); return; }- v.addEventListener('seeked', done, { once: true });- v.addEventListener('loadeddata', done, { once: true });- setTimeout(done, 10000);- });- sought = true;- if (presented) await presented;+ const callback = typeof v.requestVideoFrameCallback === 'function';+ /* a seek made just after the file loaded can decode its frame and never present it (Chromium): the picture stays on+ the frame it had (the clip's first, where it was woken), however long it is waited for. Not presented in a+ moment, the seek is made again; the last try waits as long as a slow machine may need */+ for (let tries = 1; ; tries++) {+ const last = tries === SEEK_TRIES || !callback;+ let handle = 0;+ let timer = 0;+ const presented = callback+ ? new Promise((done) => {+ const next = () => { handle = v.requestVideoFrameCallback((now, meta) => { if (right(meta.mediaTime)) done(true); else next(); }); };+ next();+ timer = setTimeout(() => done(false), last ? 3000 : PRESENT_MS);+ })+ : null;+ /* again, half a millisecond on (the same frame): a seek to where the element already is may be skipped */+ v.currentTime = t + (tries - 1) * 0.0005;+ await new Promise((done) => {+ if (!v.seeking && v.readyState >= 2) { done(); return; }+ v.addEventListener('seeked', done, { once: true });+ v.addEventListener('loadeddata', done, { once: true });+ setTimeout(done, 10000);+ });+ sought = true;+ const shown = presented ? await presented : true;+ clearTimeout(timer);+ if (handle) v.cancelVideoFrameCallback?.(handle);+ if (shown || last) return;+ }}/**@@ -664,12 +701,12 @@ function sectionOf(ti, track) {/*** The film after an edit, changed in place: clips kept (by id, with the same source) take their new fields, clips* added get elements and load (a video's file only once the playhead comes near), clips gone are taken out. False- * when the film has to be loaded again: another stage or head, or a clip that cannot load (that says why).+ * when the film has to be loaded again: another head (its styles), or a clip that cannot load (that says why). Another+ * stage is changed in place too (reshape).*/async function change(value, look) {- if (look != null && look !== head) return false;+ if (look != null && styleOf(look) !== head) return false;const next = parseFilm(value);- if (next.stage.w !== stage.w || next.stage.h !== stage.h) return false;const rows = next.tracks.flatMap((track, ti) => track.clips.map((row) => ({ row, track, ti })));const byId = new Map(clips.map((c) => [c.id, c]));const kept = (row) => { const c = byId.get(row.id); return c && c.src === row.src && c.kind === kindOf(row) ? c : null; };@@ -697,7 +734,7 @@ async function change(value, look) {await Promise.race([ready, late]);clearTimeout(timer);}- try { doc = next; rows.forEach(({ row, track, ti }, i) => settle(records[i], row, track, ti)); }+ try { reshape(next.stage); doc = next; rows.forEach(({ row, track, ti }, i) => settle(records[i], row, track, ti)); }catch { return false; }/* what the change put on at the moment shown and made ready shows now, with the clips it took away going: thepicture changes at once, not first without them until that moment is drawn again */@@ -719,6 +756,18 @@ async function change(value, look) {window.__filmEditor.stage.updated?.();return true;}+/**+ * The stage at another size, in place: the body, the viewport and what the film says of its size. Every clip is+ * placed again after (settle): a picture without a box fills the new stage, a page without a size of its own is laid+ * out at it, a boxed one stays where its box says.+ */+function reshape(next) {+ if (next.w === stage.w && next.h === stage.h) return;+ stage.w = next.w; stage.h = next.h;+ Object.assign(document.body.style, { width: stage.w + 'px', height: stage.h + 'px' });+ document.querySelector('meta[name="viewport"]')?.setAttribute('content', `width=${stage.w}, height=${stage.h}`);+ window.film.width = stage.w; window.film.height = stage.h;+}/* edits are changed in the order they came, each once the one before is done */let changing = Promise.resolve(true);diff --git a/packages/openfilm/src/timeline.test.mjs b/packages/openfilm/src/timeline.test.mjsindex aa34ebe..ae959c4 100644--- a/packages/openfilm/src/timeline.test.mjs+++ b/packages/openfilm/src/timeline.test.mjs@@ -6,7 +6,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { FilmPage, launch, serve } from './host.mjs';import { open } from './shared.mjs';-import { filmHtml } from './film-doc.mjs';+import { filmHead, filmHtml } from './film-doc.mjs';const page = (word, seconds) => `<!doctype html><body style="margin:0;background:#123"><p>${word}</p><script>window.film={duration:${seconds},width:320,height:180,frame(){}}</script></body>`;@@ -293,6 +293,37 @@ test('an exact frame of a video sought there waits for its own frame on screen,}});+test('a sought frame that is decoded but never presented (a seek just after loading, Chromium) is sought again until it shows', { skip: !hasFfmpeg && 'no ffmpeg', timeout: 60_000 }, async () => {+ const dir = footage('of-unshown-frame-');+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'v', src: 'a.mp4', at: 1, time: [0, 4] }] }] }));+ const s = await open(dir);+ try {+ const seen = await s.film.page.evaluate(async () => {+ const v = document.querySelector('video');+ await window.film.frame(1);+ /* the first seek's frame is never said to be presented (the picture stays where it was); the next ones are */+ const real = v.requestVideoFrameCallback.bind(v);+ let swallowed = false;+ v.requestVideoFrameCallback = (callback) => {+ if (swallowed) return real(callback);+ swallowed = true;+ return 0;+ };+ const seeks = [];+ v.addEventListener('seeking', () => seeks.push(v.currentTime));+ const t0 = performance.now();+ await window.film.frame(3.25);+ return { seeks, ms: performance.now() - t0, at: v.currentTime };+ });+ assert.equal(seen.seeks.length, 2, `sought again once: ${JSON.stringify(seen)}`);+ assert.ok(Math.abs(seen.at - 2.25) < 0.002, `on the frame for 2.25 s: ${seen.at}`);+ /* the second seek is shown at once: not the last try's long wait */+ assert.ok(seen.ms < 2500, `${Math.round(seen.ms)} ms`);+ } finally {+ await s.close();+ }+});+test('a video woken ahead while hidden, then shown: its old frame presented again after the seek is not taken for the sought one', { skip: !hasFfmpeg && 'no ffmpeg', timeout: 60_000 }, async () => {const dir = footage('of-stale-frame-');writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'v', src: 'a.mp4', at: 2, time: [0, 4] }] }] }));@@ -363,15 +394,77 @@ test('an edit that splits, adds, removes or moves clips to a new track changes tassert.equal(await s.film.page.evaluate(() => document.querySelector('#v0')), null, 'the deleted clip\'s element is gone');await s.film.seek(1);assert.equal(await s.film.page.evaluate(() => document.querySelector('#title').style.visibility), 'visible', 'the new page draws');- /* a file that is not there, or another stage: the film is loaded again (which says why) */+ /* a file that is not there: the film is loaded again (which says why) */assert.equal(await update({ ...film, tracks: [...film.tracks, { clips: [{ id: 'gone', src: 'gone.mp4' }] }] }), false);- assert.equal(await update({ ...film, stage: { w: 640, h: 360 } }), false);assert.equal(await s.film.page.evaluate(() => window.__same), true, 'the same page all along');} finally {await s.close();}});+test('another stage size changes the film in place: the body, the film\'s size and every clip placed again', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-reshape-'));+ writeFileSync(join(dir, 'wide.html'), `<!doctype html><body style="margin:0"><script>window.film={duration:2,frame(){}}</script></body>`);+ writeFileSync(join(dir, 'chip.html'), page('chip', 2).replace('width:320,height:180', 'width:80,height:40'));+ const film = { stage: { w: 320, h: 180 }, tracks: [+ { clips: [{ id: 'chip', src: 'chip.html', box: { x: 20, y: 30, w: 80 } }] },+ { clips: [{ id: 'wide', src: 'wide.html' }] },+ ] };+ writeFileSync(join(dir, 'film.html'), filmHtml(film));+ const s = await open(dir);+ const frames = () => s.film.page.evaluate(() => [...document.querySelectorAll('iframe')].map((el) => {+ const r = el.getBoundingClientRect();+ return [el.id, el.contentWindow.innerWidth, el.contentWindow.innerHeight, r.left, r.top, r.width, r.height];+ }));+ try {+ await s.film.page.evaluate(() => { window.__same = true; });+ /* 3:4, as Studio writes it: the wide page keeps 320 × 180 as its size, scaled into its box */+ film.stage = { w: 240, h: 320 };+ film.tracks[1].clips[0] = { id: 'wide', src: 'wide.html', size: { w: 320, h: 180 }, box: { x: 0, y: 92, w: 240, h: 135 } };+ /* the head as Studio tells it after writing the file: only its viewport changed */+ const head = filmHead(filmHtml(film));+ assert.equal(await s.film.page.evaluate(([v, h]) => window.__filmEditor.update(v, h), [film, head]), true);+ await s.film.seek(1);+ assert.deepEqual(await s.film.page.evaluate(() => [document.body.style.width, document.body.style.height, window.film.width, window.film.height]), ['240px', '320px', 240, 320]);+ assert.deepEqual(await frames(), [['chip', 80, 40, 20, 30, 80, 40], ['wide', 320, 180, 0, 92, 240, 135]]);+ /* a page without a size of its own or of its clip is laid out at the new stage */+ film.tracks[1].clips[0] = { id: 'wide', src: 'wide.html' };+ assert.equal(await s.film.page.evaluate((v) => window.__filmEditor.update(v), film), true);+ await s.film.seek(1);+ assert.deepEqual((await frames())[1], ['wide', 240, 320, 0, 0, 240, 320]);+ /* other styles in the head: the film has to be loaded again */+ assert.equal(await s.film.page.evaluate(([v, h]) => window.__filmEditor.update(v, h), [film, filmHead(filmHtml(film)).replace('</head>', '<style>p{color:red}</style></head>')]), false);+ assert.equal(await s.film.page.evaluate(() => window.__same), true, 'the same page all along');+ } finally {+ await s.close();+ }+});++test('a text override with line breaks: all the words of an element of <br>s, a <br> at each break; taken away, it is as it was', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-lines-'));+ writeFileSync(join(dir, 'title.html'), `<!doctype html><body style="margin:0"><h1 id="a">Start here,<br>make your film.</h1><p id="b">One line</p><p id="c">Quiet <em>you</em></p>+<script>window.film={duration:2,frame(){}}</script></body>`);+ const film = { stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'title', src: 'title.html', overrides: [+ { at: '#a', text: 'From here,\nyour own\nfilm.' }, { at: '#b', text: 'Two\nlines' }, { at: '#c', text: 'Loud' },+ ] }] }] };+ writeFileSync(join(dir, 'film.html'), filmHtml(film));+ const s = await open(dir);+ const html = () => s.film.page.evaluate(() => {+ const doc = document.querySelector('iframe').contentDocument;+ return ['a', 'b', 'c'].map((id) => doc.getElementById(id).innerHTML);+ });+ try {+ await s.film.seek(1);+ assert.deepEqual(await html(), ['From here,<br>your own<br>film.', 'Two<br>lines', 'Loud<em>you</em>']);+ film.tracks[0].clips[0].overrides = [];+ assert.equal(await s.film.page.evaluate((v) => window.__filmEditor.update(v), film), true);+ await s.film.seek(1);+ assert.deepEqual(await html(), ['Start here,<br>make your film.', 'One line', 'Quiet <em>you</em>']);+ } finally {+ await s.close();+ }+});+test('a host waits for a film as long as it keeps loading; a page that never gets further fails in time', { timeout: 60_000 }, async () => {const dir = mkdtempSync(join(tmpdir(), 'of-progress-'));/* five pages ready one after another, 0.5 s apart: 2.5 s in all, longer than the host waits without news */diff --git a/packages/openfilm/studio/server/derived.mjs b/packages/openfilm/studio/server/derived.mjsindex d1f6417..f58ea08 100644--- a/packages/openfilm/studio/server/derived.mjs+++ b/packages/openfilm/studio/server/derived.mjs@@ -12,7 +12,7 @@ import { createHash } from 'node:crypto';import { existsSync } from 'node:fs';import { mkdir, readFile, rename, rm, stat } from 'node:fs/promises';import { join } from 'node:path';-import { inside } from './files.mjs';+import { readable } from './files.mjs';import { TOOL_DIR } from './projects.mjs';import { writeAtomic } from './atomic.mjs';@@ -51,7 +51,7 @@ async function tool(/** @type {'ffmpeg' | 'ffprobe'} */ name, /** @type {string[/** The file, and the cache key that changes when it does. */async function source(/** @type {string} */ root, /** @type {string} */ rel) {- const abs = inside(root, rel);+ const abs = readable(root, rel);const info = await stat(abs).catch(() => null);if (!info?.isFile()) throw new MediaError(`${rel} is not there`, 404);const key = createHash('sha1').update(`${rel}\0${info.size}\0${Math.round(info.mtimeMs)}`).digest('hex').slice(0, 20);@@ -70,21 +70,27 @@ async function cached(/** @type {string} */ root, /** @type {string} */ kind, /*}/**- * Length and picture size of a media file: `{ duration (s), width, height, fps, audio }`; a still has no duration.+ * Length and picture size of a media file: `{ duration (s), width, height, fps, audio, codec, pixfmt }`; a still has no+ * duration. The size is the picture as it is shown: a video turned a quarter (a phone's portrait video) has its sides+ * swapped. `codec` and `pixfmt` are its picture's (proxies.mjs tells heavy footage by them).* @param {string} root @param {string} rel*/export async function probe(root, rel) {const { abs, key } = await source(root, rel);- const bytes = await cached(root, 'probe', `${key}.json`, async () => {+ /* `.3`: since the size is as shown (an older answer has a turned video's sides as stored), with the codec */+ const bytes = await cached(root, 'probe', `${key}.3.json`, async () => {const out = JSON.parse((await tool('ffprobe', ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', abs])).toString());const video = out.streams?.find((/** @type {{ codec_type: string }} */ s) => s.codec_type === 'video');const audio = out.streams?.some((/** @type {{ codec_type: string }} */ s) => s.codec_type === 'audio');const [n, d] = String(video?.avg_frame_rate ?? '0/1').split('/').map(Number);const duration = Number(out.format?.duration);+ const turn = Number(video?.side_data_list?.find((/** @type {{ rotation?: number }} */ s) => s.rotation != null)?.rotation ?? video?.tags?.rotate ?? 0);+ const quarter = Math.abs(Math.round(turn / 90)) % 2 === 1;return Buffer.from(JSON.stringify({...(Number.isFinite(duration) && duration > 0 && !/image|png|mjpeg/.test(String(out.format?.format_name)) ? { duration } : {}),- ...(video ? { width: video.width, height: video.height } : {}),+ ...(video ? (quarter ? { width: video.height, height: video.width } : { width: video.width, height: video.height }) : {}),...(d && n ? { fps: Math.round((n / d) * 100) / 100 } : {}),+ ...(video?.codec_name ? { codec: String(video.codec_name), pixfmt: String(video.pix_fmt ?? '') } : {}),audio: Boolean(audio),}));});diff --git a/packages/openfilm/studio/server/derived.test.mjs b/packages/openfilm/studio/server/derived.test.mjsindex 4c1c334..9cda345 100644--- a/packages/openfilm/studio/server/derived.test.mjs+++ b/packages/openfilm/studio/server/derived.test.mjs@@ -24,11 +24,21 @@ test('probe: length, picture size, frame rate and sound of a video; a sound hasassert.equal(video.fps, 25);assert.ok(Math.abs(video.duration - 2) < 0.1);assert.equal(video.audio, true);+ assert.deepEqual([video.codec, video.pixfmt], ['h264', 'yuv420p']);const sound = await probe(root, 'assets/tone.wav');assert.equal(sound.width, undefined);assert.ok(Math.abs(sound.duration - 2) < 0.05);});+test('probe: a still\'s size, and a video turned a quarter (a phone\'s portrait video) as it is shown', { skip: !hasFfmpeg && 'no ffmpeg' }, async () => {+ execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'testsrc=size=300x200', '-frames:v', '1', join(root, 'assets', 'still.png')]);+ const still = await probe(root, 'assets/still.png');+ assert.deepEqual([still.width, still.height, still.duration], [300, 200, undefined]);+ execFileSync('ffmpeg', ['-v', 'error', '-display_rotation', '90', '-i', join(root, 'assets', 'clip.mp4'), '-c', 'copy', join(root, 'assets', 'turned.mp4')]);+ const turned = await probe(root, 'assets/turned.mp4');+ assert.deepEqual([turned.width, turned.height], [180, 320]);+});+test('poster and frames are JPEG, cached until the file changes', { skip: !hasFfmpeg && 'no ffmpeg' }, async () => {const jpeg = await poster(root, 'assets/clip.mp4');assert.deepEqual([...jpeg.subarray(0, 2)], [0xff, 0xd8]);diff --git a/packages/openfilm/studio/server/exports.mjs b/packages/openfilm/studio/server/exports.mjsindex 2eda321..a3ad28f 100644--- a/packages/openfilm/studio/server/exports.mjs+++ b/packages/openfilm/studio/server/exports.mjs@@ -31,11 +31,13 @@* plain transcript); refused when the film has none* { kind: 'slides', format?: 'pptx' (default) | 'pdf', frame?, fill?, shortEdge? (default 1080), at?: number[] }* the scene stills bound as a deck (the scene's name in the speaker notes) or a PDF, one page each- * { kind: 'nle', fps? (snapped to 23.976, 24, 25, 29.97, 30, 50, 59.94 or 60; default 30), audio?: 'clips' (default)- * | 'stems', media?: 'copy' (default) | 'link', subtitles?: boolean (default true) }+ * { kind: 'nle', format?: 'xml' (default) | 'jianying' | 'capcut', fps? (snapped to 23.976, 24, 25, 29.97, 30, 50, 59.94 or 60;+ * default 30), audio?: 'clips' (default) | 'stems', media?: 'copy' (default) | 'link', subtitles?: boolean (default true) }* a folder an editing program opens (see nle.mjs): `<name>.xml` (xmeml: Premiere Pro, DaVinci Resolve), each* web page rendered to a ProRes 4444 with alpha in media/, footage, stills and sounds cloned there (`link`:- * pointed at where they are), the sound as clips or as mixed stems, `<name>.srt` when there are subtitles+ * pointed at where they are), the sound as clips or as mixed stems, `<name>.srt` when there are subtitles.+ * `jianying`, `capcut`: the same timeline as a 剪映 or CapCut draft (see jianying.mjs), made in the app's drafts folder when this+ * computer has one (else in the exports folder, to be moved there), its subtitles a text track** { kind: 'project', parts?: ('history' | 'chat' | 'logs')[], as?: 'zip' (default) | 'folder' }* the project itself, to hand on or keep (see projectFiles): its work always, the parts asked besides; a zip@@ -57,6 +59,7 @@ import { FilmPage, launch } from '../../src/host.mjs';import { filmSound, kill as killProcess, mix, open } from '../../src/shared.mjs';import { FILM_FILE, clipFade, filmHtml, fittedFade, kindOf, pictureRect, readFilmFile } from '../../src/film-doc.mjs';import { NLE_FPS, nleFps, planNleTimeline, probeSource, soundStem, xmemlDocument } from './nle.mjs';+import { draftsRoot, jianyingDraft } from './jianying.mjs';import { slidesPdf, writePptx } from './slides.mjs';import { subtitlesForExport } from './captions.mjs';import { filmSubtitleCuesInRange, filmSubtitleShown, filmSubtitleSrt, filmSubtitleTranscript, filmSubtitleVtt } from './film-subtitle.mjs';@@ -85,7 +88,7 @@ export const exportsRoot = () => process.env.OPENFILM_EXPORTS* @typedef {Framing & { kind: 'poster', format?: 'png' | 'jpg', shortEdge?: number, at?: number }} PosterAsk* @typedef {{ kind: 'subtitles', format?: 'srt' | 'vtt' | 'txt' }} SubtitlesAsk* @typedef {Framing & { kind: 'slides', format?: 'pptx' | 'pdf', shortEdge?: number, at?: number[] }} SlidesAsk- * @typedef {{ kind: 'nle', fps?: number, audio?: 'clips' | 'stems', media?: 'copy' | 'link', subtitles?: boolean }} NleAsk+ * @typedef {{ kind: 'nle', format?: 'xml' | 'jianying' | 'capcut', fps?: number, audio?: 'clips' | 'stems', media?: 'copy' | 'link', subtitles?: boolean }} NleAsk* @typedef {{ kind: 'project', parts?: ProjectPart[], as?: 'zip' | 'folder' }} ProjectAsk* @typedef {typeof PROJECT_PARTS[number]} ProjectPart* @typedef {VideoAsk | GifAsk | AudioAsk | StillsAsk | PosterAsk | SubtitlesAsk | SlidesAsk | NleAsk | ProjectAsk} ExportSpec@@ -139,6 +142,11 @@ export async function exportCapabilities() {};}+/** 剪映's or CapCut's drafts folder on this computer, or null. @param {'jianying' | 'capcut'} app */+const defaultDrafts = (app) => draftsRoot(app, { home: homedir(), localAppData: process.env.LOCALAPPDATA, exists: existsSync });+/** Which of 剪映 and CapCut are on this computer (their drafts folders are there): an editing project goes into its drafts. */+export const draftApps = () => ({ jianying: Boolean(defaultDrafts('jianying')), capcut: Boolean(defaultDrafts('capcut')) });+/* ── delivery frames (the same arithmetic as the editor's lib/film-frame.ts) ── *//** A frame written `W:H` ("16:9", "2.39:1"), from 1:4 to 4:1: its width ÷ height, or null. @param {unknown} frame */@@ -152,21 +160,27 @@ const MAX_DIM = 4096;const even = (/** @type {number} */ n) => Math.max(2, Math.round(n / 2) * 2);/**- * The film (`stage`) fitted into a delivery frame: the frame's size (its long side follows the film's) and the film's- * scale inside it (`contain`: whole, with bars; `cover`: filling it, the overflow cut).- * @param {{ w: number, h: number }} stage @param {string} frame @param {'contain' | 'cover'} fill+ * The film (`stage`) fitted into a delivery frame: the frame's size (its long side follows the film's), its exact+ * shape (`ratio`: the frame's own, not its even-rounded pixels'), and the film's scale inside it (`contain`: whole,+ * with bars; `cover`: filling it, the overflow cut).+ * @param {{ w: number, h: number, ratio?: number }} stage @param {string} frame @param {'contain' | 'cover'} fill*/export function frameBox(stage, frame, fill) {const ratio = frame === 'native' ? null : frameRatio(frame);- if (ratio == null) return { w: even(stage.w), h: even(stage.h), scale: 1 };+ /* native: the stage's own shape (a frame drawn as a page, with subtitles over it, keeps the frame's exact one) */+ if (ratio == null) return { w: even(stage.w), h: even(stage.h), ratio: stage.ratio ?? stage.w / Math.max(1, 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) };+ return { w, h, ratio, scale: fill === 'cover' ? Math.max(w / stage.w, h / stage.h) : Math.min(w / stage.w, h / stage.h) };}-/** A box's size with its short side at `shortEdge` (even, no side over 4096). @param {{ w: number, h: number }} box @param {number} shortEdge */+/**+ * A box's size with its short side at `shortEdge` (even, no side over 4096), in the box's exact shape: a 16:9 frame+ * at 1080 is 1920 × 1080, whatever its rounded pixels around a 2:1 film.+ * @param {{ w: number, h: number, ratio?: number }} box @param {number} shortEdge+ */export function dimsForShortEdge(box, shortEdge) {- const r = box.w / Math.max(1, box.h);+ const r = box.ratio ?? box.w / Math.max(1, box.h);let w, h;if (r >= 1) { h = even(shortEdge); w = even(h * r); } else { w = even(shortEdge); h = even(w / r); }if (w > MAX_DIM || h > MAX_DIM) {@@ -176,9 +190,9 @@ export function dimsForShortEdge(box, shortEdge) {return { w, h };}-/** A GIF's size: its long side at `width`. @param {{ w: number, h: number }} box @param {number} width */+/** A GIF's size: its long side at `width`. @param {{ w: number, h: number, ratio?: number }} box @param {number} width */function gifDims(box, width) {- const r = box.w / Math.max(1, box.h);+ const r = box.ratio ?? box.w / Math.max(1, box.h);return r >= 1 ? { w: even(width), h: even(width / r) } : { w: even(width * r), h: even(width) };}@@ -232,7 +246,7 @@ function baseName(project, ask) {}case 'stills': return `${base} stills`;case 'poster': return `${base} poster`;- case 'nle': return `${base} · Editor XML`;+ case 'nle': return ask.format === 'jianying' || ask.format === 'capcut' ? base : `${base} · Editor XML`;default: return `${base}${range}`;}}@@ -292,6 +306,7 @@ function checked(/** @type {ExportAsk} */ ask) {break;case 'nle':if (ask.range !== undefined) throw new ExportError('an editor gets the whole timeline: no range');+ if (ask.format !== undefined && !['xml', 'jianying', 'capcut'].includes(ask.format)) throw new ExportError('format: xml, jianying or capcut');if (!between(ask.fps, 1, 120)) throw new ExportError(`fps: ${NLE_FPS.join(', ')}`);if (ask.audio !== undefined && ask.audio !== 'clips' && ask.audio !== 'stems') throw new ExportError('audio: clips or stems');if (ask.media !== undefined && ask.media !== 'copy' && ask.media !== 'link') throw new ExportError('media: copy or link');@@ -718,9 +733,11 @@ async function rasterize(browser, file, w, h, out) {/*** The export queue. `onChange(job)` is told every change of a job (its progress included), for the pages watching.* `captions(root)`: a film's subtitle cues and the person's style for them (captions.mjs by default).- * @param {{ onChange?: (job: ExportJob) => void, captions?: (root: string) => Promise<{ cues: Cue[], style: SubtitleStyle }> }} [options]+ * `drafts(app)`: 剪映's or CapCut's drafts folder, where its draft goes (null: the exports folder); this computer's by default.+ * @param {{ onChange?: (job: ExportJob) => void, captions?: (root: string) => Promise<{ cues: Cue[], style: SubtitleStyle }>,+ * drafts?: (app: 'jianying' | 'capcut') => string | null }} [options]*/-export function createExports({ onChange = () => {}, captions = subtitlesForExport } = {}) {+export function createExports({ onChange = () => {}, captions = subtitlesForExport, drafts = defaultDrafts } = {}) {/** @type {ExportJob[]} */const jobs = [];/** @type {Map<string, { root: string, folder: string, abort: AbortController }>} */@@ -936,8 +953,8 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpoconst probe = await open(burn ? burn.dir : root, burn ? { root } : {}).catch(async (e) => { await burn?.remove(); throw e; });try {const meta = probe.film.meta;- const stage = { w: meta.width, h: meta.height };/* with subtitles, the frame is the page drawn */+ const stage = burn ? burn.box : { w: meta.width, h: meta.height };const frame = burn ? 'native' : ask.frame ?? 'native', fill = ask.fill ?? 'contain';const box = frameBox(stage, frame, fill);const size = dimsForShortEdge(box, ask.shortEdge ?? Math.min(box.w, box.h));@@ -1048,11 +1065,15 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo/*** The timeline for an editing program: a folder with the xmeml, the media it points at, and the subtitles as SRT- * (see nle.mjs). Made in a hidden folder beside it and moved into place when whole.- * @param {ExportJob} job @param {string} root @param {string} dir @param {AbortSignal} signal+ * (see nle.mjs), or a 剪映 or CapCut draft (jianying.mjs) in the app's drafts folder. Made in a hidden folder beside it and moved+ * into place when whole.+ * @param {ExportJob} job @param {string} root @param {string} out @param {AbortSignal} signal*/- async function exportNle(job, root, dir, signal) {+ async function exportNle(job, root, out, signal) {const ask = /** @type {NleAsk} */ (job.ask);+ const app = ask.format === 'jianying' || ask.format === 'capcut' ? ask.format : null;+ /* a draft goes where its app lists its drafts, when the app is on this computer */+ const dir = (app && drafts(app)) || out;const fps = nleFps(ask.fps ?? 30);const mode = ask.audio ?? 'clips';const title = safeName(job.name);@@ -1202,17 +1223,26 @@ export function createExports({ onChange = () => {}, captions = subtitlesForExpo}update(job, { phase: 'finishing', progress: 0.98 });- if (ask.subtitles !== false) {- const srt = filmSubtitleSrt((await subtitlesOf(root).catch(() => ({ cues: [] }))).cues);+ const cues = ask.subtitles !== false ? (await subtitlesOf(root).catch(() => ({ cues: [] }))).cues : [];+ if (app) {+ /* the app on Windows reads draft_content.json, on a Mac draft_info.json: the same draft in both */+ const draft = jianyingDraft(timeline, { app, name: basename(final), folder: final, root: dir, cues });+ const info = JSON.stringify(draft.info);+ await writeFile(join(staging, 'draft_info.json'), info, 'utf8');+ await writeFile(join(staging, 'draft_content.json'), info, 'utf8');+ await writeFile(join(staging, 'draft_meta_info.json'), JSON.stringify(draft.meta), 'utf8');+ } else {+ const srt = filmSubtitleSrt(cues);if (srt) await writeFile(join(staging, `${title}.srt`), srt, 'utf8');+ await writeFile(join(staging, `${title}.xml`), xmemlDocument(timeline), 'utf8');}- await writeFile(join(staging, `${title}.xml`), xmemlDocument(timeline), 'utf8');if (signal.aborted) throw new Error('cancelled');if (!(await readdir(join(staging, 'media'))).length) await rmdir(join(staging, 'media'));await rename(staging, final);const media = existsSync(join(final, 'media')) ? (await readdir(join(final, 'media'))).sort().map((n) => join(final, 'media', n)) : [];- const top = (await readdir(final)).filter((n) => n !== 'media').sort((a, b) => Number(!a.endsWith('.xml')) - Number(!b.endsWith('.xml')) || a.localeCompare(b));- /* the XML first: "Show in Finder" shows the first */+ const first = app ? 'draft_info.json' : '.xml';+ const top = (await readdir(final)).filter((n) => n !== 'media').sort((a, b) => Number(!a.endsWith(first)) - Number(!b.endsWith(first)) || a.localeCompare(b));+ /* the XML (the draft) first: "Show in Finder" shows the first */const outputs = [...top.map((n) => join(final, n)), ...media];update(job, { out: outputs[0], outputs });} finally {diff --git a/packages/openfilm/studio/server/exports.test.mjs b/packages/openfilm/studio/server/exports.test.mjsindex b565177..e5de9f6 100644--- a/packages/openfilm/studio/server/exports.test.mjs+++ b/packages/openfilm/studio/server/exports.test.mjs@@ -194,10 +194,17 @@ test('a cancelled export stops and leaves no file, and a bad ask is refused befo});test('the delivery frame: the same box as the editor, the short side asked, never past 4096', () => {- assert.deepEqual(frameBox({ w: 1920, h: 1080 }, '9:16', 'contain'), { w: 1920, h: 3414, scale: 1 });+ assert.deepEqual(frameBox({ w: 1920, h: 1080 }, '9:16', 'contain'), { w: 1920, h: 3414, ratio: 9 / 16, scale: 1 });assert.deepEqual(dimsForShortEdge(frameBox({ w: 1920, h: 1080 }, '9:16', 'contain'), 1080), { w: 1080, h: 1920 });assert.deepEqual(dimsForShortEdge({ w: 1920, h: 1080 }, 2160), { w: 3840, h: 2160 });assert.deepEqual(dimsForShortEdge({ w: 2520, h: 1080 }, 2160), { w: 4096, h: 1756 });+ /* the frame's own shape, not its rounded pixels': 16:9 around a 2:1 film is 2160 × 1216, and comes out 1920 × 1080 */+ const wide = frameBox({ w: 2160, h: 1080 }, '16:9', 'contain');+ assert.deepEqual([wide.w, wide.h], [2160, 1216]);+ assert.deepEqual(dimsForShortEdge(wide, 1080), { w: 1920, h: 1080 });+ assert.deepEqual(dimsForShortEdge(wide, 2160), { w: 3840, h: 2160 });+ /* a frame drawn as a page (subtitles over it) keeps that shape */+ assert.deepEqual(dimsForShortEdge(frameBox(wide, 'native', 'contain'), 1080), { w: 1920, h: 1080 });});test('a film in another frame is fitted with bars, or fills it and is cropped', ffmpeg, async () => {@@ -504,6 +511,42 @@ test('editing software: an xmeml folder; pages rendered with alpha, footage placassert.ok(!xml.includes('<link>'), 'a stem is not linked to a picture');});+test('剪映: the same timeline as a draft in 剪映\'s drafts folder, its media beside it, subtitles a text track', { ...ffmpeg, timeout: 240_000 }, async () => {+ /* the Cut project the editing-software test made */+ const cut = join(scratch, 'Cut');+ const drafts = join(scratch, 'JianyingPro Drafts');+ mkdirSync(drafts, { recursive: true });+ const exports = createExports({ captions: subtitles, drafts: (app) => (app === 'jianying' ? drafts : null) });+ const done = await ended(exports, exports.start(project('Cut', cut), { kind: 'nle', format: 'jianying', fps: 25 }));+ assert.equal(done.status, 'done', done.error);+ const folder = join(drafts, 'Cut');+ assert.equal(done.out, join(folder, 'draft_info.json'));+ assert.deepEqual(readdirSync(folder).sort(), ['draft_content.json', 'draft_info.json', 'draft_meta_info.json', 'media']);+ assert.equal(readFileSync(join(folder, 'draft_content.json'), 'utf8'), readFileSync(join(folder, 'draft_info.json'), 'utf8'));+ assert.deepEqual(readdirSync(drafts).filter((n) => n.startsWith('.')), [], 'no half-made draft');+ const info = JSON.parse(readFileSync(done.out, 'utf8'));+ const meta = JSON.parse(readFileSync(join(folder, 'draft_meta_info.json'), 'utf8'));+ assert.deepEqual([meta.draft_name, meta.draft_fold_path, meta.draft_root_path, meta.draft_id], ['Cut', folder, drafts, info.id]);+ assert.deepEqual(info.canvas_config, { width: 320, height: 180, ratio: 'original' });+ assert.equal(info.fps, 25);+ /* every clip's material is a file in the draft's media folder */+ const materials = new Map([...info.materials.videos, ...info.materials.audios].map((m) => [m.id, m]));+ for (const seg of info.tracks.filter((t) => t.type !== 'text').flatMap((t) => t.segments)) {+ const m = materials.get(seg.material_id);+ assert.ok(m && existsSync(m.path) && m.path.startsWith(join(folder, 'media')), `${m?.path}`);+ }+ /* the footage plays its own sound at its level, so there is no second clip of it */+ const shot = info.tracks.flatMap((t) => t.segments).find((s) => materials.get(s.material_id)?.path.endsWith('shot one.mp4') && s.clip);+ assert.equal(shot.volume, 0.5);+ assert.deepEqual(shot.target_timerange, { start: 0, duration: 1_600_000 });+ assert.deepEqual(shot.source_timerange, { start: 400_000, duration: 1_600_000 });+ /* the muted bed comes muted */+ assert.equal(info.tracks.find((t) => t.type === 'audio' && t.name === 'Music').attribute, 1);+ const text = info.tracks.find((t) => t.type === 'text');+ assert.deepEqual(info.materials.texts.map((m) => JSON.parse(m.content).text), CUES.map((c) => c.text));+ assert.deepEqual(text.segments.map((s) => s.target_timerange.start), [0, 800_000]);+});+test('burned-in subtitles: drawn over the frame, bars included; a subtitle file beside the video', ffmpeg, async () => {/* the pixels of the bottom tenth of a picture that are near white (the title's own text is at the top) */const bright = (file) => {@@ -636,6 +679,7 @@ test('the API: where exports go and what can be made here; several at once; openassert.deepEqual(listed.exports, []);assert.equal(listed.folder, exportsRoot());assert.deepEqual(Object.keys(listed.can).sort(), ['h264', 'hevc', 'hevcAlpha', 'mp3', 'prores', 'vp9']);+ assert.deepEqual(Object.keys(listed.drafts).sort(), ['capcut', 'jianying'], 'whether 剪映 and CapCut are here, for an editing project');assert.equal(listed.subtitles, 0, 'no subtitle cues in a new project');const bad = await api(`/projects/${project.id}/exports`, { method: 'POST', body: { jobs: [{ kind: 'audio' }, { kind: 'slides', format: 'key' }] } });assert.equal(bad.status, 400);diff --git a/packages/openfilm/studio/server/fetch-error.mjs b/packages/openfilm/studio/server/fetch-error.mjsnew file mode 100644index 0000000..104fe72--- /dev/null+++ b/packages/openfilm/studio/server/fetch-error.mjs@@ -0,0 +1,14 @@+// @ts-check+/** Why fetching a film failed (fetch-repo.mjs, fetch-github.mjs). */+export class FetchError extends Error {+ /**+ * `code`, for the editor's own words: url, host, ref, access, network, git, no-folder, no-film, too-big, timeout,+ * cancelled, failed; 'use-git' only between the two modules (GitHub's API cannot list it, git is tried).+ * @param {string} message @param {number} [status] @param {string} [code]+ */+ constructor(message, status = 400, code = 'failed') {+ super(message);+ this.status = status;+ this.code = code;+ }+}diff --git a/packages/openfilm/studio/server/fetch-github.mjs b/packages/openfilm/studio/server/fetch-github.mjsnew file mode 100644index 0000000..3282f41--- /dev/null+++ b/packages/openfilm/studio/server/fetch-github.mjs@@ -0,0 +1,181 @@+// @ts-check+/**+ * A film from a public GitHub repository, over plain https: no git needed. GitHub's API names the commit and lists+ * the folder's files with their sizes, so the size of the whole is known before the first byte comes; the files then+ * come from GitHub's raw file host at that commit, a few at a time, each written as it streams in.+ *+ * When the API cannot help (a private repository, its hourly limit for this address used up, a listing too long to be+ * whole), it throws a FetchError with code 'use-git', before anything is downloaded: the caller fetches with git.+ */+import { createWriteStream } from 'node:fs';+import { mkdir } from 'node:fs/promises';+import { dirname, join, relative, isAbsolute } from 'node:path';+import { Readable, Transform } from 'node:stream';+import { pipeline } from 'node:stream/promises';+import { FetchError } from './fetch-error.mjs';++export const GITHUB_API = 'https://api.github.com';+export const GITHUB_RAW = 'https://raw.githubusercontent.com';+/* files downloading at once */+const PARALLEL = 4;+/* tries at each file, and the wait before the second (doubled for each after) */+const TRIES = 5;+const RETRY_MS = 500;+/* the starts of a folder's address tried as a branch's name (a branch may have slashes in its name) */+const MAX_REF_PARTS = 6;++/**+ * @typedef {{ api?: string, raw?: string }} GitHubHosts where the API and the raw files are (a test's own server)+ * @typedef {{ path: string, size: number }} RemoteFile `path`: in the folder, with slashes+ * @typedef {{ commit: string, folder: string[], files: RemoteFile[], total: number }} RemoteListing+ */++const encodePath = (/** @type {string[]} */ parts) => parts.map(encodeURIComponent).join('/');++/** Whether GitHub refused because this address used up its hourly calls. @param {Response} res */+const limited = (res) => res.status === 429 || (res.status === 403 && res.headers.get('x-ratelimit-remaining') === '0');++/** Wait `ms`, or less when `signal` stops it. @param {number} ms @param {AbortSignal} [signal] */+const pause = (ms, signal) => new Promise((done) => {+ const timer = setTimeout(done, ms);+ signal?.addEventListener('abort', () => { clearTimeout(timer); done(undefined); }, { once: true });+});++/**+ * Ask GitHub. A connection that fails is tried again, a little later each time; failing every time, it is said as a+ * network failure. @param {string} url+ * @param {{ signal?: AbortSignal, accept?: string }} options @returns {Promise<Response>}+ */+async function request(url, { signal, accept }) {+ for (let tries = 1; ; tries++) {+ try {+ return await fetch(url, { signal, headers: { accept: accept ?? 'application/vnd.github+json', 'user-agent': 'OpenFilm-Studio' } });+ } catch (e) {+ if (signal?.aborted) throw e;+ if (tries >= TRIES) throw new FetchError('Could not reach GitHub: check your internet connection.', 502, 'network');+ await pause(RETRY_MS * 2 ** (tries - 1), signal);+ }+ }+}++/**+ * The commit `tree` points at, and the folder in it: the shortest start of `tree` that GitHub knows as a branch, a+ * tag or a commit (null `tree`: the default branch, the whole repository). A file's address means its folder.+ * @param {{ owner: string, repo: string }} at @param {string[] | null} tree @param {boolean} blob+ * @param {{ signal?: AbortSignal, hosts?: GitHubHosts }} [options]+ * @returns {Promise<{ commit: string, folder: string[] }>}+ */+export async function resolveCommit(at, tree, blob, { signal, hosts = {} } = {}) {+ const base = `${hosts.api ?? GITHUB_API}/repos/${encodeURIComponent(at.owner)}/${encodeURIComponent(at.repo)}/commits/`;+ const tries = tree ? Array.from({ length: Math.min(tree.length, MAX_REF_PARTS) }, (_, i) => i + 1) : [0];+ for (const n of tries) {+ const ref = tree ? tree.slice(0, n) : ['HEAD'];+ const res = await request(base + encodePath(ref), { signal, accept: 'application/vnd.github.sha' });+ if (res.ok) {+ const commit = (await res.text()).trim();+ if (!/^[0-9a-f]{40,64}$/.test(commit)) throw new FetchError('GitHub answered with something that is not a commit.', 502, 'failed');+ const folder = tree ? tree.slice(n) : [];+ return { commit, folder: blob ? folder.slice(0, -1) : folder };+ }+ /* not to be seen (private, or no such repository), or no more calls this hour: git may still get it */+ if (res.status === 404 || res.status === 401 || limited(res)) throw new FetchError('GitHub’s API cannot list it.', 409, 'use-git');+ /* 422: no such branch or tag; try a longer start */+ if (res.status !== 422) throw new FetchError(`GitHub answered ${res.status}.`, 502, 'failed');+ }+ throw new FetchError(`There is no branch or tag “${tree?.[0] ?? 'HEAD'}” in that repository.`, 404, 'ref');+}++/**+ * The files of `folder` at `commit`, with their sizes. Links and submodules are left out.+ * @param {{ owner: string, repo: string }} at @param {string} commit @param {string[]} folder+ * @param {{ signal?: AbortSignal, hosts?: GitHubHosts }} [options]+ * @returns {Promise<RemoteFile[]>}+ */+export async function listFiles(at, commit, folder, { signal, hosts = {} } = {}) {+ const treeish = folder.length ? `${commit}:${folder.join('/')}` : commit;+ const url = `${hosts.api ?? GITHUB_API}/repos/${encodeURIComponent(at.owner)}/${encodeURIComponent(at.repo)}/git/trees/${encodeURIComponent(treeish)}?recursive=1`;+ const res = await request(url, { signal });+ if (res.status === 404) throw new FetchError(`There is no folder “${folder.join('/')}” in that repository.`, 404, 'no-folder');+ if (res.status === 401 || limited(res)) throw new FetchError('GitHub’s API cannot list it.', 409, 'use-git');+ if (!res.ok) throw new FetchError(`GitHub answered ${res.status}.`, 502, 'failed');+ const body = /** @type {{ truncated?: boolean, tree?: { path?: unknown, type?: unknown, mode?: unknown, size?: unknown }[] }} */ (await res.json());+ if (body.truncated || !Array.isArray(body.tree)) throw new FetchError('GitHub’s listing is not whole.', 409, 'use-git');+ /** @type {RemoteFile[]} */+ const files = [];+ for (const entry of body.tree) {+ if (entry.type !== 'blob' || entry.mode === '120000' || typeof entry.path !== 'string') continue;+ const parts = entry.path.split('/');+ if (parts.some((p) => !p || p === '.' || p === '..' || p.includes('\\'))) continue;+ files.push({ path: entry.path, size: typeof entry.size === 'number' && entry.size > 0 ? entry.size : 0 });+ }+ return files;+}++/**+ * Download `files` (of `folder` at `commit`) into `dir`, a few at a time; `onBytes` hears each piece as it comes.+ * @param {{ owner: string, repo: string }} at @param {string} commit @param {string[]} folder @param {RemoteFile[]} files+ * @param {{ dir: string, signal?: AbortSignal, hosts?: GitHubHosts, onBytes?: (n: number) => void }} options+ */+export async function downloadFiles(at, commit, folder, files, { dir, signal, hosts = {}, onBytes = () => {} }) {+ const base = `${hosts.raw ?? GITHUB_RAW}/${encodeURIComponent(at.owner)}/${encodeURIComponent(at.repo)}/${commit}/`;+ /* the biggest first, so the last to finish are small; one that fails stops the others */+ const queue = [...files].sort((a, b) => b.size - a.size);+ const control = new AbortController();+ const stopAll = () => control.abort();+ if (signal?.aborted) stopAll();+ signal?.addEventListener('abort', stopAll, { once: true });+ /** @type {unknown} */+ let failed = null;+ /** One try at a file, counting only the bytes past `counted` (what an earlier try already told). */+ const attempt = async (/** @type {RemoteFile} */ file, /** @type {string} */ to, /** @type {{ counted: number }} */ told) => {+ const res = await request(base + encodePath([...folder, ...file.path.split('/')]), { signal: control.signal, accept: '*/*' });+ if (!res.ok || !res.body) {+ const error = new FetchError(`GitHub did not send “${file.path}” (${res.status}).`, 502, 'failed');+ throw res.status === 429 || res.status >= 500 ? Object.assign(error, { again: true }) : error;+ }+ let got = 0;+ const count = new Transform({+ transform(chunk, _, done) {+ got += chunk.length;+ if (got > told.counted) { onBytes(got - told.counted); told.counted = got; }+ done(null, chunk);+ },+ });+ try {+ await pipeline(Readable.fromWeb(/** @type {import('node:stream/web').ReadableStream} */ (res.body)), count, createWriteStream(to), { signal: control.signal });+ } catch (e) {+ if (control.signal.aborted) throw e;+ throw Object.assign(new FetchError('The download broke off: check your internet connection.', 502, 'network'), { again: true });+ }+ };+ const one = async (/** @type {RemoteFile} */ file) => {+ const to = join(dir, ...file.path.split('/'));+ const inside = relative(dir, to);+ if (!inside || inside.startsWith('..') || isAbsolute(inside)) throw new FetchError(`“${file.path}” is not a path in the folder.`, 422, 'failed');+ await mkdir(dirname(to), { recursive: true });+ /* a connection that drops is tried again, a little later each time, from the start of the file */+ const told = { counted: 0 };+ for (let tries = 1; ; tries++) {+ try {+ await attempt(file, to, told);+ return;+ } catch (e) {+ if (control.signal.aborted || !(/** @type {any} */ (e)?.again) || tries >= TRIES) throw e;+ await pause(RETRY_MS * 2 ** (tries - 1), control.signal);+ }+ }+ };+ const worker = async () => {+ for (let file = queue.shift(); file && !control.signal.aborted; file = queue.shift()) {+ try {+ await one(file);+ } catch (e) {+ failed ??= e;+ stopAll();+ }+ }+ };+ await Promise.all(Array.from({ length: Math.min(PARALLEL, queue.length) }, worker));+ signal?.removeEventListener('abort', stopAll);+ if (failed) throw failed;+}diff --git a/packages/openfilm/studio/server/fetch-repo.mjs b/packages/openfilm/studio/server/fetch-repo.mjsindex 227accc..36767c8 100644--- a/packages/openfilm/studio/server/fetch-repo.mjs+++ b/packages/openfilm/studio/server/fetch-repo.mjs@@ -1,12 +1,13 @@// @ts-check/*** A film from GitHub (or GitLab): a repository, or a folder in one, copied into the projects library as the person's- * own project. git fetches it shallow (`--depth 1`); for a folder, a partial clone with a sparse checkout, so only- * that folder's files download. The fetched `.git` is left behind: the copy has no tie to where it came from.+ * own project. A public GitHub repository comes over https (fetch-github.mjs), its size known before it starts;+ * otherwise git fetches it shallow (`--depth 1`); for a folder, a partial clone with a sparse checkout, so only that+ * folder's files download. No `.git` is kept: the copy has no tie to where it came from.** Only https addresses of github.com and gitlab.com are taken, and git always runs through execFile with its- * arguments as a list (never a shell), with the ref and the folder checked first. A fetch stops when it takes too- * long or grows too big, and says so.+ * arguments as a list (never a shell), with the ref and the folder checked first. A fetch stops when nothing comes+ * for a while or it grows too big, and says so.*/import { spawn } from 'node:child_process';import { randomBytes } from 'node:crypto';@@ -14,24 +15,15 @@ import { existsSync } from 'node:fs';import { lstat, mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { FILM_FILE } from '../../src/film-doc.mjs';+import { FetchError } from './fetch-error.mjs';+import { downloadFiles, listFiles, resolveCommit } from './fetch-github.mjs';-export class FetchError extends Error {- /**- * `code`, for the editor's own words: url, host, ref, access, network, git, no-folder, no-film, too-big, timeout,- * cancelled, failed.- * @param {string} message @param {number} [status] @param {string} [code]- */- constructor(message, status = 400, code = 'failed') {- super(message);- this.status = status;- this.code = code;- }-}+export { FetchError };/** Biggest fetch, unless OPENFILM_FETCH_MAX_MB says otherwise. */export const MAX_BYTES = (Number(process.env.OPENFILM_FETCH_MAX_MB) || 500) * 1024 * 1024;-/** Longest fetch. */-export const TIMEOUT_MS = 10 * 60 * 1000;+/** Longest wait for anything to come: a fetch that gets nothing for this long is stopped. */+export const TIMEOUT_MS = 2 * 60 * 1000;const HOSTS = /** @type {Record<string, 'github' | 'gitlab'>} */ ({ 'github.com': 'github', 'www.github.com': 'github', 'gitlab.com': 'gitlab' });/* a name in an owner/repo path; a folder's name, less what a sparse-checkout pattern would read as a wildcard */@@ -39,9 +31,11 @@ const NAME = /^[\w.-]+$/;const SEGMENT = /^[^\u0000-\u001f\u007f*?[\]\\]+$/;/**- * @typedef {{ host: 'github' | 'gitlab', web: string, cloneUrl: string, name: string, tree: string[] | null, blob: boolean }} RepoSource+ * @typedef {{ host: 'github' | 'gitlab', web: string, cloneUrl: string, name: string, tree: string[] | null, blob: boolean,+ * github?: { owner: string, repo: string } | null }} RepoSource* `tree`: what follows `/tree/` (or `/blob/`) in the address: a branch or tag, then a folder (which part is which is- * known only from the repository's refs, see resolveRef); null: the whole repository, its default branch.+ * known only from the repository's refs, see resolveRef); null: the whole repository, its default branch. `github`:+ * its owner and name on GitHub, fetched over https (fetch-github.mjs); none: through git.*//**@@ -80,7 +74,8 @@ export function parseRepoUrl(input) {}const origin = host === 'github' ? 'https://github.com' : 'https://gitlab.com';const path = repoParts.join('/');- return { host, web: `${origin}/${path}`, cloneUrl: `${origin}/${path}.git`, name: repoParts[repoParts.length - 1], tree, blob };+ const github = host === 'github' ? { owner: repoParts[0], repo: repoParts[1] } : null;+ return { host, web: `${origin}/${path}`, cloneUrl: `${origin}/${path}.git`, name: repoParts[repoParts.length - 1], tree, blob, github };}/**@@ -105,11 +100,12 @@ export function splitTree(tree, refs, blob) {/*** Run git, never through a shell, without asking anything in a terminal; `onLine` hears its progress (git writes it- * on stderr, each step ending in \r). Resolves to stdout; a failure rejects with what git said.- * @param {string[]} args @param {{ cwd?: string, signal?: AbortSignal, onLine?: (line: string) => void }} [options]+ * on stderr, each step ending in \r); `input` is written to its stdin. Resolves to stdout; a failure rejects with what+ * git said.+ * @param {string[]} args @param {{ cwd?: string, signal?: AbortSignal, onLine?: (line: string) => void, input?: string }} [options]* @returns {Promise<string>}*/-function git(args, { cwd, signal, onLine } = {}) {+function git(args, { cwd, signal, onLine, input } = {}) {return new Promise((done, fail) => {/* stopped before it began: git never runs */if (signal?.aborted) { fail(new Error('stopped')); return; }@@ -117,8 +113,9 @@ function git(args, { cwd, signal, onLine } = {}) {cwd,windowsHide: true,env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_PROGRESS_DELAY: '0' },- stdio: ['ignore', 'pipe', 'pipe'],+ stdio: ['pipe', 'pipe', 'pipe'],});+ child.stdin.on('error', () => {}).end(input ?? '');let out = '';let err = '';let partial = '';@@ -189,13 +186,15 @@ async function folderSize(dir) {/*** How a fetch is going: `phase` ('lookup': asking the host about the repository, 'download', 'checkout': writing the- * files, 'copy': putting them in the library), git's percent for the phase when it says one, and the bytes on disk so far.- * @typedef {{ phase: 'lookup' | 'download' | 'checkout' | 'copy', percent: number | null, bytes: number }} FetchProgress+ * files, 'copy': putting them in the library); `bytes` downloaded so far, of `total` when that is known (GitHub's API+ * says it; git does not), and the `percent` done: of the bytes, or git's own when only it knows.+ * @typedef {{ phase: 'lookup' | 'download' | 'checkout' | 'copy', percent: number | null, bytes: number, total: number | null }} FetchProgress*//*** Clone `cloneUrl` at `ref` (null: its default branch) into `dir`, shallow; with `folder`, a partial clone whose- * checkout holds only that folder. Leaves `.git` in `dir` (the caller drops it).+ * checkout holds only that folder. Leaves `.git` in `dir` (the caller drops it). `onLine` hears git's progress for the+ * download of the files only: a folder's list of files comes first, unheard.* @param {{ cloneUrl: string, ref: string | null, folder: string[], dir: string, signal?: AbortSignal, onLine?: (line: string) => void }} options*/export async function cloneInto({ cloneUrl, ref, folder, dir, signal, onLine }) {@@ -205,9 +204,15 @@ export async function cloneInto({ cloneUrl, ref, folder, dir, signal, onLine })await git(['clone', '--depth=1', '--single-branch', '--no-tags', '--progress', ...branch, '--', cloneUrl, dir], { signal, onLine });return;}- await git(['clone', '--depth=1', '--single-branch', '--no-tags', '--progress', '--filter=blob:none', '--no-checkout', ...branch, '--', cloneUrl, dir], { signal, onLine });+ await git(['clone', '--depth=1', '--single-branch', '--no-tags', '--filter=blob:none', '--no-checkout', ...branch, '--', cloneUrl, dir], { signal });+ /* the folder's files, asked for by name: read-tree would fetch them too, but says nothing about how far it got */+ const listed = await git(['ls-tree', '-r', '-z', 'HEAD', '--', folder.join('/')], { cwd: dir, signal });+ const blobs = listed.split('\0').map((entry) => /^\d+ blob ([0-9a-f]+)\t/.exec(entry)?.[1]).filter(Boolean);+ if (blobs.length) {+ await git(['-c', 'fetch.negotiationAlgorithm=noop', 'fetch', '--progress', '--no-tags', '--no-write-fetch-head', '--recurse-submodules=no', '--stdin', 'origin'], { cwd: dir, signal, onLine, input: `${blobs.join('\n')}\n` });+ }/* only the folder: a sparse checkout whose one pattern is the folder (anchored, so a same-named folder deeper down is- not taken too); read-tree then fetches just its files */+ not taken too); read-tree then writes just its files */await git(['config', 'core.sparseCheckout', 'true'], { cwd: dir, signal });await mkdir(join(dir, '.git', 'info'), { recursive: true });await writeFile(join(dir, '.git', 'info', 'sparse-checkout'), `/${folder.join('/')}/\n`);@@ -217,13 +222,15 @@ export async function cloneInto({ cloneUrl, ref, folder, dir, signal, onLine })/*** Fetch a film into `library`: the repository or folder `source` points at, as a folder of its own named after it* ("one-prompt", "one-prompt 2", …), without `.git`. Resolves to that folder. A folder that is missing, or has no- * film.html, leaves nothing behind.+ * film.html, leaves nothing behind. GitHub's public repositories come over https (fetch-github.mjs); the others, and+ * any GitHub's API cannot list, through git.* @param {RepoSource} source- * @param {{ library: string, onProgress?: (p: FetchProgress) => void, signal?: AbortSignal, maxBytes?: number, timeoutMs?: number }} options+ * @param {{ library: string, onProgress?: (p: FetchProgress) => void, signal?: AbortSignal, maxBytes?: number, timeoutMs?: number,+ * hosts?: import('./fetch-github.mjs').GitHubHosts }} options*/-export async function fetchFilm(source, { library, onProgress = () => {}, signal, maxBytes = MAX_BYTES, timeoutMs = TIMEOUT_MS }) {+export async function fetchFilm(source, { library, onProgress = () => {}, signal, maxBytes = MAX_BYTES, timeoutMs = TIMEOUT_MS, hosts }) {const where = source.host === 'github' ? 'GitHub' : 'GitLab';- /* why it stopped, when it was stopped here (too long, too big) or by the caller */+ /* why it stopped, when it was stopped here (nothing coming, too big) or by the caller *//** @type {FetchError | null} */let stopped = null;const control = new AbortController();@@ -231,67 +238,110 @@ export async function fetchFilm(source, { library, onProgress = () => {}, signalconst onAbort = () => stop(new FetchError('Cancelled.', 499, 'cancelled'));if (signal?.aborted) onAbort();signal?.addEventListener('abort', onAbort, { once: true });- const timer = setTimeout(() => stop(new FetchError(`It took longer than ${Math.round(timeoutMs / 60000) || 1} minutes, so it was stopped.`, 504, 'timeout')), timeoutMs);+ /* stopped when nothing has come for a while: a big film on a slow line still gets there */+ /** @type {ReturnType<typeof setTimeout> | undefined} */+ let timer;+ const minutes = Math.max(1, Math.round(timeoutMs / 60000));+ const waited = () => {+ clearTimeout(timer);+ timer = setTimeout(() => stop(new FetchError(`Nothing came for ${minutes} minute${minutes === 1 ? '' : 's'}, so it was stopped.`, 504, 'timeout')), timeoutMs);+ };+ waited();const tooBig = () => new FetchError(`It is bigger than ${Math.max(1, Math.round(maxBytes / 1024 / 1024))} MB, so it was stopped.`, 413, 'too-big');/** @type {FetchProgress} */- const progress = { phase: 'lookup', percent: null, bytes: 0 };+ const progress = { phase: 'lookup', percent: null, bytes: 0, total: null };const tell = () => onProgress({ ...progress });+ const grew = (/** @type {number} */ bytes) => {+ if (bytes <= progress.bytes) return;+ progress.bytes = bytes;+ if (progress.total) progress.percent = Math.min(100, Math.floor((bytes / progress.total) * 100));+ waited();+ tell();+ if (bytes > maxBytes) stop(tooBig());+ };await mkdir(library, { recursive: true });const work = join(library, `.fetching-${randomBytes(6).toString('hex')}`);- /* the size on disk, read every half second: too big stops it */- const measure = setInterval(() => {- void folderSize(work).then((bytes) => {- if (bytes <= progress.bytes) return;- progress.bytes = bytes;- tell();- if (bytes > maxBytes) stop(tooBig());- });- }, 500);- const onLine = (/** @type {string} */ line) => {- const m = /^(?:remote: )?(Counting objects|Compressing objects|Receiving objects|Resolving deltas|Updating files|Checking out files)[^:]*:\s+(\d+)%/.exec(line);- if (!m) return;- const phase = /Updating files|Checking out files/.test(m[1]) ? 'checkout' : 'download';- const percent = Number(m[2]);- if (phase === progress.phase && percent === progress.percent) return;- progress.phase = phase;- progress.percent = percent;++ /** Over https: the list of files and their sizes first, so nothing is downloaded for a folder that is not a film. */+ const overHttp = async (/** @type {{ owner: string, repo: string }} */ at) => {+ const { commit, folder } = await resolveCommit(at, source.tree, source.blob, { signal: control.signal, hosts });+ const files = await listFiles(at, commit, folder, { signal: control.signal, hosts });+ if (!files.some((file) => file.path === FILM_FILE)) {+ throw new FetchError(`There is no film.html in ${folder.length ? `“${folder.join('/')}”` : 'that repository'}: it is not an OpenFilm film.`, 422, 'no-film');+ }+ const total = files.reduce((sum, file) => sum + file.size, 0);+ if (total > maxBytes) throw tooBig();+ Object.assign(progress, { phase: 'download', total, percent: 0 });tell();+ const dir = join(work, 'files');+ await mkdir(dir, { recursive: true });+ let got = 0;+ await downloadFiles(at, commit, folder, files, { dir, signal: control.signal, hosts, onBytes: (n) => grew((got += n)) });+ return { from: dir, folder };};- try {- tell();+ /** Through git: how much has come is the size of what git keeps, read every half second. */+ const overGit = async () => {let ref = null;/** @type {string[]} */let folder = [];if (source.tree) ({ ref, folder } = splitTree(source.tree, await remoteRefs(source.cloneUrl, control.signal), source.blob));- progress.phase = 'download';- progress.percent = null;+ Object.assign(progress, { phase: 'download', total: null, percent: null });tell();- await cloneInto({ cloneUrl: source.cloneUrl, ref, folder, dir: work, signal: control.signal, onLine });+ const clone = join(work, 'clone');+ const kept = join(clone, '.git');+ const measure = setInterval(() => { void folderSize(kept).then(grew); }, 500);+ const onLine = (/** @type {string} */ line) => {+ /* only these two say how far the download and the writing are: the server's counting and compressing, and the+ resolving after, each run 0 to 100 too */+ const m = /^(Receiving objects|Updating files|Checking out files)[^:]*:\s+(\d+)%/.exec(line);+ if (!m) return;+ const phase = m[1] === 'Receiving objects' ? 'download' : 'checkout';+ const percent = Number(m[2]);+ if (phase === progress.phase && percent === progress.percent) return;+ progress.phase = phase;+ progress.percent = percent;+ waited();+ tell();+ };+ try {+ await cloneInto({ cloneUrl: source.cloneUrl, ref, folder, dir: clone, signal: control.signal, onLine });+ } finally {+ clearInterval(measure);+ }if (stopped) throw stopped;/* done between two looks at its size: looked at once more */- progress.bytes = Math.max(progress.bytes, await folderSize(work));+ grew(await folderSize(kept));if (progress.bytes > maxBytes) throw tooBig();- const from = join(work, ...folder);+ const from = join(clone, ...folder);const kind = await stat(from).catch(() => null);if (!kind?.isDirectory()) throw new FetchError(`There is no folder “${folder.join('/')}” in that repository.`, 404, 'no-folder');if (!existsSync(join(from, FILM_FILE))) {throw new FetchError(`There is no film.html in ${folder.length ? `“${folder.join('/')}”` : 'that repository'}: it is not an OpenFilm film.`, 422, 'no-film');}- progress.phase = 'copy';- progress.percent = null;- tell();/* the copy is the person's own: no history of where it came from, no remote */await rm(join(from, '.git'), { recursive: true, force: true });- const to = freeName(library, folder.length ? folder[folder.length - 1] : source.name);- await rename(from, to);+ return { from, folder };+ };++ try {+ tell();+ const github = source.github;+ const got = (github ? await overHttp(github).catch((e) => {+ if (e instanceof FetchError && e.code === 'use-git' && !stopped) return null;+ throw e;+ }) : null) ?? await overGit();+ if (stopped) throw stopped;+ Object.assign(progress, { phase: 'copy' });+ tell();+ const to = freeName(library, got.folder.length ? got.folder[got.folder.length - 1] : source.name);+ await rename(got.from, to);return to;} catch (e) {throw stopped ?? explain(e, where);} finally {clearTimeout(timer);- clearInterval(measure);signal?.removeEventListener('abort', onAbort);await rm(work, { recursive: true, force: true, maxRetries: 3 }).catch(() => {});}@@ -313,7 +363,7 @@ function freeName(/** @type {string} */ root, /** @type {string} */ name) {export function createFetches({ library, open, maxBytes, timeoutMs }) {/*** @typedef {{ id: string, url: string, label: string, state: 'running' | 'done' | 'failed', phase: FetchProgress['phase'],- * percent: number | null, bytes: number, error?: string, code?: string, project?: { id: string } }} FetchJob+ * percent: number | null, bytes: number, total: number | null, error?: string, code?: string, project?: { id: string } }} FetchJob*//** @type {Map<string, { job: FetchJob, control: AbortController }>} */const jobs = new Map();@@ -326,7 +376,7 @@ export function createFetches({ library, open, maxBytes, timeoutMs }) {const control = new AbortController();const label = [source.web.replace(/^https:\/\/[^/]+\//, ''), ...(source.tree ?? []).slice(1)].join(' / ');/** @type {FetchJob} */- const job = { id, url: String(url).trim(), label, state: 'running', phase: 'lookup', percent: null, bytes: 0 };+ const job = { id, url: String(url).trim(), label, state: 'running', phase: 'lookup', percent: null, bytes: 0, total: null };jobs.set(id, { job, control });void fetchFilm(source, {library: library(), signal: control.signal, ...(maxBytes ? { maxBytes } : {}), ...(timeoutMs ? { timeoutMs } : {}),diff --git a/packages/openfilm/studio/server/fetch-repo.test.mjs b/packages/openfilm/studio/server/fetch-repo.test.mjsindex d8557c1..3574434 100644--- a/packages/openfilm/studio/server/fetch-repo.test.mjs+++ b/packages/openfilm/studio/server/fetch-repo.test.mjs@@ -1,8 +1,9 @@-import { test, before } from 'node:test';+import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { execFileSync } from 'node:child_process';import { randomBytes } from 'node:crypto';-import { existsSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs';+import { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';+import { createServer } from 'node:http';import { tmpdir } from 'node:os';import { join } from 'node:path';import { pathToFileURL } from 'node:url';@@ -16,6 +17,7 @@ test('a repository address, with or without .git, a slash or the scheme', () =>assert.equal(source.cloneUrl, 'https://github.com/openfilm/examples.git', input);assert.equal(source.name, 'examples');assert.equal(source.tree, null);+ assert.deepEqual(source.github, { owner: 'openfilm', repo: 'examples' }, 'GitHub: over https');}});@@ -29,6 +31,7 @@ test('a folder\'s address: what follows /tree/ is the ref and the folder, told aassert.deepEqual(parseRepoUrl('https://github.com/o/r/tree/main/a%20b').tree, ['main', 'a b']);const lab = parseRepoUrl('https://gitlab.com/group/sub/film/-/tree/main/one');assert.equal(lab.cloneUrl, 'https://gitlab.com/group/sub/film.git');+ assert.equal(lab.github, null, 'GitLab: through git');assert.deepEqual(lab.tree, ['main', 'one']);});@@ -109,12 +112,16 @@ test('a folder is a partial clone: only its files download, and only it is checktest('a fetched folder lands in the library under its own name, without .git; a second copy gets a new name', async () => {const lib = library();const progress = [];- const first = await fetchFilm(source(['main', 'films', 'one']), { library: lib, onProgress: (p) => progress.push(p.phase) });+ const first = await fetchFilm(source(['main', 'films', 'one']), { library: lib, onProgress: (p) => progress.push(p) });assert.equal(first, join(lib, 'one'));assert.ok(existsSync(join(first, 'film.html')));assert.ok(existsSync(join(first, 'assets', 'a.txt')));assert.ok(!existsSync(join(first, '.git')));- assert.deepEqual([...new Set(progress)].filter((p) => p !== 'checkout'), ['lookup', 'download', 'copy']);+ assert.deepEqual([...new Set(progress.map((p) => p.phase))].filter((p) => p !== 'checkout'), ['lookup', 'download', 'copy']);+ /* the bar follows the download of the folder's files: up to 100 once, never back to the start */+ const percents = progress.filter((p) => p.phase === 'download' && p.percent != null).map((p) => p.percent);+ assert.ok(percents.length && percents.at(-1) === 100, `the download says how far it got: ${percents}`);+ assert.deepEqual(percents, [...percents].sort((a, b) => a - b), `it only goes up: ${percents}`);const second = await fetchFilm(source(['feature', 'x', 'films', 'one']), { library: lib });assert.equal(second, join(lib, 'one 2'), 'a branch with a slash in its name');assert.deepEqual(readdirSync(lib).sort(), ['one', 'one 2'], 'nothing else left behind');@@ -151,10 +158,132 @@ test('the job list: a wrong address is refused at once; a job says how it went',const fetches = createFetches({ library: () => join(scratch, 'jobs'), open: async () => ({ id: 'p' }) });assert.throws(() => fetches.start('https://example.com/o/r'), (e) => e.code === 'host');assert.throws(() => fetches.get('nope'), (e) => e.status === 404);- /* stopped at once, before git runs (no network): it reports how it ended */+ /* stopped at once, before anything is asked (no network): it reports how it ended */const job = fetches.start('https://github.com/openfilm/examples/tree/main/x');assert.equal(job.state, 'running');fetches.cancel(job.id);for (let i = 0; i < 100 && fetches.get(job.id).state === 'running'; i++) await new Promise((r) => setTimeout(r, 20));assert.deepEqual([fetches.get(job.id).state, fetches.get(job.id).code], ['failed', 'cancelled']);});++/* ── over https, against a GitHub of our own: its API and its raw files, read from the work tree ── */++const COMMIT = 'c'.repeat(40);+let github;+/* what the fake GitHub was asked; a file named here drops its connection half way the first time it is asked */+const asked = [];+const dropOnce = new Set();+const filesUnder = (dir, prefix = '') => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ if (entry.name === '.git') return [];+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;+ return entry.isDirectory() ? filesUnder(join(dir, entry.name), path) : [{ path, type: 'blob', mode: '100644', size: statSync(join(dir, entry.name)).size }];+});+before(async () => {+ const work = join(scratch, 'work');+ const server = createServer((req, res) => {+ const url = new URL(req.url, 'http://x');+ asked.push(url.pathname);+ const parts = url.pathname.split('/').filter(Boolean).map(decodeURIComponent);+ if (parts[0] === 'raw') {+ /* raw/owner/repo/commit/…path */+ const path = parts.slice(4).join('/');+ if (parts[3] !== COMMIT || !existsSync(join(work, path))) { res.writeHead(404).end(); return; }+ const body = readFileSync(join(work, path));+ res.writeHead(200, { 'content-length': body.length });+ if (dropOnce.delete(path)) { res.write(body.subarray(0, body.length >> 1)); setTimeout(() => res.destroy(), 20); return; }+ res.end(body);+ return;+ }+ /* repos/owner/repo/… */+ if (parts[1] === 'private') { res.writeHead(404).end('{}'); return; }+ if (parts[3] === 'commits') {+ const ref = parts.slice(4).join('/');+ if (['HEAD', 'main', 'feature/x'].includes(ref)) res.writeHead(200).end(COMMIT);+ else res.writeHead(422).end('{}');+ return;+ }+ if (parts[3] === 'git' && parts[4] === 'trees') {+ const [commit, folder = ''] = parts.slice(5).join('/').split(':');+ const dir = join(work, folder);+ if (commit !== COMMIT || !existsSync(dir)) { res.writeHead(404).end('{}'); return; }+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ truncated: false, tree: filesUnder(dir) }));+ return;+ }+ res.writeHead(404).end('{}');+ });+ await new Promise((done) => server.listen(0, '127.0.0.1', done));+ const at = `http://127.0.0.1:${server.address().port}`;+ github = { server, hosts: { api: at, raw: `${at}/raw` } };+});+after(() => github?.server.close());++const overHttp = (tree, blob = false, owner = 'o') => ({ ...source(tree, blob), github: { owner, repo: 'r' } });++test('over https: the size is known before the first byte, and the bar only goes up, to 100', async () => {+ const lib = library();+ const seen = [];+ const to = await fetchFilm(overHttp(['main', 'films', 'one']), { library: lib, hosts: github.hosts, onProgress: (p) => seen.push(p) });+ assert.equal(to, join(lib, 'one'));+ assert.equal(readFileSync(join(to, 'film.html'), 'utf8'), '<!doctype html><title>one</title>');+ assert.equal(readFileSync(join(to, 'assets', 'a.txt'), 'utf8'), 'a');+ assert.deepEqual(readdirSync(lib), ['one'], 'nothing else left behind');+ assert.deepEqual([...new Set(seen.map((p) => p.phase))], ['lookup', 'download', 'copy']);+ const downloads = seen.filter((p) => p.phase === 'download');+ const total = statSync(join(to, 'film.html')).size + 1;+ assert.ok(downloads.every((p) => p.total === total), 'the total from the start');+ const percents = downloads.map((p) => p.percent);+ assert.deepEqual(percents, [...percents].sort((a, b) => a - b));+ assert.equal(percents.at(-1), 100);+ assert.equal(seen.at(-1).bytes, total);+});++test('over https: a branch with a slash in its name; the whole repository; a file\'s address means its folder', async () => {+ const lib = library();+ assert.equal(await fetchFilm(overHttp(['feature', 'x', 'films', 'one']), { library: lib, hosts: github.hosts }), join(lib, 'one'));+ const whole = await fetchFilm(overHttp(null), { library: lib, hosts: github.hosts });+ assert.equal(whole, join(lib, 'origin'));+ assert.ok(existsSync(join(whole, 'films', 'two', 'film.html')));+ assert.ok(!existsSync(join(whole, '.git')));+ assert.equal(await fetchFilm(overHttp(['main', 'films', 'two', 'film.html'], true), { library: lib, hosts: github.hosts }), join(lib, 'two'));+});++test('over https: no film, no folder, no branch, too big: said before anything downloads', async () => {+ const lib = library();+ const fails = async (src, code, options = {}) => {+ asked.length = 0;+ await assert.rejects(fetchFilm(src, { library: lib, hosts: github.hosts, ...options }), (e) => e instanceof FetchError && e.code === code);+ assert.deepEqual(readdirSync(lib), [], `${code}: nothing left`);+ assert.ok(!asked.some((path) => path.startsWith('/raw/')), `${code}: no file was downloaded`);+ };+ await fails(overHttp(['main', 'docs']), 'no-film');+ await fails(overHttp(['main', 'films', 'three']), 'no-folder');+ await fails(overHttp(['nope', 'films']), 'ref');+ await fails(overHttp(null), 'too-big', { maxBytes: 64 * 1024 });+});++test('over https: a connection that drops is tried again, and its bytes are not counted twice', async () => {+ const lib = library();+ dropOnce.add('big.bin');+ let last = null;+ const to = await fetchFilm(overHttp(null), { library: lib, hosts: github.hosts, onProgress: (p) => { last = p; } });+ assert.equal(dropOnce.size, 0, 'it did drop');+ assert.ok(readFileSync(join(to, 'big.bin')).equals(readFileSync(join(scratch, 'work', 'big.bin'))));+ assert.equal(last.bytes, last.total);+});++test('a repository GitHub\'s API cannot see (private) is fetched with git instead', async () => {+ const lib = library();+ const to = await fetchFilm(overHttp(['main', 'films', 'one'], false, 'private'), { library: lib, hosts: github.hosts });+ assert.equal(to, join(lib, 'one'));+ assert.ok(existsSync(join(to, 'film.html')));+});++test('over https: cancelled while downloading, it stops and leaves nothing', async () => {+ const lib = library();+ const control = new AbortController();+ await assert.rejects(+ fetchFilm(overHttp(null), { library: lib, hosts: github.hosts, signal: control.signal, onProgress: (p) => { if (p.phase === 'download') control.abort(); } }),+ (e) => e.code === 'cancelled',+ );+ assert.deepEqual(readdirSync(lib), []);+});diff --git a/packages/openfilm/studio/server/files.mjs b/packages/openfilm/studio/server/files.mjsindex 6836951..b9d9c8e 100644--- a/packages/openfilm/studio/server/files.mjs+++ b/packages/openfilm/studio/server/files.mjs@@ -1,19 +1,22 @@// @ts-check/**- * A project's media and pages, as the media pane shows them and changes them. Everything is a real file in the folder:- * imports are streamed to disk whatever their size, and nothing is replaced by a pointer.+ * A project's media and pages, as the media pane shows them and changes them. Imports are streamed to disk whatever+ * their size; files picked on this computer are copied (cloned, where the disk can: no time, no room) or linked, a+ * link in assets/ to where they are kept (a NAS, another disk: src/media-links.mjs).** Paths in and out are relative to the project folder, with forward slashes. Nothing outside the folder, and nothing- * in Studio's own `.film/`, can be read or written through here, by its name or through a link in the folder.+ * in Studio's own `.film/`, can be written through here, by its name or through a link in the folder; outside it, only+ * what the person linked can be read.*/import { execFile } from 'node:child_process';import { createHash } from 'node:crypto';-import { createReadStream, createWriteStream, existsSync, lstatSync, realpathSync, statSync } from 'node:fs';-import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';+import { constants, createReadStream, createWriteStream, existsSync, lstatSync, realpathSync, statSync } from 'node:fs';+import { copyFile, cp, lstat, mkdir, readFile, readdir, readlink, rename, rm, stat, symlink, unlink, 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';import { FILM_FILE, clipKind } from '../../src/film-doc.mjs';+import { addLinkedPlaces, readableLink } from '../../src/media-links.mjs';import { readProjectFilm, writeProjectFilm } from './film.mjs';import { TOOL_DIR } from './projects.mjs';import { moveToTrash } from './trash.mjs';@@ -35,10 +38,11 @@ export class FileError extends Error {/*** The absolute path of a project-relative one, refused when it leaves the folder or reaches into `.film/`: as written,- * and as it is on disk (a folder in a downloaded project can be a link to anywhere).- * @param {string} root @param {string} rel+ * and as it is on disk (a folder in a downloaded project can be a link to anywhere). `read`: a link in assets/ to a+ * place the person linked is followed too (it is read, never written).+ * @param {string} root @param {string} rel @param {{ read?: boolean }} [how]*/-export function inside(root, rel) {+export function inside(root, rel, how = {}) {if (typeof rel !== 'string' || !rel || rel.includes('\0')) throw new FileError('which file?');const clean = normalize(rel.split('/').join(sep));const abs = join(root, clean);@@ -46,15 +50,33 @@ export function inside(root, rel) {const parts = back.split(sep);/* on Windows a `:` in a name is a stream of it (`.film::$INDEX_ALLOCATION` is the folder itself) */const streams = process.platform === 'win32' && parts.some((p) => p.includes(':'));- if (!back || parts[0] === '..' || isToolDir(parts[0]) || streams || /^[a-zA-Z]:/.test(clean) || clean.startsWith(sep) || !onDiskInside(root, abs)) {+ if (!back || parts[0] === '..' || isToolDir(parts[0]) || streams || /^[a-zA-Z]:/.test(clean) || clean.startsWith(sep)+ || !(onDiskInside(root, abs) || (how.read === true && readableLink(root, abs)))) {throw new FileError(`${rel} is not a path inside the project`);}return abs;}-/** {@link inside}, or null where it would refuse: for paths a film names (a clip's src), not a person. */+/** {@link inside} to read: a linked file is followed to where it is kept. */+export const readable = (/** @type {string} */ root, /** @type {string} */ rel) => inside(root, rel, { read: true });++/** {@link readable}, or null where it would refuse: for paths a film names (a clip's src), not a person. */export function inProject(/** @type {string} */ root, /** @type {string} */ rel) {- try { return inside(root, rel); } catch { return null; }+ try { return readable(root, rel); } catch { return null; }+}++/**+ * {@link inside} for an entry itself, to move or remove it: a link in assets/ is the link, wherever it leads, or if+ * it leads nowhere (a NAS that is off); its folder must be in the project.+ * @param {string} root @param {string} rel+ */+function entryInside(root, rel) {+ const cut = typeof rel === 'string' ? rel.lastIndexOf('/') : -1;+ if (cut > 0 && rel.startsWith(`${ASSETS}/`)) {+ const abs = join(inside(root, rel.slice(0, cut)), rel.slice(cut + 1));+ if (lstatSync(abs, { throwIfNoEntry: false })?.isSymbolicLink() && !rel.slice(cut + 1).startsWith('.')) return abs;+ }+ return inside(root, rel);}/**@@ -150,6 +172,8 @@ export async function listFiles(root) {const folders = [];/** @type {{ path: string, size: number, mtime: number }[]} */const pages = [];+ /** @type {Record<string, { to: string, missing?: true }>} */+ const links = {};async function walk(/** @type {string} */ dir, /** @type {number} */ depth, /** @type {boolean} */ media) {let entries;@@ -159,6 +183,17 @@ export async function listFiles(root) {if (entry.name.startsWith('.')) continue;const abs = join(dir, entry.name);const rel = posix(relative(root, abs));+ /* a link the person made to media kept elsewhere: followed to a place they linked; one that leads nowhere (a+ NAS that is off), or out of the project to a place they never linked (a project from elsewhere), is missing */+ if (media && entry.isSymbolicLink()) {+ const to = await readlink(abs).catch(() => '');+ const info = readableLink(root, abs) ? await stat(abs).catch(() => null) : null;+ links[rel] = { to: isAbsolute(to) ? to : join(dir, to), ...(info ? {} : { missing: true }) };+ if (info?.isDirectory()) { folders.push(rel); if (depth < 8) await walk(abs, depth + 1, true); continue; }+ const at = info ?? await lstat(abs).catch(() => null);+ if (at) files.push({ path: rel, kind: kindOf(entry.name), size: info ? info.size : 0, mtime: Math.round(at.mtimeMs) });+ continue;+ }if (entry.isDirectory()) {if (media) { folders.push(rel); if (depth < 8) await walk(abs, depth + 1, true); }else if (!SKIP.has(entry.name) && depth < 3) await walk(abs, depth + 1, false);@@ -175,7 +210,7 @@ export async function listFiles(root) {await walk(join(root, ASSETS), 0, true);await walk(root, 0, false);const sort = (/** @type {{ path: string }} */ a, /** @type {{ path: string }} */ b) => a.path.localeCompare(b.path, undefined, { numeric: true });- return { files: files.sort(sort), folders: folders.sort(), made: made.sort(), pages: pages.sort(sort) };+ return { files: files.sort(sort), folders: folders.sort(), made: made.sort(), pages: pages.sort(sort), links };}/** The file that marks a folder a person made: it keeps an empty folder in the listing and in history. */@@ -316,15 +351,16 @@ async function relinkAfterMove(root, from, to) {* @param {string} root @param {string} from @param {string} asked*/export async function moveFile(root, from, asked) {- const src = inside(root, from);+ const src = entryInside(root, from);askedInside(root, asked);const to = cleanLast(asked);const dst = inside(root, to);- if (!existsSync(src)) throw new FileError(`${from} is not there`, 404);+ const link = lstatSync(src, { throwIfNoEntry: false })?.isSymbolicLink() === true;+ if (!link && !existsSync(src)) throw new FileError(`${from} is not there`, 404);/* a file's ending says what it is: a picture renamed .mp3 would be taken for a sound (and fail as one). Anotherending of the same kind (.jpeg → .jpg) is fine */const fromName = posix(from).split('/').pop() ?? '', toName = to.split('/').pop() ?? '';- if ((await stat(src)).isFile() && kindOf(fromName) !== kindOf(toName)) {+ if ((link || (await stat(src)).isFile()) && kindOf(fromName) !== kindOf(toName)) {throw new FileError(`${fromName} can't be renamed ${toName}: the ending says what a file is (a picture, a video, a sound or a page), and this one would change it. Keep an ending of the same kind`);}if (existsSync(dst) && !sameEntry(src, dst)) throw new FileError(`${to} is already there`, 409);@@ -402,9 +438,112 @@ export async function freezeFrame(root, rel, ms) {return posix(relative(root, out));}-/** Move a file or folder to the system's trash (see trash.mjs). */+/**+ * Move a file or folder to the system's trash (see trash.mjs). A link is only taken away: what it leads to stays where+ * it is kept, untouched.+ */export async function trashFile(/** @type {string} */ root, /** @type {string} */ rel) {- const abs = inside(root, rel);+ const abs = entryInside(root, rel);+ if (lstatSync(abs, { throwIfNoEntry: false })?.isSymbolicLink()) { await unlink(abs); return; }if (!existsSync(abs)) throw new FileError(`${rel} is not there`, 404);await moveToTrash(abs);}++/* ── media kept elsewhere: copied in (cloned where the disk can) or linked (src/media-links.mjs) ── */++/** The first free name for `name` in `dir`: `name.ext`, then `name 2.ext`… (importFile's rule). */+function freeIn(/** @type {string} */ dir, /** @type {string} */ name) {+ const ext = extname(name);+ for (let n = 1; ; n++) {+ const candidate = n === 1 ? name : `${name.slice(0, name.length - ext.length)} ${n}${ext}`;+ if (!lstatSync(join(dir, candidate), { throwIfNoEntry: false })) return candidate;+ }+}++/**+ * Bring files or folders from this computer into the project folder `into` (`assets` or under it): `copy` copies each+ * (a clone where the disk can make one: at once, and no more room taken until either is changed), `link` puts a link+ * to it there and remembers the place as one the person linked. A link to the same place already there is that one.+ * Returns where each landed.+ * @param {string} root @param {string} into @param {string[]} paths @param {'copy' | 'link'} mode+ */+export async function bringIn(root, into, paths, mode) {+ if (into !== ASSETS && !into.startsWith(`${ASSETS}/`)) throw new FileError('media goes in assets/');+ const dir = inside(root, into);+ await mkdir(dir, { recursive: true });+ /** @type {string[]} */+ const landed = [];+ for (const path of paths) {+ if (typeof path !== 'string' || !isAbsolute(path)) throw new FileError('a full path, please');+ const from = realpathSync.native(path);+ const info = await stat(from);+ const name = cleanName(basename(from));+ if (!name || name.startsWith('.')) throw new FileError(`${basename(from)} can't be named here`);+ if (mode === 'link') {+ /* the person picked it: theirs to read, whichever link leads there */+ addLinkedPlaces([from]);+ const same = (await readdir(dir)).find((n) => {+ const at = join(dir, n);+ return lstatSync(at).isSymbolicLink() && (() => { try { return realpathSync.native(at) === from; } catch { return false; } })();+ });+ if (same) { landed.push(posix(relative(root, join(dir, same)))); continue; }+ const at = join(dir, freeIn(dir, name));+ await symlink(from, at, info.isDirectory() ? 'dir' : 'file');+ landed.push(posix(relative(root, at)));+ continue;+ }+ const at = join(dir, freeIn(dir, name));+ /* under a hidden name until it is all there: the pane never shows half a file */+ const part = join(dir, `.${basename(at)}.${process.pid}.importing`);+ try {+ if (info.isDirectory()) await cp(from, part, { recursive: true, mode: constants.COPYFILE_FICLONE, filter: (src) => !basename(src).startsWith('.') });+ else await copyFile(from, part, constants.COPYFILE_FICLONE);+ await rename(part, at);+ } catch (e) {+ await rm(part, { recursive: true, force: true });+ throw e;+ }+ landed.push(posix(relative(root, at)));+ }+ return landed;+}++/**+ * Point a link at another place (a NAS that moved, a file renamed there): the person's pick, remembered as linked.+ * @param {string} root @param {string} rel @param {string} to+ */+export async function relink(root, rel, to) {+ const abs = entryInside(root, rel);+ if (!lstatSync(abs, { throwIfNoEntry: false })?.isSymbolicLink()) throw new FileError(`${rel} is not a link`);+ if (typeof to !== 'string' || !isAbsolute(to)) throw new FileError('a full path, please');+ const from = realpathSync.native(to);+ const info = await stat(from);+ addLinkedPlaces([from]);+ const part = `${abs}.${process.pid}.linking`;+ await symlink(from, part, info.isDirectory() ? 'dir' : 'file');+ await rename(part, abs);+ return rel;+}++/**+ * Copy what a link leads to into the project in its place (an editor's "collect files"): the film then has its own+ * copy, to share or to keep when the NAS is gone. Cloned where the disk can. The original stays where it is.+ * @param {string} root @param {string} rel+ */+export async function collect(root, rel) {+ const abs = entryInside(root, rel);+ if (!lstatSync(abs, { throwIfNoEntry: false })?.isSymbolicLink()) return rel;+ const from = readable(root, rel);+ const info = await stat(from);+ const part = join(dirname(abs), `.${basename(abs)}.${process.pid}.collecting`);+ try {+ if (info.isDirectory()) await cp(from, part, { recursive: true, mode: constants.COPYFILE_FICLONE, filter: (src) => !basename(src).startsWith('.') });+ else await copyFile(from, part, constants.COPYFILE_FICLONE);+ await unlink(abs);+ await rename(part, abs);+ } catch (e) {+ await rm(part, { recursive: true, force: true });+ throw e;+ }+ return rel;+}diff --git a/packages/openfilm/studio/server/files.test.mjs b/packages/openfilm/studio/server/files.test.mjsindex 7ad6c29..f440046 100644--- a/packages/openfilm/studio/server/files.test.mjs+++ b/packages/openfilm/studio/server/files.test.mjs@@ -4,7 +4,8 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkSimport { tmpdir } from 'node:os';import { join } from 'node:path';import { Readable } from 'node:stream';-import { FileError, cleanName, extractAudio, freezeFrame, importFile, inProject, inside, listFiles, makeFolder, moveCheck, moveFile, trashFile } from './files.mjs';+import { FileError, bringIn, cleanName, collect, extractAudio, freezeFrame, importFile, inProject, inside, listFiles, makeFolder, moveCheck, moveFile, readable, relink, trashFile } from './files.mjs';+import { lstatSync, rmSync } from 'node:fs';import { execFileSync } from 'node:child_process';import { filmHtml, readFilmFile } from '../../src/film-doc.mjs';@@ -13,6 +14,8 @@ beforeEach(() => {root = mkdtempSync(join(tmpdir(), 'of-files-'));trash = mkdtempSync(join(tmpdir(), 'of-trash-'));process.env.OPENFILM_TRASH_DIR = trash;+ /* the places the person linked are kept in Studio's home: one of each test's own */+ process.env.OPENFILM_HOME = mkdtempSync(join(tmpdir(), 'of-home-'));});const put = (rel, text = 'x') => { mkdirSync(join(root, rel, '..'), { recursive: true }); writeFileSync(join(root, rel), text); };@@ -211,3 +214,88 @@ test('a freeze frame is the video\'s frame at that moment, full size, a PNG besiawait assert.rejects(freezeFrame(root, 'assets/none.mp4', 0), FileError);await assert.rejects(freezeFrame(root, '../x.mp4', 0), FileError);});++test('media linked from elsewhere (a NAS): read through the link, listed, never written there', links, async () => {+ const nas = mkdtempSync(join(tmpdir(), 'of-nas-'));+ writeFileSync(join(nas, 'take 1.mp4'), 'footage');+ mkdirSync(join(nas, 'b-roll'));+ writeFileSync(join(nas, 'b-roll', 'sky.png'), 'sky');+ mkdirSync(join(root, 'assets'));+ assert.deepEqual(await bringIn(root, 'assets', [join(nas, 'take 1.mp4'), join(nas, 'b-roll')], 'link'), ['assets/take 1.mp4', 'assets/b-roll']);+ assert.ok(lstatSync(join(root, 'assets', 'take 1.mp4')).isSymbolicLink());+ /* the same place linked again is the link there */+ assert.deepEqual(await bringIn(root, 'assets', [join(nas, 'take 1.mp4')], 'link'), ['assets/take 1.mp4']);+ /* read: followed; a film's clip finds it */+ assert.equal(readable(root, 'assets/take 1.mp4'), join(root, 'assets', 'take 1.mp4'));+ assert.ok(inProject(root, 'assets/b-roll/sky.png'));+ /* written: never */+ assert.throws(() => inside(root, 'assets/b-roll/new.png'), FileError);+ await assert.rejects(importFile(root, 'assets/b-roll/x.png', Readable.from([Buffer.from('x')])), FileError);+ await assert.rejects(moveFile(root, 'assets/take 1.mp4', 'assets/b-roll/take 1.mp4'), FileError);+ /* listed: the linked folder and what is in it, each link with where it leads */+ const listed = await listFiles(root);+ assert.deepEqual(listed.files.map((f) => f.path), ['assets/b-roll/sky.png', 'assets/take 1.mp4']);+ assert.ok(listed.folders.includes('assets/b-roll'));+ assert.deepEqual(Object.keys(listed.links).sort(), ['assets/b-roll', 'assets/take 1.mp4']);+ assert.equal(listed.links['assets/take 1.mp4'].missing, undefined);+ /* moved in the project: the link moves; deleted: only the link goes, the footage stays where it is kept */+ mkdirSync(join(root, 'assets', 'cuts'));+ assert.equal((await moveFile(root, 'assets/take 1.mp4', 'assets/cuts/take 1.mp4')).path, 'assets/cuts/take 1.mp4');+ await trashFile(root, 'assets/cuts/take 1.mp4');+ assert.ok(!existsSync(join(root, 'assets', 'cuts', 'take 1.mp4')));+ assert.equal(readFileSync(join(nas, 'take 1.mp4'), 'utf8'), 'footage');+ assert.deepEqual(readdirSync(trash), [], 'nothing of the NAS in the trash');+ rmSync(nas, { recursive: true, force: true });+});++test('a link that leads nowhere (the NAS is off) is listed as missing, relinked, and collected into the project', links, async () => {+ const nas = mkdtempSync(join(tmpdir(), 'of-nas-'));+ writeFileSync(join(nas, 'a.png'), 'one');+ mkdirSync(join(root, 'assets'));+ await bringIn(root, 'assets', [join(nas, 'a.png')], 'link');+ rmSync(join(nas, 'a.png'));+ const off = await listFiles(root);+ assert.deepEqual(off.files.map((f) => f.path), ['assets/a.png']);+ assert.equal(off.links['assets/a.png'].missing, true);+ assert.equal(inProject(root, 'assets/a.png'), null);+ /* pointed at where it is now, then copied in: the project's own file, the original untouched */+ const moved = mkdtempSync(join(tmpdir(), 'of-nas2-'));+ writeFileSync(join(moved, 'a.png'), 'two');+ await relink(root, 'assets/a.png', join(moved, 'a.png'));+ assert.equal(readFileSync(join(root, 'assets', 'a.png'), 'utf8'), 'two');+ await collect(root, 'assets/a.png');+ assert.ok(!lstatSync(join(root, 'assets', 'a.png')).isSymbolicLink());+ assert.equal(readFileSync(join(root, 'assets', 'a.png'), 'utf8'), 'two');+ assert.equal(readFileSync(join(moved, 'a.png'), 'utf8'), 'two');+ assert.deepEqual((await listFiles(root)).links, {});+});++test('a link a project brings from elsewhere is not followed, even to a file that is there; one the person makes is', links, async () => {+ const away = mkdtempSync(join(tmpdir(), 'of-away-'));+ writeFileSync(join(away, 'secret.png'), 'theirs');+ mkdirSync(join(root, 'assets'));+ symlinkSync(join(away, 'secret.png'), join(root, 'assets', 'pic.png'));+ assert.equal(inProject(root, 'assets/pic.png'), null);+ assert.equal((await listFiles(root)).links['assets/pic.png'].missing, true);+ /* outside assets/ no link is followed, linked or not */+ await bringIn(root, 'assets', [join(away, 'secret.png')], 'link');+ symlinkSync(join(away, 'secret.png'), join(root, 'page.png'));+ assert.equal(inProject(root, 'page.png'), null);+ assert.ok(inProject(root, 'assets/pic.png'), 'the place is linked now');+});++test('files copied in from this computer: a copy each under a free name, the originals left as they are', async () => {+ const disk = mkdtempSync(join(tmpdir(), 'of-disk-'));+ writeFileSync(join(disk, 'a.png'), 'pic');+ mkdirSync(join(disk, 'set'));+ writeFileSync(join(disk, 'set', 'b.wav'), 'snd');+ writeFileSync(join(disk, 'set', '.DS_Store'), '');+ put('assets/a.png', 'other');+ assert.deepEqual(await bringIn(root, 'assets', [join(disk, 'a.png'), join(disk, 'set')], 'copy'), ['assets/a 2.png', 'assets/set']);+ assert.equal(readFileSync(join(root, 'assets', 'a 2.png'), 'utf8'), 'pic');+ assert.deepEqual(readdirSync(join(root, 'assets', 'set')), ['b.wav']);+ assert.ok(!lstatSync(join(root, 'assets', 'set')).isSymbolicLink());+ assert.equal(readFileSync(join(disk, 'a.png'), 'utf8'), 'pic');+ await assert.rejects(bringIn(root, 'scenes', [join(disk, 'a.png')], 'copy'), FileError);+ await assert.rejects(bringIn(root, 'assets', ['a.png'], 'copy'), FileError);+});diff --git a/packages/openfilm/studio/server/folder-picker.mjs b/packages/openfilm/studio/server/folder-picker.mjsindex 64a7140..4113bd9 100644--- a/packages/openfilm/studio/server/folder-picker.mjs+++ b/packages/openfilm/studio/server/folder-picker.mjs@@ -1,10 +1,14 @@// @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`).+ * The system's own folder and file dialogs, opened by Studio for a page in a browser (which can never learn a path):+ * the export's "Save to", and the media pane's "Import" and "Link" (pickFiles). The desktop app opens its own folder+ * dialog instead (lib/host.ts `folders.pick`).*- * macOS osascript, `choose folder`- * Windows PowerShell, the Windows Forms folder dialog+ * macOS osascript, `choose folder` / `choose file`, asked of Finder: a dialog of osascript's own opens behind+ * the browser (macOS lets no background program bring itself forward), so it seems nothing happened. The+ * first time, macOS asks once to let Studio's program control Finder; the app that was in front comes back+ * when the dialog closes.+ * Windows PowerShell, the Windows Forms folder / file 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@@ -12,7 +16,37 @@*/import { execFile } from 'node:child_process';import { existsSync } from 'node:fs';-import { isAbsolute } from 'node:path';+import { dirname, isAbsolute } from 'node:path';++/**+ * osascript's lines (`-e` each) for a dialog Finder opens in front, `lines` setting `picked`; the app that was in+ * front is brought back after, picked or not. @param {string[]} lines+ */+function finderDialog(lines) {+ return [+ 'on run argv',+ 'set frontApp to (path to frontmost application as text)',+ /* the folder to start in, made here: Finder can't make a path one (-1700), and one that is gone opens none */+ 'set startAt to missing value',+ 'if (item 2 of argv) is not "" then',+ 'try',+ 'set startAt to (POSIX file (item 2 of argv)) as alias',+ 'end try',+ 'end if',+ 'try',+ 'tell application "Finder"',+ 'activate',+ ...lines,+ 'end tell',+ 'on error message number n',+ 'tell application frontApp to activate',+ 'error message number n',+ 'end try',+ 'tell application frontApp to activate',+ 'return picked',+ 'end run',+ ].flatMap((line) => ['-e', line]);+}/*** How to open the dialog here: the program, its arguments and the environment it adds; null when this system has none.@@ -24,16 +58,13 @@ export function folderPickerCommand(platform, { title, at }, has = () => true) {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,- ],+ args: [...finderDialog([+ 'if startAt is missing value then',+ 'set picked to POSIX path of (choose folder with prompt (item 1 of argv))',+ 'else',+ 'set picked to POSIX path of (choose folder with prompt (item 1 of argv) default location startAt)',+ 'end if',+ ]), title, start],};}if (platform === 'win32') {@@ -55,6 +86,73 @@ export function folderPickerCommand(platform, { title, at }, has = () => true) {return null;}+/**+ * How to open the dialog that picks files (several at once): the program, its arguments and the environment it adds;+ * null when this system has none. It prints one path a line.+ * @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 filePickerCommand(platform, { title, at }, has = () => true) {+ const start = at && isAbsolute(at) ? at : '';+ if (platform === 'darwin') {+ return {+ cmd: 'osascript',+ args: [...finderDialog([+ 'if startAt is missing value then',+ 'set chosen to choose file with prompt (item 1 of argv) with multiple selections allowed',+ 'else',+ 'set chosen to choose file with prompt (item 1 of argv) default location startAt with multiple selections allowed',+ 'end if',+ 'set picked to ""',+ 'repeat with f in chosen',+ 'set picked to picked & POSIX path of f & linefeed',+ 'end repeat',+ ]), title, start],+ };+ }+ if (platform === 'win32') {+ const script = [+ 'Add-Type -AssemblyName System.Windows.Forms',+ '$d = New-Object System.Windows.Forms.OpenFileDialog',+ '$d.Title = $env:OPENFILM_PICK_TITLE',+ '$d.Multiselect = $true',+ 'if ($env:OPENFILM_PICK_AT) { $d.InitialDirectory = $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.FileNames -join "`n")) }',+ ].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', '--multiple', '--separator=\n', `--title=${title}`, ...(start ? [`--filename=${start}/`] : [])] };+ }+ if (has('kdialog')) return { cmd: 'kdialog', args: ['--getopenfilename', start || '.', '--multiple', '--separate-output', '--title', title] };+ return null;+}++/**+ * Whether a dialog that gave nothing was cancelled: osascript says error -128 (any other error exits 1 too: Finder+ * not allowed, -1743, is a failure, and the page lets the person type the path), zenity and kdialog exit 1, Windows+ * prints nothing. @param {string} cmd @param {import('node:child_process').ExecFileException | null} error+ */+export function cancelled(cmd, error) {+ if (!error) return true;+ if (/-128\b|User canceled/i.test(String(error.message))) return true;+ return cmd !== 'osascript' && error.code === 1;+}++/**+ * Where a dialog starts: the folder asked, or the nearest folder above it that is there (an exports folder is made+ * by the first export); none when nothing of it is. @param {string | null | undefined} at+ * @param {(path: string) => boolean} [exists]+ */+export function startFolder(at, exists = existsSync) {+ if (!at || !isAbsolute(at)) return null;+ for (let dir = at; ; dir = dirname(dir)) {+ if (exists(dir)) return dir;+ if (dirname(dir) === dir) 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}`));@@ -64,16 +162,34 @@ const onPath = (name) => (process.env.PATH ?? '').split(':').some((dir) => dir &* @param {{ title: string, at?: string | null }} ask @returns {Promise<string | null>}*/export function pickFolder(ask) {- const command = folderPickerCommand(process.platform, ask, onPath);+ const command = folderPickerCommand(process.platform, { ...ask, at: startFolder(ask.at) }, 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 (cancelled(command.cmd, error)) { resolve(null); return; }if (/** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT') { reject(new Error('no folder dialog on this system')); return; }reject(error);});});}++/**+ * Ask the person for files. Resolves their paths (none when they cancelled); rejects when this system has no dialog+ * Studio can open.+ * @param {{ title: string, at?: string | null }} ask @returns {Promise<string[]>}+ */+export function pickFiles(ask) {+ const command = filePickerCommand(process.platform, { ...ask, at: startFolder(ask.at) }, onPath);+ if (!command) return Promise.reject(new Error('no file 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 paths = String(stdout).split(/\r?\n/).map((line) => line.trim()).filter((line) => line && isAbsolute(line));+ if (paths.length) { resolve(paths); return; }+ if (cancelled(command.cmd, error)) { resolve([]); return; }+ if (/** @type {NodeJS.ErrnoException} */ (error).code === 'ENOENT') { reject(new Error('no file 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.mjsindex eb1c715..f3fa388 100644--- a/packages/openfilm/studio/server/folder-picker.test.mjs+++ b/packages/openfilm/studio/server/folder-picker.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { folderPickerCommand } from './folder-picker.mjs';+import { cancelled, filePickerCommand, folderPickerCommand, startFolder } 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' });@@ -26,3 +26,47 @@ test('Linux: zenity, else kdialog, else none', () => {assert.equal(folderPickerCommand('linux', { title: 'T' }, (n) => n === 'kdialog').cmd, 'kdialog');assert.equal(folderPickerCommand('linux', { title: 'T' }, () => false), null);});++test('files: several at once, a path a line; the words are arguments, never inside the script', () => {+ const mac = filePickerCommand('darwin', { title: 'Link "media" end tell', at: '/Volumes/NAS' });+ assert.deepEqual(mac.args.slice(-2), ['Link "media" end tell', '/Volumes/NAS']);+ assert.ok(mac.args.some((a) => a.includes('multiple selections allowed')));+ assert.ok(mac.args.filter((a, i) => mac.args[i - 1] === '-e').every((line) => !line.includes('media')));+ const win = filePickerCommand('win32', { title: "it's mine" });+ assert.equal(win.env.OPENFILM_PICK_TITLE, "it's mine");+ assert.match(win.args.at(-1), /Multiselect = \$true/);+ assert.ok(filePickerCommand('linux', { title: 'T' }, (n) => n === 'zenity').args.includes('--multiple'));+ assert.equal(filePickerCommand('linux', { title: 'T' }, () => false), null);+});++test('macOS: Finder opens the dialog, in front, and the app that was in front comes back', () => {+ for (const c of [folderPickerCommand('darwin', { title: 'T' }), filePickerCommand('darwin', { title: 'T' })]) {+ const lines = c.args.filter((a, i) => c.args[i - 1] === '-e');+ assert.ok(lines.indexOf('tell application "Finder"') < lines.indexOf('activate'));+ assert.equal(lines.filter((l) => l === 'tell application frontApp to activate').length, 2, 'after a pick and after a cancel');+ }+});++test('only a real cancel is a cancel: osascript failing (Finder not allowed) is an error the page answers', () => {+ const fail = (/** @type {number} */ code, /** @type {string} */ message) => Object.assign(new Error(message), { code });+ assert.equal(cancelled('osascript', null), true);+ assert.equal(cancelled('osascript', fail(1, 'execution error: User canceled. (-128)')), true);+ assert.equal(cancelled('osascript', fail(1, 'execution error: Not authorized to send Apple events to Finder. (-1743)')), false);+ assert.equal(cancelled('zenity', fail(1, '')), true);+ assert.equal(cancelled('kdialog', fail(2, 'crashed')), false);+});++test('a dialog starts in the folder asked, or the nearest one above it that is there', () => {+ const there = new Set(['/', '/Films', '/Films/Cut']);+ const exists = (/** @type {string} */ p) => there.has(p);+ assert.equal(startFolder('/Films/Cut', exists), '/Films/Cut');+ assert.equal(startFolder('/Films/Cut/exports/not yet', exists), '/Films/Cut');+ assert.equal(startFolder('relative/path', exists), null);+ assert.equal(startFolder(null, exists), null);+});++test('macOS: the starting folder is made before Finder is asked, and one that is gone opens none', () => {+ const lines = folderPickerCommand('darwin', { title: 'T', at: '/Films' }).args.filter((a, i, all) => all[i - 1] === '-e');+ assert.ok(lines.indexOf('set startAt to (POSIX file (item 2 of argv)) as alias') < lines.indexOf('tell application "Finder"'));+ assert.ok(!lines.some((l) => l.includes('default location (POSIX file')), 'Finder never makes a path a folder itself');+});diff --git a/packages/openfilm/studio/server/jianying.mjs b/packages/openfilm/studio/server/jianying.mjsnew file mode 100644index 0000000..324dfff--- /dev/null+++ b/packages/openfilm/studio/server/jianying.mjs@@ -0,0 +1,289 @@+// @ts-check+/**+ * The film as a 剪映 (Jianying Pro) or CapCut draft (the same editor, one for China, one for elsewhere, with the same+ * drafts in their own folders): the editor's timeline (nle.mjs planNleTimeline, the same plan the XML is+ * written from) as the draft folder 剪映 lists on its home screen, so the film opens there as a project, ready to keep+ * cutting. exports.mjs makes the media the plan asks for; this file only writes the draft's JSON, so it can be+ * checked on its own.+ *+ * What 剪映 reads (tested with 剪映 11.6 on macOS): a folder in its drafts folder with `draft_info.json` (what Windows+ * calls `draft_content.json`; both are written) and `draft_meta_info.json`, plain JSON. 剪映 saves its own drafts+ * encrypted, but opens a plain one and saves it encrypted from then on. CapCut keeps its drafts plain; a draft says+ * which of the two wrote it.+ *+ * The rules:+ * · Times are microseconds: a clip's frames on the plan's rate, rounded edge by edge, so two clips back to back+ * share their cut.+ * · A picture is fitted whole inside the canvas first (as 剪映 places anything new), then scaled: `scale` is the+ * plan's Basic Motion over that fit; its place is in half-canvas units, y upward.+ * · Footage keeps its own sound: the sound clip linked to it in the plan becomes the video clip's level, so nothing+ * plays twice. Other sounds are audio clips, their fades 剪映's own fades.+ * · A hidden track's clips come hidden, a muted track's sounds muted, one click from back on.+ * · Subtitles are text clips on a track of their own, white with a dark edge, low in the picture.+ * · Each file is in the draft's media library (draft_meta_info.json `draft_materials`, group 0, what the app lists+ * under its media panel), and each material names its entry there (`local_material_id`): without it the app+ * lists none of them and finds a video by nothing but its path.+ */+import { randomUUID } from 'node:crypto';+import { join } from 'node:path';++/**+ * @typedef {import('./nle.mjs').NleTimeline} NleTimeline+ * @typedef {import('./nle.mjs').NleClip} NleClip+ * @typedef {import('./nle.mjs').NleFile} NleFile+ * @typedef {{ text: string, startMs: number, durMs: number }} JianyingCue+ */++/** @typedef {'jianying' | 'capcut'} DraftApp */++/** Each app's folder, in Movies on a Mac and in the local app data on Windows. */+const APP_FOLDER = /** @type {Record<DraftApp, string>} */ ({ jianying: 'JianyingPro', capcut: 'CapCut' });++/**+ * Where 剪映 or CapCut keeps its drafts by default (its Settings › Drafts location can move them): the folder when it+ * is there, else null.+ * @param {DraftApp} app+ * @param {{ platform?: NodeJS.Platform, home: string, localAppData?: string, exists: (path: string) => boolean }} where+ */+export function draftsRoot(app, { platform = process.platform, home, localAppData, exists }) {+ const base = platform === 'darwin' ? join(home, 'Movies') : platform === 'win32' ? localAppData ?? join(home, 'AppData', 'Local') : null;+ const dir = base && join(base, APP_FOLDER[app], 'User Data', 'Projects', 'com.lveditor.draft');+ return dir && exists(dir) ? dir : null;+}++/** 剪映 ids: 32 hex digits for materials and clips, an upper-case UUID for the draft. */+const hex = () => randomUUID().replace(/-/g, '');++/** A photo's length in 剪映: three hours, so any clip of it fits. */+const PHOTO_US = 10_800_000_000;++/** The material kinds an empty draft lists (剪映 reads the draft whether or not they are there). */+const MATERIAL_KINDS = [+ 'ai_translates', 'audio_balances', 'audio_effects', 'audio_fades', 'audio_track_indexes', 'audios', 'beats', 'canvases',+ 'chromas', 'color_curves', 'digital_humans', 'drafts', 'effects', 'flowers', 'green_screens', 'handwrites', 'hsl', 'images',+ 'log_color_wheels', 'loudnesses', 'manual_deformations', 'masks', 'material_animations', 'material_colors',+ 'multi_language_refs', 'placeholders', 'plugin_effects', 'primary_color_wheels', 'realtime_denoises', 'shapes',+ 'smart_crops', 'smart_relights', 'sound_channel_mappings', 'speeds', 'stickers', 'tail_leaders', 'text_templates', 'texts',+ 'time_marks', 'transitions', 'video_effects', 'video_trackings', 'videos', 'vocal_beautifys', 'vocal_separations',+];++/** The app a draft says wrote it: for 剪映 the one tested to open as a plain draft; CapCut's own id for CapCut. */+const PLATFORM = /** @type {Record<DraftApp, object>} */ ({+ jianying: { app_id: 3704, app_source: 'lv', app_version: '5.9.0', os: 'windows' },+ capcut: { app_id: 359289, app_source: 'cc', app_version: '5.9.0', os: 'windows' },+});++/** A clip's picture settings: none (as placed), or scaled and moved. */+const clipSettings = (/** @type {number} */ scale, /** @type {number} */ x, /** @type {number} */ y) => ({+ alpha: 1, flip: { horizontal: false, vertical: false }, rotation: 0, scale: { x: scale, y: scale }, transform: { x, y },+});++const round6 = (/** @type {number} */ n) => { const r = Math.round(n * 1e6) / 1e6; return Object.is(r, -0) ? 0 : r; };++/**+ * The draft: `info` (draft_info.json) and `meta` (draft_meta_info.json), for the folder `folder` in the app's drafts+ * folder `root`.+ * @param {NleTimeline} timeline+ * @param {{ app?: DraftApp, name: string, folder: string, root: string, cues?: readonly JianyingCue[], now?: number }} opts+ */+export function jianyingDraft(timeline, opts) {+ const platform = PLATFORM[opts.app ?? 'jianying'];+ const fps = timeline.rate.fps;+ /** frame → microseconds, on the plan's rate */+ const us = (/** @type {number} */ frame) => Math.round((frame * 1e6) / fps);+ const span = (/** @type {number} */ from, /** @type {number} */ to) => ({ start: us(from), duration: us(to) - us(from) });+ const files = new Map(timeline.files.map((f) => [f.id, f]));+ /** @type {Record<string, any[]>} */+ const materials = Object.fromEntries(MATERIAL_KINDS.map((k) => [k, []]));+ /** @type {Map<string, string>} one material a file, however many clips use it */+ const materialOf = new Map();+ /** @type {Record<string, unknown>[]} the media library: one entry a file */+ const library = [];+ /** @type {Map<string, string>} a file's entry in the library, by its path */+ const entryOf = new Map();+ const register = (/** @type {NleFile} */ file, /** @type {'video' | 'photo' | 'music'} */ kind, /** @type {string} */ name) => {+ const known = entryOf.get(file.path);+ if (known) return known;+ const id = randomUUID().toUpperCase();+ library.push({+ ai_group_type: '', create_time: -1, duration: kind === 'photo' ? 5_000_000 : us(file.durationFrames), enter_from: 0,+ extra_info: name, file_Path: file.path, height: file.video?.h ?? 0, id, import_time: -1, import_time_ms: -1, item_source: 1,+ material_color_tag: '', md5: '', metetype: kind, roughcut_time_range: { duration: -1, start: -1 },+ sub_time_range: { duration: -1, start: -1 }, type: 0, width: file.video?.w ?? 0,+ });+ entryOf.set(file.path, id);+ return id;+ };++ const material = (/** @type {NleFile} */ file, /** @type {'video' | 'audio'} */ media) => {+ const key = `${media}:${file.id}`;+ const known = materialOf.get(key);+ if (known) return known;+ const id = hex();+ const name = file.path.split(/[\\/]/).pop() ?? file.name;+ if (media === 'video') {+ const still = Boolean(file.video?.still);+ materials.videos.push({+ audio_fade: null, category_id: '', category_name: 'local', check_flag: 63487,+ crop: { upper_left_x: 0, upper_left_y: 0, upper_right_x: 1, upper_right_y: 0, lower_left_x: 0, lower_left_y: 1, lower_right_x: 1, lower_right_y: 1 },+ crop_ratio: 'free', crop_scale: 1, duration: still ? PHOTO_US : us(file.durationFrames),+ height: file.video?.h ?? timeline.height, width: file.video?.w ?? timeline.width,+ id, local_material_id: register(file, still ? 'photo' : 'video', name), material_id: id, material_name: name, media_path: '',+ path: file.path, type: still ? 'photo' : 'video',+ });+ } else {+ materials.audios.push({+ app_id: 0, category_id: '', category_name: 'local', check_flag: 3, copyright_limit_type: 'none',+ duration: us(file.durationFrames), effect_id: '', formula_id: '', id, local_material_id: register(file, 'music', name), music_id: id,+ name, path: file.path,+ source_platform: 0, type: 'extract_music', wave_points: [],+ });+ }+ materialOf.set(key, id);+ return id;+ };+ const speed = () => {+ const id = hex();+ materials.speeds.push({ curve_speed: null, id, mode: 0, speed: 1, type: 'speed' });+ return id;+ };++ /** @type {Record<string, any>[]} */+ const tracks = [];+ let renderIndex = 0;+ const segment = (/** @type {Record<string, any>} */ fields) => ({+ enable_adjust: true, enable_color_correct_adjust: false, enable_color_curves: true, enable_color_match_adjust: false,+ enable_color_wheels: true, enable_lut: true, enable_smart_color_adjust: false, last_nonzero_volume: 1, reverse: false,+ track_attribute: 0, track_render_index: 0, visible: true, id: hex(), common_keyframes: [], keyframe_refs: [],+ speed: 1, volume: 1, is_tone_modify: false, ...fields,+ });++ /* footage's own sound, by the picture it belongs to: the video clip plays it at its level */+ /** @type {Map<string, number>} linkGroup → level */+ const ownSound = new Map();+ for (const t of timeline.audio) {+ for (const c of t.clips) if (c.linkGroup && !c.levels) ownSound.set(c.linkGroup, t.enabled && c.enabled ? c.gain ?? 1 : 0);+ }++ /* pictures: the plan's first track is the bottom one, as 剪映's first video track (its main track) is */+ for (const t of timeline.video) {+ const index = renderIndex++;+ tracks.push({+ attribute: 0, flag: 0, id: hex(), is_default_name: false, name: t.name, type: 'video',+ segments: t.clips.map((c) => {+ const file = /** @type {NleFile} */ (files.get(c.fileId));+ const w = file.video?.w ?? timeline.width, h = file.video?.h ?? timeline.height;+ /* 剪映 first fits it whole in the canvas; the plan's scale is of its own pixels, 100 when none */+ const fit = Math.min(timeline.width / w, timeline.height / h);+ const scale = round6((c.motion ? c.motion.scale / 100 : 1) / fit);+ const x = round6((c.motion?.center.h ?? 0) * 2), y = round6(-(c.motion?.center.v ?? 0) * 2);+ const level = c.linkGroup && ownSound.has(c.linkGroup) ? /** @type {number} */ (ownSound.get(c.linkGroup)) : 0;+ return segment({+ material_id: material(file, 'video'), target_timerange: span(c.start, c.end),+ source_timerange: file.video?.still ? { start: 0, duration: us(c.end) - us(c.start) } : span(c.in, c.out),+ visible: t.enabled && c.enabled, volume: level, last_nonzero_volume: level || 1,+ extra_material_refs: [speed()], clip: clipSettings(scale, x, y), uniform_scale: { on: true, value: 1 },+ hdr_settings: { intensity: 1, mode: 1, nits: 1000 }, render_index: index,+ });+ }),+ });+ }++ /* sounds: footage's own are already its picture's */+ for (const t of timeline.audio) {+ const clips = t.clips.filter((c) => !(c.linkGroup && ownSound.has(c.linkGroup) && timeline.video.some((v) => v.clips.some((p) => p.linkGroup === c.linkGroup))));+ if (!clips.length) continue;+ const index = renderIndex++;+ tracks.push({+ attribute: t.enabled ? 0 : 1, flag: 0, id: hex(), is_default_name: false, name: t.name, type: 'audio',+ segments: clips.map((c) => {+ const file = /** @type {NleFile} */ (files.get(c.fileId));+ const level = c.levels ? Math.max(...c.levels.map((k) => k.value)) : c.gain ?? 1;+ const refs = [speed()];+ /* a fade: the plan's level keyframes (silent at an end) as 剪映's fade in and out */+ if (c.levels && c.levels.length > 1) {+ const keys = c.levels;+ const fadeIn = keys[0].value === 0 ? keys[1].when : 0;+ const last = keys[keys.length - 1];+ const fadeOut = last.value === 0 ? last.when - keys[keys.length - 2].when : 0;+ if (fadeIn > 0 || fadeOut > 0) {+ const id = hex();+ materials.audio_fades.push({ id, fade_in_duration: us(fadeIn), fade_out_duration: us(fadeOut), fade_type: 0, type: 'audio_fade' });+ refs.push(id);+ }+ }+ return segment({+ material_id: material(file, 'audio'), target_timerange: span(c.start, c.end), source_timerange: span(c.in, c.out),+ volume: c.enabled ? round6(level) : 0, last_nonzero_volume: round6(level) || 1,+ extra_material_refs: refs, clip: null, hdr_settings: null, render_index: index,+ });+ }),+ });+ }++ /* subtitles: a text track over everything */+ const cues = (opts.cues ?? []).filter((c) => c.text.trim() && c.durMs > 0);+ if (cues.length) {+ const index = renderIndex++;+ const frame = (/** @type {number} */ ms) => Math.round((ms / 1000) * fps);+ tracks.push({+ attribute: 0, flag: 0, id: hex(), is_default_name: false, name: 'Subtitles', type: 'text',+ segments: cues.map((cue) => {+ const id = hex();+ const text = cue.text.trim();+ materials.texts.push({+ id, type: 'text', typesetting: 0, alignment: 1, letter_spacing: 0, line_spacing: 0.02, line_feed: 1,+ line_max_width: 0.82, force_apply_line_max_width: false, check_flag: 15, global_alpha: 1,+ content: JSON.stringify({+ styles: [{+ fill: { alpha: 1, content: { render_type: 'solid', solid: { alpha: 1, color: [1, 1, 1] } } },+ range: [0, [...text].length], size: 6, bold: false, italic: false, underline: false,+ strokes: [{ content: { render_type: 'solid', solid: { alpha: 1, color: [0, 0, 0] } }, width: 0.08 }],+ }],+ text,+ }),+ });+ const from = frame(cue.startMs), to = Math.max(from + 1, frame(cue.startMs + cue.durMs));+ return segment({+ material_id: id, target_timerange: span(from, to), source_timerange: null, extra_material_refs: [],+ clip: clipSettings(1, 0, -0.8), uniform_scale: { on: true, value: 1 }, render_index: index,+ });+ }),+ });+ }++ const duration = us(timeline.durationFrames);+ const draftId = randomUUID().toUpperCase();+ const now = opts.now ?? Date.now();+ const info = {+ canvas_config: { width: timeline.width, height: timeline.height, ratio: 'original' },+ color_space: 0,+ config: {+ adjust_max_index: 1, attachment_info: [], combination_max_index: 1, export_range: null, extract_audio_last_index: 1,+ lyrics_recognition_id: '', lyrics_sync: true, lyrics_taskinfo: [], maintrack_adsorb: false, material_save_mode: 0,+ multi_language_current: 'none', multi_language_list: [], multi_language_main: 'none', multi_language_mode: 'none',+ original_sound_last_index: 1, record_audio_last_index: 1, sticker_max_index: 1, subtitle_keywords_config: null,+ subtitle_recognition_id: '', subtitle_sync: true, subtitle_taskinfo: [], system_font_list: [], video_mute: false,+ zoom_info_params: null,+ },+ cover: null, create_time: 0, duration, extra_info: null, fps, free_render_index_mode_on: false, group_container: null,+ id: draftId, keyframe_graph_list: [],+ keyframes: { adjusts: [], audios: [], effects: [], filters: [], handwrites: [], stickers: [], texts: [], videos: [] },+ last_modified_platform: platform, platform, materials, mutable_config: null, name: opts.name,+ new_version: '110.0.0', relationships: [], render_index_track_mode_on: false, retouch_cover: null, source: 'default',+ static_cover_image_path: '', time_marks: null, tracks, update_time: 0, version: 360000,+ };+ const meta = {+ cloud_package_completed_time: '', draft_cloud_capcut_purchase_info: '', draft_cloud_last_action_download: false,+ draft_cloud_materials: [], draft_cloud_purchase_info: '', draft_cloud_template_id: '', draft_cloud_tutorial_info: '',+ draft_cloud_videocut_purchase_info: '', draft_cover: '', draft_deeplink_url: '',+ draft_enterprise_info: { draft_enterprise_extra: '', draft_enterprise_id: '', draft_enterprise_name: '', enterprise_material: [] },+ draft_fold_path: opts.folder, draft_id: draftId, draft_is_ai_packaging_used: false, draft_is_ai_shorts: false,+ draft_is_ai_translate: false, draft_is_article_video_draft: false, draft_is_from_deeplink: 'false', draft_is_invisible: false,+ draft_materials: [0, 1, 2, 3, 6, 7, 8].map((type) => ({ type, value: type === 0 ? library : [] })), draft_materials_copied_info: [],+ draft_name: opts.name, draft_new_version: '', draft_removable_storage_device: '', draft_root_path: opts.root,+ draft_segment_extra_info: [], draft_type: '', tm_draft_cloud_completed: '', tm_draft_cloud_modified: 0,+ tm_draft_create: now * 1000, tm_draft_modified: now * 1000, tm_draft_removed: 0, tm_duration: duration,+ };+ return { info, meta };+}diff --git a/packages/openfilm/studio/server/jianying.test.mjs b/packages/openfilm/studio/server/jianying.test.mjsnew file mode 100644index 0000000..c8270f3--- /dev/null+++ b/packages/openfilm/studio/server/jianying.test.mjs@@ -0,0 +1,125 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { join } from 'node:path';+import { planNleTimeline } from './nle.mjs';+import { draftsRoot, jianyingDraft } from './jianying.mjs';++const facts = { w: 960, h: 540, duration: 10, hasVideo: true, hasAudio: true, channels: 2, sampleRate: 48000 };+const sound = { duration: 20, hasVideo: false, hasAudio: true, channels: 2, sampleRate: 48000 };++/** A film: a page over footage placed small, its own sound, music fading in on a muted track's neighbour, a still. */+const plan = (/** @type {Partial<{ musicOn: boolean }>} */ o = {}) => planNleTimeline({+ stage: { w: 1920, h: 1080 }, duration: 6,+ pictures: [+ { id: 'title', kind: 'page', src: 'title.html', path: '/p/title.html', at: 0, end: 2, from: 0, speed: 1, track: 0, hidden: false, facts: null },+ { id: 'shot', kind: 'video', src: 'a.mp4', path: '/p/a.mp4', at: 1, end: 5, from: 2, speed: 1, track: 1, hidden: false, box: { x: 480, y: 0, w: 960 }, facts },+ { id: 'still', kind: 'still', src: 'b.png', path: '/p/b.png', at: 5, end: 6, from: 0, speed: 1, track: 1, hidden: true, facts: { w: 1920, h: 1080 } },+ ],+ sounds: [+ { id: 'shot', src: 'a.mp4', path: '/p/a.mp4', at: 1, from: 2, to: 6, speed: 1, volume: 0.5, enabled: true, role: 'footage', picture: 'shot', facts },+ { id: 'bed', src: 'assets/audio/music/bed.wav', path: '/p/bed.wav', at: 0, from: 0, to: 6, speed: 1, volume: 0.8, enabled: o.musicOn ?? true, role: 'music', facts: sound, fade: [1, 0] },+ ],+}, { title: 'Film', fps: 30, audio: 'clips', media: 'copy', mediaDir: '/drafts/Film/media' });++test('a 剪映 draft: microseconds edge by edge, the plan\'s tracks, bottom first, as 剪映 stacks them', () => {+ const { info, meta } = jianyingDraft(plan(), { name: 'Film', folder: '/drafts/Film', root: '/drafts', now: 1_700_000_000_000 });+ assert.deepEqual(info.canvas_config, { width: 1920, height: 1080, ratio: 'original' });+ assert.equal(info.fps, 30);+ assert.equal(info.duration, 6_000_000);+ assert.deepEqual(info.tracks.map((t) => t.type), ['video', 'video', 'audio']);+ /* the film's second track is under its first: 剪映's first video track is the bottom one */+ const [bottom, top] = info.tracks;+ assert.deepEqual(bottom.segments.map((s) => s.target_timerange), [{ start: 1_000_000, duration: 4_000_000 }, { start: 5_000_000, duration: 1_000_000 }]);+ assert.deepEqual(top.segments[0].target_timerange, { start: 0, duration: 2_000_000 });+ /* footage from its second 2 */+ assert.deepEqual(bottom.segments[0].source_timerange, { start: 2_000_000, duration: 4_000_000 });+ assert.equal(meta.draft_name, 'Film');+ assert.equal(meta.draft_fold_path, '/drafts/Film');+ assert.equal(meta.draft_root_path, '/drafts');+ assert.equal(meta.draft_id, info.id);+ assert.equal(meta.tm_duration, 6_000_000);+});++test('placement: fitted in the canvas, then the plan\'s scale; moved in half-canvas units, y upward', () => {+ const { info } = jianyingDraft(plan(), { name: 'Film', folder: '/d/Film', root: '/d' });+ const shot = info.tracks[0].segments[0];+ /* 960 × 540 at its own size is half of a 1920 × 1080 canvas it would fill: scale 0.5; its middle a quarter up */+ assert.deepEqual(shot.clip.scale, { x: 0.5, y: 0.5 });+ assert.deepEqual(shot.clip.transform, { x: 0, y: 0.5 });+ /* the page fills the canvas as it is */+ assert.deepEqual(info.tracks[1].segments[0].clip.scale, { x: 1, y: 1 });+ const still = info.tracks[0].segments[1];+ assert.equal(still.visible, false, 'a hidden track\'s clip comes hidden');+ const photo = info.materials.videos.find((m) => m.id === still.material_id);+ assert.equal(photo.type, 'photo');+ assert.deepEqual(still.source_timerange, { start: 0, duration: 1_000_000 });+});++test('footage plays its own sound at its level; other sounds are audio clips with 剪映\'s fades', () => {+ const { info } = jianyingDraft(plan(), { name: 'Film', folder: '/d/Film', root: '/d' });+ const shot = info.tracks[0].segments[0];+ assert.equal(shot.volume, 0.5);+ const audio = info.tracks.filter((t) => t.type === 'audio');+ assert.equal(audio.length, 1, 'the footage\'s sound is not a second clip');+ const bed = audio[0].segments[0];+ assert.equal(bed.volume, 0.8);+ const fade = info.materials.audio_fades.find((f) => bed.extra_material_refs.includes(f.id));+ assert.equal(fade.fade_in_duration, 1_000_000);+ assert.equal(fade.fade_out_duration, 0);+ for (const s of info.tracks.flatMap((t) => t.segments)) {+ assert.ok(s.extra_material_refs.some((id) => info.materials.speeds.some((m) => m.id === id)), 'each clip has its speed');+ }+ /* each file one material */+ assert.equal(new Set(info.materials.videos.map((m) => m.path)).size, info.materials.videos.length);+ const silent = jianyingDraft(plan({ musicOn: false }), { name: 'Film', folder: '/d/Film', root: '/d' });+ assert.equal(silent.info.tracks.find((t) => t.type === 'audio').segments[0].volume, 0, 'a sound not heard comes silent');+});++test('subtitles: a text track over all, one clip a cue, white with a dark edge, low in the picture', () => {+ const { info } = jianyingDraft(plan(), { name: 'Film', folder: '/d/Film', root: '/d', cues: [{ text: '你好 world', startMs: 500, durMs: 1500 }, { text: ' ', startMs: 2000, durMs: 500 }] });+ const text = info.tracks.at(-1);+ assert.equal(text.type, 'text');+ assert.equal(text.segments.length, 1, 'an empty cue is left out');+ assert.deepEqual(text.segments[0].target_timerange, { start: 500_000, duration: 1_500_000 });+ assert.equal(text.segments[0].clip.transform.y, -0.8);+ const content = JSON.parse(info.materials.texts[0].content);+ assert.equal(content.text, '你好 world');+ assert.deepEqual(content.styles[0].range, [0, 8]);+ assert.deepEqual(content.styles[0].strokes[0].content.solid.color, [0, 0, 0]);+});++test('the drafts folders: 剪映\'s and CapCut\'s, on a Mac and on Windows, when they are there', () => {+ const mac = (app) => join('/mac-home', 'Movies', app, 'User Data', 'Projects', 'com.lveditor.draft');+ assert.equal(draftsRoot('jianying', { platform: 'darwin', home: '/mac-home', exists: (p) => p === mac('JianyingPro') }), mac('JianyingPro'));+ assert.equal(draftsRoot('capcut', { platform: 'darwin', home: '/mac-home', exists: (p) => p === mac('CapCut') }), mac('CapCut'));+ assert.equal(draftsRoot('capcut', { platform: 'darwin', home: '/mac-home', exists: (p) => p === mac('JianyingPro') }), null);+ const win = join('D:\\local-app-data', 'JianyingPro', 'User Data', 'Projects', 'com.lveditor.draft');+ assert.equal(draftsRoot('jianying', { platform: 'win32', home: 'D:\\win-home', localAppData: 'D:\\local-app-data', exists: (p) => p === win }), win);+ assert.equal(draftsRoot('jianying', { platform: 'linux', home: '/linux-home', exists: () => true }), null);+});++test('a draft says which app wrote it: 剪映 or CapCut', () => {+ const jy = jianyingDraft(plan(), { name: 'Film', folder: '/d/Film', root: '/d' }).info;+ const cc = jianyingDraft(plan(), { app: 'capcut', name: 'Film', folder: '/d/Film', root: '/d' }).info;+ assert.equal(jy.platform.app_source, 'lv');+ assert.equal(cc.platform.app_source, 'cc');+ assert.deepEqual(cc.last_modified_platform, cc.platform);+});++test('each file is in the draft\'s media library, once, and each material names its entry', () => {+ const { info, meta } = jianyingDraft(plan(), { name: 'Film', folder: '/d/Film', root: '/d' });+ const library = meta.draft_materials.find((g) => g.type === 0).value;+ const files = [...info.materials.videos, ...info.materials.audios];+ assert.equal(library.length, new Set(files.map((m) => m.path)).size, 'one entry a file');+ for (const m of files) {+ const entry = library.find((e) => e.id === m.local_material_id);+ assert.ok(entry, `${m.path} is in the library`);+ assert.equal(entry.file_Path, m.path);+ }+ const kinds = Object.fromEntries(library.map((e) => [e.file_Path.split('/').pop(), e.metetype]));+ assert.equal(kinds['bed fade.wav'], 'music', 'the bed, its fade its own part');+ assert.equal(kinds['b.png'], 'photo');+ assert.equal(Object.values(kinds).filter((k) => k === 'video').length, 2, 'the page rendered and the footage');+ const shot = library.find((e) => e.file_Path.endsWith('a.mp4'));+ assert.deepEqual([shot.width, shot.height, shot.duration], [960, 540, 10_000_000]);+});diff --git a/packages/openfilm/studio/server/ops.mjs b/packages/openfilm/studio/server/ops.mjsindex 1af6a1d..33a3041 100644--- a/packages/openfilm/studio/server/ops.mjs+++ b/packages/openfilm/studio/server/ops.mjs@@ -16,7 +16,7 @@ import { FILM_FILE, clipFade, clipIdFor, clipKind, clipSpeed, kindOf } from '../* | { op: 'insert', clip?: Partial<Clip> & { src: string }, from?: string, at?: number, after?: string, track?: number | { insert: number }, newTrack?: number, link?: string | null }* | { op: 'remove', clip: string }* | { op: 'split', clip: string, at: number, time: [number, number], restTime: [number, number], restId?: string }- * | { op: 'split', clip: string, left: Record<string, PropValue>, right: Record<string, PropValue> }+ * | { op: 'split', clip: string, left: Record<string, PropValue>, right: Record<string, PropValue>, rightId?: string }* | { op: 'props', edits: PropEdit[] }* | { op: 'stage', w: number, h: number }* | { op: 'fields', clip: string, fields: Record<string, unknown> }@@ -147,7 +147,10 @@ export function applyOps(value, ops) {const { t, c, clip } = find(value, op.clip);const left = /** @type {Clip} */ (structuredClone(clip));const right = /** @type {Clip} */ (structuredClone(clip));- right.id = mintClipId(usedIds(value), clip.id);+ /* the right half's id: the one asked for (so the editor can select it) when it is free, else `<id>-b` */+ const asked = typeof op.rightId === 'string' && /^[A-Za-z][\w-]*$/.test(op.rightId) && !usedIds(value).includes(op.rightId)+ ? op.rightId : null;+ right.id = asked ?? mintClipId(usedIds(value), clip.id);/* a fade belongs to the end it is at: the left half keeps the fade in, the right one the fade out */splitFades(left, right);for (const [prop, v] of Object.entries(op.left ?? {})) setField(left, prop, snapTime(prop, v));diff --git a/packages/openfilm/studio/server/ops.test.mjs b/packages/openfilm/studio/server/ops.test.mjsindex 63800ff..a65bbc5 100644--- a/packages/openfilm/studio/server/ops.test.mjs+++ b/packages/openfilm/studio/server/ops.test.mjs@@ -47,6 +47,11 @@ test('split into halves the timeline worked out: deep copies, the right one nameassert.deepEqual([l.id, l.time, r.id, r.at, r.time], ['b', [0, 2], 'b-b', 7, [2]]);l.box.x = 9;assert.deepEqual(r.box, { x: 1, y: 2 }, 'the halves share nothing');+ /* the right half takes the id asked for when it is free and well formed */+ const named = applyOps(film(), [{ op: 'split', clip: 'b', left: { end: 2 }, right: { at: 7, start: 2 }, rightId: 'b-right' }]);+ assert.equal(named.tracks[0].clips[2].id, 'b-right');+ const taken = applyOps(film(), [{ op: 'split', clip: 'b', left: { end: 2 }, right: { at: 7, start: 2 }, rightId: 'b' }]);+ assert.equal(taken.tracks[0].clips[2].id, 'b-b');});test('insert: a copy of a clip, after a clip, on a new track, or on the last track of its kind', () => {diff --git a/packages/openfilm/studio/server/pageframes.mjs b/packages/openfilm/studio/server/pageframes.mjsindex 9f68a89..c7e09a9 100644--- a/packages/openfilm/studio/server/pageframes.mjs+++ b/packages/openfilm/studio/server/pageframes.mjs@@ -225,7 +225,8 @@ async function loadedFiles(/** @type {FilmPage} */ page, /** @type {string} */ b}/**- * What a page says of itself, for the media pane: `{ duration (s), width, height }`, no duration when it has no end.+ * What a page says of itself, for the media pane: `{ duration (s), width, height }`, no duration when it has no end;+ * `reflows` when it sets no size of its own (then laid out at what it is given: its size here is 1920 × 1080).* Asked of the page kept open for its poster.* @param {string} root @param {string} base @param {string} rel*/@@ -236,7 +237,7 @@ export async function pageFacts(root, base, rel) {if (!info?.isFile()) throw new PageFrameError(`${rel} is not there`);return withPage(pageUrl(base, rel), POSTER_W, `${info.mtimeMs}:${info.size}`, async (page) => {const duration = lengthOf(page);- return { ...(duration != null ? { duration } : {}), width: page.meta.width, height: page.meta.height };+ return { ...(duration != null ? { duration } : {}), width: page.meta.width, height: page.meta.height, ...(page.meta.sized ? {} : { reflows: true }) };});}diff --git a/packages/openfilm/studio/server/pageframes.test.mjs b/packages/openfilm/studio/server/pageframes.test.mjsindex 391d990..f574338 100644--- a/packages/openfilm/studio/server/pageframes.test.mjs+++ b/packages/openfilm/studio/server/pageframes.test.mjs@@ -109,3 +109,12 @@ test('a page asked for by a path out of the project (`../`) is not there: neverassert.match((await res.json()).error, /is not there/);}});++test('a page\'s facts: its own size, or none (reflows: shown alone at 1920 × 1080, in a film at what it is given)', async () => {+ const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Facts') } })).json();+ writeFileSync(join(project.path, 'chart.html'), '<!doctype html><script>window.film = { width: 480, height: 320, frame() {} };</script>');+ writeFileSync(join(project.path, 'cards.html'), '<!doctype html><script>window.film = { duration: 5, frame() {} };</script>');+ const facts = async (path) => (await api(`/api/projects/${project.id}/media?what=probe&path=${path}`)).json();+ assert.deepEqual(await facts('chart.html'), { width: 480, height: 320 });+ assert.deepEqual(await facts('cards.html'), { duration: 5, width: 1920, height: 1080, reflows: true });+});diff --git a/packages/openfilm/studio/server/pages.mjs b/packages/openfilm/studio/server/pages.mjsindex 4f682d0..bd9f4b4 100644--- a/packages/openfilm/studio/server/pages.mjs+++ b/packages/openfilm/studio/server/pages.mjs@@ -25,6 +25,10 @@ import { mkdir, rename } from 'node:fs/promises';import { createServer } from 'node:http';import { basename, dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';import { HOST_FLAG, folderFiles } from '../../src/host.mjs';+import { readableLink } from '../../src/media-links.mjs';+import { clipKind } from '../../src/film-doc.mjs';+import { readPrefs } from './prefs.mjs';+import { readyProxy } from './proxies.mjs';import { soundOf } from './derived.mjs';const BRIDGE = readFileSync(new URL('./bridge.js', import.meta.url), 'utf8');@@ -44,7 +48,10 @@ async function playableCopy(root, rel) {const file = normalize(join(root, rel));if (!file.startsWith(root + sep)) return null;let info;- try { info = statSync(file); if (!realpathSync(file).startsWith(realpathSync(root) + sep)) return null; } catch { return null; }+ try {+ info = statSync(file);+ if (!realpathSync(file).startsWith(realpathSync(root) + sep) && !readableLink(root, file)) return null;+ } catch { return null; }const name = `${createHash('sha1').update(`${rel}\0${info.size}\0${info.mtimeMs}`).digest('hex').slice(0, 20)}.wav`;const out = join(root, PLAYABLE_DIR, name);try { statSync(out); return name; } catch { /* not made yet */ }@@ -80,8 +87,8 @@ export function ownHost(req, port) {/*** Whether the decoded path `plain` of a project folder may be served: no part of it hidden (`.film`, `.git`, `.env`,* `..`) or with a `:` (on Windows `name::$DATA` is the file `name`, and `.film:` the folder), and the file it names,- * when there is one, really in the folder (not through a link out of it) and not hidden by its real name either (on- * Windows `ENV~1` is the short name of `.env`).+ * when there is one, really in the folder (not through a link out of it, but for media the person linked:+ * src/media-links.mjs) and not hidden by its real name either (on Windows `ENV~1` is the short name of `.env`).* @param {string} root @param {string} plain*/function servable(root, plain) {@@ -92,7 +99,8 @@ function servable(root, plain) {let home;try { home = realpathSync.native(root); } catch { return false; }const back = relative(home, real);- return !back || (!isAbsolute(back) && !back.split(sep).some((part) => part.startsWith('.')));+ if (isAbsolute(back) || back.split(sep)[0] === '..') return readableLink(root, join(root, ...parts));+ return !back || !back.split(sep).some((part) => part.startsWith('.'));}/**@@ -116,6 +124,12 @@ export async function startPages({ port, editorOrigin, secret, projects }) {inject: `<script>${HOST_FLAG}</script>${scripts(BRIDGE)}`,timelineInject: `<script>${HOST_FLAG}</script>${scripts(BRIDGE, STAGE)}`,headers: policy(),+ /* heavy footage is played from its proxy once it is made, while proxies are on (proxies.mjs): the preview only */+ swap: (file) => {+ if (clipKind(file) !== 'video') return null;+ const { proxies } = readPrefs();+ return proxies.on ? readyProxy(root, relative(root, file).split(sep).join('/'), proxies.height) : null;+ },});/** a project's playable copies (UNPLAYABLE), served as its files are */diff --git a/packages/openfilm/studio/server/prefs.mjs b/packages/openfilm/studio/server/prefs.mjsnew file mode 100644index 0000000..65865a8--- /dev/null+++ b/packages/openfilm/studio/server/prefs.mjs@@ -0,0 +1,47 @@+// @ts-check+/**+ * Studio's own preferences, the same for every project (`prefs.json` in Studio's home): what the editor does on this+ * computer, not what a film is. A project's own settings are project-settings.mjs.+ *+ * proxies light copies of heavy footage for the preview (proxies.mjs): on, and how tall+ */+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { studioHome } from './projects.mjs';++/** @typedef {{ proxies: { on: boolean, height: 540 | 720 | 1080 } }} Prefs */++/** As CapCut has them: on, at 720p. */+export const DEFAULT_PREFS = /** @type {Prefs} */ ({ proxies: { on: true, height: 720 } });+const HEIGHTS = [540, 720, 1080];++/** What is kept, each field checked; anything missing or wrong is its default. @param {unknown} raw @returns {Prefs} */+export function prefsOf(raw) {+ const p = /** @type {{ proxies?: { on?: unknown, height?: unknown } } | null} */ (raw && typeof raw === 'object' ? raw : null);+ const height = Number(p?.proxies?.height);+ return {+ proxies: {+ on: typeof p?.proxies?.on === 'boolean' ? p.proxies.on : DEFAULT_PREFS.proxies.on,+ height: /** @type {540 | 720 | 1080} */ (HEIGHTS.includes(height) ? height : DEFAULT_PREFS.proxies.height),+ },+ };+}++const file = () => join(studioHome(), 'prefs.json');++/** @returns {Prefs} */+export function readPrefs() {+ try { return prefsOf(JSON.parse(readFileSync(file(), 'utf8'))); } catch { return prefsOf(null); }+}++/** Change some of them (a field at a time); returns them all. @param {unknown} patch @returns {Prefs} */+export function writePrefs(patch) {+ const now = readPrefs();+ const asked = /** @type {{ proxies?: object }} */ (patch && typeof patch === 'object' ? patch : {});+ const next = prefsOf({ ...now, ...asked, proxies: { ...now.proxies, ...(asked.proxies ?? {}) } });+ const at = file();+ mkdirSync(studioHome(), { recursive: true });+ writeFileSync(`${at}.${process.pid}.tmp`, `${JSON.stringify(next, null, 2)}\n`);+ renameSync(`${at}.${process.pid}.tmp`, at);+ return next;+}diff --git a/packages/openfilm/studio/server/proxies.mjs b/packages/openfilm/studio/server/proxies.mjsnew file mode 100644index 0000000..428b18d--- /dev/null+++ b/packages/openfilm/studio/server/proxies.mjs@@ -0,0 +1,151 @@+// @ts-check+/**+ * Proxies: light copies of heavy footage for the preview to play, as editors make them (CapCut's, Premiere's). Footage+ * past 1080p, or in a form slow to decode (ProRes, HEVC, 10-bit…), from a NAS most of all, stutters when played and+ * scrubbed; its proxy is an H.264 copy `height` px on its short side, its picture only, with the same frames at the+ * same times (passthrough: none added or dropped) and a key frame every half second, so a scrub lands at once. Made in+ * the background, one at a time, kept in the project's cache.+ *+ * Only the preview plays them (pages.mjs swaps a file for its proxy): the film's sound is mixed from the original, and+ * an export or a render reads the originals. Nothing in film.html changes.+ */+import { spawn } from 'node:child_process';+import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, renameSync, rmSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { clipKind } from '../../src/film-doc.mjs';+import { probe } from './derived.mjs';+import { readable } from './files.mjs';+import { TOOL_DIR } from './projects.mjs';++/** Changing how proxies are made makes new ones. */+const VERSION = 1;+/** Decoded at full speed by every browser, 8-bit: light enough as it is, up to 1080p. */+const LIGHT_CODECS = new Set(['h264', 'vp8', 'vp9', 'av1']);+const LIGHT_PIXFMTS = new Set(['yuv420p', 'yuvj420p']);+/** A key frame every half second. */+const GOP_S = 0.5;++/**+ * Whether footage is heavy to play: past 1080p (its long side over 1920 or its short over 1080), or not 8-bit H.264,+ * VP8/9 or AV1 4:2:0.+ * @param {{ width?: number, height?: number, codec?: string, pixfmt?: string }} facts+ */+export function heavy(facts) {+ const w = Number(facts.width), h = Number(facts.height);+ if (!(w > 0 && h > 0) || !facts.codec) return false;+ return Math.max(w, h) > 1920 || Math.min(w, h) > 1080 || !LIGHT_CODECS.has(facts.codec) || !LIGHT_PIXFMTS.has(String(facts.pixfmt));+}++/** The proxy's size: `height` px on the short side (never larger than the footage), even, the shape kept. */+export function proxySize(/** @type {number} */ w, /** @type {number} */ h, /** @type {number} */ height) {+ const k = Math.min(1, height / Math.min(w, h));+ const even = (/** @type {number} */ n) => Math.max(2, Math.round(n / 2) * 2);+ return { w: even(w * k), h: even(h * k) };+}++/**+ * Where `rel`'s proxy at `height` is kept: named by the file itself (so it stays its proxy when the file is renamed or+ * moved) and its version (so a changed file gets a new one).+ */+function proxyFile(/** @type {string} */ root, /** @type {string} */ rel, /** @type {number} */ height) {+ const abs = readable(root, rel);+ const info = statSync(abs);+ const name = createHash('sha1').update(`${VERSION}\0${info.dev}:${info.ino}\0${info.size}\0${Math.round(info.mtimeMs)}\0${height}`).digest('hex').slice(0, 20);+ return { abs, out: join(root, TOOL_DIR, 'cache', 'proxies', `${name}.mp4`) };+}++/** The proxy of `rel` at `height`, when it is made; else null. */+export function readyProxy(/** @type {string} */ root, /** @type {string} */ rel, /** @type {number} */ height) {+ try { const { out } = proxyFile(root, rel, height); return existsSync(out) ? out : null; } catch { return null; }+}++/** @typedef {{ state: 'waiting' | 'making' | 'ready' | 'failed', ratio?: number }} ProxyState */++/** Proxies asked for and not made yet, and what became of each (by its file). @type {Map<string, ProxyState & { make?: () => Promise<void> }>} */+const jobs = new Map();+let running = false;++/** Make the proxies waiting, one at a time. */+async function drain() {+ if (running) return;+ running = true;+ try {+ for (;;) {+ const next = [...jobs.entries()].find(([, job]) => job.state === 'waiting');+ if (!next) return;+ const [out, job] = next;+ job.state = 'making';+ job.ratio = 0;+ try { await job.make?.(); job.state = 'ready'; } catch { job.state = 'failed'; }+ delete job.make;+ if (job.state === 'ready') jobs.delete(out);+ }+ } finally { running = false; }+}++/**+ * What the preview needs for the project's videos `rels` at `height`: a proxy made for each heavy one (asked for when+ * it is not made yet). Returns the state of each heavy one; light footage is left out.+ * @param {string} root @param {string[]} rels @param {number} height+ * @returns {Promise<Record<string, ProxyState>>}+ */+export async function ensureProxies(root, rels, height) {+ /** @type {Record<string, ProxyState>} */+ const states = {};+ for (const rel of rels) {+ if (clipKind(rel) !== 'video') continue;+ let facts;+ try { facts = await probe(root, rel); } catch { continue; }+ if (!heavy(facts)) continue;+ let file;+ try { file = proxyFile(root, rel, height); } catch { continue; }+ const { abs, out } = file;+ if (existsSync(out)) { states[rel] = { state: 'ready' }; continue; }+ /* asked for once; one that failed (footage ffmpeg cannot read) is said, not tried again and again */+ let job = jobs.get(out);+ if (!job) {+ const size = proxySize(Number(facts.width), Number(facts.height), height);+ const fps = Number(facts.fps) > 0 ? Number(facts.fps) : 30;+ const seconds = Number(facts.duration) > 0 ? Number(facts.duration) : 0;+ /** @type {ProxyState & { make?: () => Promise<void> }} */+ const fresh = { state: 'waiting' };+ fresh.make = () => make(abs, out, size, fps, seconds, (ratio) => { fresh.ratio = ratio; });+ jobs.set(out, fresh);+ job = fresh;+ }+ states[rel] = { state: job.state, ...(job.state === 'making' ? { ratio: job.ratio ?? 0 } : {}) };+ }+ void drain();+ return states;+}++/**+ * Make one proxy: through a hidden name, renamed once whole. ffmpeg turns a turned video upright (as it is shown),+ * which is the size asked for.+ * @param {string} abs @param {string} out @param {{ w: number, h: number }} size @param {number} fps @param {number} seconds+ * @param {(ratio: number) => void} progress+ */+function make(abs, out, size, fps, seconds, progress) {+ mkdirSync(join(out, '..'), { recursive: true });+ const part = `${out}.part.mp4`;+ const gop = String(Math.max(1, Math.round(fps * GOP_S)));+ return new Promise((done, fail) => {+ const proc = spawn('ffmpeg', ['-hide_banner', '-nostdin', '-loglevel', 'error', '-y', '-i', abs,+ '-map', '0:v:0', '-an', '-sn', '-dn', '-fps_mode', 'passthrough', '-vf', `scale=${size.w}:${size.h}`,+ '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-g', gop, '-keyint_min', gop, '-pix_fmt', 'yuv420p',+ '-movflags', '+faststart', '-progress', 'pipe:1', '-nostats', part], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });+ let err = '';+ proc.stderr.on('data', (d) => { err += d; });+ proc.stdout.on('data', (d) => {+ const at = /out_time_us=(\d+)/.exec(String(d).split('\n').reverse().join('\n'));+ if (at && seconds > 0) progress(Math.min(0.99, Number(at[1]) / 1e6 / seconds));+ });+ proc.on('error', (e) => { rmSync(part, { force: true }); fail(e); });+ proc.on('close', (code) => {+ if (code === 0 && existsSync(part)) { renameSync(part, out); done(undefined); return; }+ rmSync(part, { force: true });+ fail(new Error(err.trim() || `ffmpeg exit ${code}`));+ });+ });+}diff --git a/packages/openfilm/studio/server/proxies.test.mjs b/packages/openfilm/studio/server/proxies.test.mjsnew file mode 100644index 0000000..ded70a3--- /dev/null+++ b/packages/openfilm/studio/server/proxies.test.mjs@@ -0,0 +1,46 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { ensureProxies, heavy, proxySize, readyProxy } from './proxies.mjs';++const hasFfmpeg = (() => { try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; } catch { return false; } })();++test('heavy footage: past 1080p, or not 8-bit H.264, VP8/9 or AV1', () => {+ assert.equal(heavy({ width: 1920, height: 1080, codec: 'h264', pixfmt: 'yuv420p' }), false);+ assert.equal(heavy({ width: 1080, height: 1920, codec: 'h264', pixfmt: 'yuv420p' }), false, 'a phone\'s 1080p, upright');+ assert.equal(heavy({ width: 3840, height: 2160, codec: 'h264', pixfmt: 'yuv420p' }), true);+ assert.equal(heavy({ width: 1920, height: 1080, codec: 'prores', pixfmt: 'yuv422p10le' }), true);+ assert.equal(heavy({ width: 1920, height: 1080, codec: 'hevc', pixfmt: 'yuv420p' }), true);+ assert.equal(heavy({ width: 1920, height: 1080, codec: 'h264', pixfmt: 'yuv420p10le' }), true);+ assert.equal(heavy({ codec: 'mp3' }), false, 'a sound');+});++test('a proxy is its height on the short side, even, the shape kept, never larger than the footage', () => {+ assert.deepEqual(proxySize(3840, 2160, 720), { w: 1280, h: 720 });+ assert.deepEqual(proxySize(2160, 3840, 720), { w: 720, h: 1280 });+ assert.deepEqual(proxySize(4096, 2160, 540), { w: 1024, h: 540 });+ assert.deepEqual(proxySize(1280, 720, 1080), { w: 1280, h: 720 });+});++test('heavy footage gets a proxy in the background, with the same frames at the same times; light footage none', { skip: !hasFfmpeg && 'no ffmpeg' }, async () => {+ const root = mkdtempSync(join(tmpdir(), 'of-proxies-'));+ mkdirSync(join(root, 'assets'));+ execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'testsrc=size=2560x1440:rate=25:duration=1', '-pix_fmt', 'yuv420p', join(root, 'assets', 'big.mp4')]);+ execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'testsrc=size=640x360:rate=25:duration=1', '-pix_fmt', 'yuv420p', join(root, 'assets', 'small.mp4')]);+ const first = await ensureProxies(root, ['assets/big.mp4', 'assets/small.mp4'], 540);+ assert.deepEqual(Object.keys(first), ['assets/big.mp4']);+ assert.ok(['waiting', 'making'].includes(first['assets/big.mp4'].state));+ let states = first;+ for (const end = Date.now() + 30_000; states['assets/big.mp4']?.state !== 'ready' && Date.now() < end;) {+ await new Promise((r) => setTimeout(r, 100));+ states = await ensureProxies(root, ['assets/big.mp4'], 540);+ }+ assert.equal(states['assets/big.mp4'].state, 'ready');+ const proxy = readyProxy(root, 'assets/big.mp4', 540);+ const info = JSON.parse(execFileSync('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-count_frames', '-show_entries', 'stream=width,height,nb_read_frames,codec_name', '-of', 'json', proxy]).toString()).streams[0];+ assert.deepEqual([info.width, info.height, info.codec_name, Number(info.nb_read_frames)], [960, 540, 'h264', 25]);+ assert.equal(readyProxy(root, 'assets/big.mp4', 720), null, 'another height is another proxy');+});diff --git a/packages/openfilm/studio/server/server.mjs b/packages/openfilm/studio/server/server.mjsindex 37d76b9..ad3a1d4 100644--- a/packages/openfilm/studio/server/server.mjs+++ b/packages/openfilm/studio/server/server.mjs@@ -3,15 +3,17 @@* OpenFilm Studio's server: one process for the whole editor. Two origins, so a web page can never reach the editor:** http://127.0.0.1:<port> the editor's pages and its API. The API needs the launch key: as a cookie, set by- * /open?key=…, or as `x-studio-key` (the CLI). Writes from a browser must come from- * this origin.+ * any page's address with ?key=… (/open?key=… too), or as `x-studio-key` (the CLI).+ * The key stays in the pages' address, so a copied address opens Studio anywhere on+ * this machine (another browser, an agent's preview). Writes from a browser must come+ * from this origin.* http://localhost:<port + 1> the film itself: project files, read only, for the preview (see pages.mjs).** Both answer only requests addressed to 127.0.0.1, localhost or [::1] at their own port (ownHost): another site* whose name is pointed at this machine (DNS rebinding) gets nothing, not even /api/health.*/import { randomBytes, timingSafeEqual } from 'node:crypto';-import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';import { basename, extname, isAbsolute, join, normalize, resolve, sep } from 'node:path';import { fileURLToPath } from 'node:url';import { createServer } from 'node:http';@@ -19,8 +21,8 @@ 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, moveCheck, moveFile, trashFile } from './files.mjs';-import { ExportError, createExports, exportCapabilities, exportsRoot, projectSizes } from './exports.mjs';+import { FileError, bringIn, collect, extractAudio, freezeFrame, importFile, inside, listFiles, makeFolder, moveCheck, moveFile, readable, relink, trashFile } from './files.mjs';+import { ExportError, createExports, draftApps, exportCapabilities, exportsRoot, projectSizes } from './exports.mjs';import { MediaError, frame, loudness, poster, probe, waveform } from './derived.mjs';import { HistoryError, checkout, commitChanges, deleteBranch, discardChanges, historyFiles, log, mergeBranch, renameBranch, restoreCommit, status as historyStatus } from './history.mjs';import { ownHost, startPages } from './pages.mjs';@@ -33,7 +35,9 @@ 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 { pickFiles, pickFolder } from './folder-picker.mjs';+import { readPrefs, writePrefs } from './prefs.mjs';+import { ensureProxies } from './proxies.mjs';import { npmOpenfilm, olderThanThis } from '../client.mjs';import { writeAtomic } from './atomic.mjs';import { createWatchers } from './watch.mjs';@@ -155,16 +159,29 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse/* which Studio this is: the CLI replaces an older one, and finds its own home's when run.json is gone. Askedwithout the key, so it says nothing of the machine: its home only as a digest (homeTag), no process id */if (path === '/api/health') return json(res, 200, { product: 'openfilm-studio', version: VERSION, home: homeTag(), filmOrigin });+ const signIn = [`${COOKIE}=${key}; Path=/; HttpOnly; SameSite=Strict`, `${FRAMED}=${key}; Path=/; HttpOnly; Secure; SameSite=None; Partitioned`];+ /** A page's address with the key in it (the address bar is what a person copies). */+ const keyed = (/** @type {string} */ to) => {+ const at = new URL(to, origin);+ at.searchParams.set('key', String(key));+ return at.pathname + at.search;+ };if (path === '/open') {if (!sameKey(url.searchParams.get('key'))) throw new HttpError(403, 'this link is from another Studio launch; use the one `openfilm open` printed');const to = url.searchParams.get('to') ?? '/';- res.writeHead(302, {- location: /^\/(?!\/)[^\s\\]*$/.test(to) ? to : '/',- 'set-cookie': [`${COOKIE}=${key}; Path=/; HttpOnly; SameSite=Strict`, `${FRAMED}=${key}; Path=/; HttpOnly; Secure; SameSite=None; Partitioned`],- });+ res.writeHead(302, { location: keyed(/^\/(?!\/)[^\s\\]*$/.test(to) ? to : '/'), 'set-cookie': signIn, 'referrer-policy': 'no-referrer' });return res.end();}- if (!path.startsWith('/api/')) return sendEditor(res, editorDir, path);+ if (!path.startsWith('/api/')) {+ if (path.startsWith('/assets/')) return sendEditor(res, editorDir, path);+ /* a page with the key in its address signs this browser in; one signed in without it gets it in its address */+ if (sameKey(url.searchParams.get('key'))) return sendEditor(res, editorDir, path, { 'set-cookie': signIn });+ if (sameKey(cookieKey(req))) {+ res.writeHead(302, { location: keyed(path + url.search), 'referrer-policy': 'no-referrer' });+ return res.end();+ }+ return sendEditor(res, editorDir, path);+ }authorize(req);const parts = path.slice('/api/'.length).split('/').map(decodeURIComponent);@@ -247,6 +264,21 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowsethrow new HttpError(501, /** @type {Error} */ (e).message);}}+ /* Studio's own preferences, the same for every project (prefs.mjs) */+ if (parts[0] === 'prefs' && parts.length === 1) {+ if (req.method === 'GET') return json(res, 200, readPrefs());+ if (req.method === 'PATCH') return json(res, 200, writePrefs(await readJson(req)));+ }+ /* the system's file dialog (folder-picker.mjs pickFiles), several at once: { paths } (none: cancelled); 501 when+ this system has none */+ if (parts[0] === 'pick-files' && parts.length === 1 && req.method === 'POST') {+ const { title } = /** @type {{ title?: unknown }} */ (await readJson(req).catch(() => ({})) ?? {});+ try {+ return json(res, 200, { paths: await pickFiles({ title: typeof title === 'string' && title.trim() ? title.trim().slice(0, 120) : 'Choose files', at: null }) });+ } 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'));@@ -442,6 +474,37 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowseconst { path: from } = /** @type {{ path?: string }} */ (await readJson(req));return json(res, 200, { path: await extractAudio(project.path, String(from ?? '')) });}+ /* files or folders of this computer copied in (cloned where the disk can) or linked (files.mjs bringIn): the paths+ given (the desktop app knows a dropped file's), else the person's pick in the system's dialog. { landed } */+ if (rest === 'files/bring' && req.method === 'POST') {+ const { into, mode, paths, folder, title } = /** @type {{ into?: unknown, mode?: unknown, paths?: unknown, folder?: unknown, title?: unknown }} */ (await readJson(req));+ const how = mode === 'link' ? 'link' : 'copy';+ const ask = { title: typeof title === 'string' && title.trim() ? title.trim().slice(0, 120) : 'Choose', at: null };+ const picked = Array.isArray(paths) ? paths.map(String)+ : await (folder === true ? pickFolder(ask).then((p) => (p ? [p] : [])) : pickFiles(ask)).catch((e) => { throw new HttpError(501, String(e?.message ?? e)); });+ return json(res, 200, { landed: await bringIn(project.path, String(into ?? 'assets'), picked, how) });+ }+ /* a link pointed somewhere else (files.mjs relink): the path given, else the person's pick. { path } (null: cancelled) */+ if (rest === 'files/relink' && req.method === 'POST') {+ const { path: rel, to, folder, title } = /** @type {{ path?: unknown, to?: unknown, folder?: unknown, title?: unknown }} */ (await readJson(req));+ const ask = { title: typeof title === 'string' && title.trim() ? title.trim().slice(0, 120) : 'Choose', at: null };+ const where = typeof to === 'string' ? to+ : await (folder === true ? pickFolder(ask) : pickFiles(ask).then((p) => p[0] ?? null)).catch((e) => { throw new HttpError(501, String(e?.message ?? e)); });+ return json(res, 200, { path: where ? await relink(project.path, String(rel ?? ''), where) : null });+ }+ /* the proxies the preview plays heavy footage from (proxies.mjs), asked for when not made yet: each heavy video's+ state. Off: none */+ if (rest === 'proxies' && req.method === 'POST') {+ const { proxies } = readPrefs();+ if (!proxies.on) return json(res, 200, { on: false, height: proxies.height, states: {} });+ const videos = (await listFiles(project.path)).files.filter((f) => f.kind === 'video').map((f) => f.path);+ return json(res, 200, { on: true, height: proxies.height, states: await ensureProxies(project.path, videos, proxies.height) });+ }+ /* what a link leads to copied into the project in its place (files.mjs collect) */+ if (rest === 'files/collect' && req.method === 'POST') {+ const { path: rel } = /** @type {{ path?: unknown }} */ (await readJson(req));+ return json(res, 200, { path: await collect(project.path, String(rel ?? '')) });+ }/* a video's frame made a still beside it (files.mjs freezeFrame): the timeline's freeze frame */if (rest === 'files/still' && req.method === 'POST') {const { path: from, ms } = /** @type {{ path?: string, ms?: number }} */ (await readJson(req));@@ -521,7 +584,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowsehow many subtitle cues the film has (the subtitle choices need some), and how big the project and its parts are */if (rest === 'exports') {if (req.method === 'GET') {- return json(res, 200, { exports: exports.list(project.id), folder: exportsRoot(), can: await exportCapabilities(), subtitles: await exports.subtitles(project.path), project: await projectSizes(project.path) });+ return json(res, 200, { exports: exports.list(project.id), folder: exportsRoot(), can: await exportCapabilities(), drafts: draftApps(), subtitles: await exports.subtitles(project.path), project: await projectSizes(project.path) });}if (req.method === 'POST') {exportRoots.set(project.id, project.path);@@ -557,9 +620,9 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse}/* a file or folder of the project, shown where it is on the person's computer */if (rest === 'reveal' && req.method === 'POST') {- const { path: rel } = /** @type {{ path?: string }} */ (await readJson(req));- /* no path: the project's own folder */- const abs = rel ? inside(project.path, String(rel)) : project.path;+ const { path: rel, original } = /** @type {{ path?: string, original?: boolean }} */ (await readJson(req));+ /* no path: the project's own folder; `original`: where a linked file is kept */+ const abs = !rel ? project.path : original === true ? realpathSync(readable(project.path, String(rel))) : readable(project.path, String(rel));if (!existsSync(abs)) throw new HttpError(404, 'that is not there any more');reveal(abs);return json(res, 200, {});@@ -690,7 +753,7 @@ const EDITOR_DIR = fileURLToPath(new URL('../ui/dist/', import.meta.url));const TYPES = { '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2', '.ico': 'image/x-icon' };/** The editor's files: its assets as they are (named by their content, so kept for good), any other path its page. */-function sendEditor(/** @type {Res} */ res, /** @type {string} */ dir, /** @type {string} */ path) {+function sendEditor(/** @type {Res} */ res, /** @type {string} */ dir, /** @type {string} */ path, /** @type {Record<string, string | string[]>} */ headers = {}) {const root = dir.endsWith(sep) ? dir : dir + sep;if (path.startsWith('/assets/')) {const file = normalize(join(root, path));@@ -702,7 +765,8 @@ function sendEditor(/** @type {Res} */ res, /** @type {string} */ dir, /** @typereturn;}const page = join(root, 'index.html');- res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });+ /* no referrer: the page's address holds the key, and a link it opens must not carry it to another site */+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', ...headers });res.end(existsSync(page) ? readFileSync(page) : '<!doctype html><meta charset="utf-8"><title>OpenFilm Studio</title><p>The editor is not built: run <code>npm run build:ui</code>.</p>');}diff --git a/packages/openfilm/studio/server/server.test.mjs b/packages/openfilm/studio/server/server.test.mjsindex 322fe57..56aefb6 100644--- a/packages/openfilm/studio/server/server.test.mjs+++ b/packages/openfilm/studio/server/server.test.mjs@@ -1,6 +1,6 @@import { test, before, after } from 'node:test';import assert from 'node:assert/strict';-import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { execFileSync } from 'node:child_process';@@ -41,13 +41,13 @@ function collect(path, until) {});}-test('the API needs the key; /open sets it as a cookie and goes where it was asked', async () => {+test('the API needs the key; /open sets it as a cookie and goes where it was asked, the key kept in the address', async () => {assert.equal((await api('/api/projects', { key: null })).status, 401);assert.equal((await api('/api/health', { key: null })).status, 200);assert.equal((await api(`/open?key=wrong`, { key: null })).status, 403);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');+ assert.equal(res.headers.get('location'), `/projects/x?key=${studio.key}`);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 */@@ -62,6 +62,21 @@ test('the API needs the key; /open sets it as a cookie and goes where it was askassert.equal(write.status, 403);});+test('a page\'s address with the key signs a browser in (a copied address opens anywhere); one signed in gets the key in its address', async () => {+ const page = await api(`/projects/x?key=${studio.key}`, { key: null });+ assert.equal(page.status, 200);+ assert.equal(page.headers.get('referrer-policy'), 'no-referrer');+ const [cookie] = page.headers.getSetCookie();+ assert.equal((await api('/api/projects', { key: null, headers: { cookie: cookie.split(';')[0] } })).status, 200);+ /* signed in, an address without the key (typed, or from before) is sent to the one with it */+ const bare = await api('/projects/x?t=2', { key: null, headers: { cookie: cookie.split(';')[0] } });+ assert.equal(bare.status, 302);+ assert.equal(bare.headers.get('location'), `/projects/x?t=2&key=${studio.key}`);+ /* not signed in and no key: the page, which says how to get in; a wrong key signs nothing in */+ assert.equal((await api('/projects/x', { key: null })).status, 200);+ assert.deepEqual((await api('/projects/x?key=wrong', { key: null })).headers.getSetCookie(), []);+});+test('openfilm open: with no editor page, the person\'s browser gets the address after the fallback', async () => {assert.equal((await api('/api/open', { method: 'POST', body: { path: 'Launch', fallback: 0 } })).status, 400, 'a relative folder would be Studio\'s own, not the caller\'s');const res = await api('/api/open', { method: 'POST', body: { path: join(scratch, 'Launch'), fallback: 0.05 } });@@ -180,6 +195,50 @@ test('rename renames the folder; delete moves it to the Trash and off the list',assert.ok(readdirSync(process.env.OPENFILM_TRASH_DIR).some((n) => n.startsWith('Final')));});+test('the preview plays heavy footage from its proxy once made; what the file is (film-facts), an export and proxies off read the original', { skip: !(() => { try { execFileSync('ffmpeg', ['-version'], { stdio: 'ignore' }); return true; } catch { return false; } })() && 'no ffmpeg' }, async () => {+ const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Proxied') } })).json();+ mkdirSync(join(project.path, 'assets'), { recursive: true });+ const big = join(project.path, 'assets', 'big.mp4');+ execFileSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'testsrc=size=2560x1440:rate=25:duration=1', '-pix_fmt', 'yuv420p', big]);+ assert.deepEqual(await (await api('/api/prefs')).json(), { proxies: { on: true, height: 720 } });+ let answer;+ for (const end = Date.now() + 30_000; answer?.states?.['assets/big.mp4']?.state !== 'ready' && Date.now() < end;) {+ answer = await (await api(`/api/projects/${project.id}/proxies`, { method: 'POST', body: {} })).json();+ if (answer.states['assets/big.mp4']?.state !== 'ready') await new Promise((r) => setTimeout(r, 150));+ }+ assert.deepEqual(answer, { on: true, height: 720, states: { 'assets/big.mp4': { state: 'ready' } } });+ const { folder } = await (await api(`/api/projects/${project.id}`)).json();+ const size = async (q = '') => (await (await fetch(`${folder}assets/big.mp4${q}`)).arrayBuffer()).byteLength;+ const played = await size();+ assert.ok(played > 0 && played !== statSync(big).size, 'the proxy');+ assert.equal(await size('?film-facts=1'), statSync(big).size, 'what the file is: the file');+ /* off: the original, and no proxy asked for */+ assert.deepEqual(await (await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: false } } })).json(), { proxies: { on: false, height: 720 } });+ assert.equal(await size(), statSync(big).size);+ assert.deepEqual((await (await api(`/api/projects/${project.id}/proxies`, { method: 'POST', body: {} })).json()).states, {});+ await api('/api/prefs', { method: 'PATCH', body: { proxies: { on: true } } });+});++test('media linked in the media pane is served to the film; a link a project brings from elsewhere is not', { skip: process.platform === 'win32' && 'links need Developer Mode on Windows' }, async () => {+ const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Linked') } })).json();+ const nas = mkdtempSync(join(tmpdir(), 'of-nas-'));+ writeFileSync(join(nas, 'take.wav'), 'footage');+ writeFileSync(join(nas, 'secret.wav'), 'theirs');+ mkdirSync(join(project.path, 'assets'), { recursive: true });+ symlinkSync(join(nas, 'secret.wav'), join(project.path, 'assets', 'secret.wav'));+ const res = await api(`/api/projects/${project.id}/files/bring`, { method: 'POST', body: { into: 'assets', mode: 'link', paths: [join(nas, 'take.wav')] } });+ assert.deepEqual((await res.json()).landed, ['assets/take.wav']);+ const { folder } = await (await api(`/api/projects/${project.id}`)).json();+ assert.equal(await (await fetch(`${folder}assets/take.wav`)).text(), 'footage');+ assert.equal((await fetch(`${folder}assets/secret.wav`)).status, 404);+ const listed = await (await api(`/api/projects/${project.id}/files`)).json();+ assert.deepEqual(listed.links['assets/take.wav'], { to: join(realpathSync(nas), 'take.wav') });+ assert.equal(listed.links['assets/secret.wav'].missing, true);+ /* copied in its place: the project's own file */+ await api(`/api/projects/${project.id}/files/collect`, { method: 'POST', body: { path: 'assets/take.wav' } });+ assert.deepEqual((await (await api(`/api/projects/${project.id}/files`)).json()).links['assets/take.wav'], undefined);+});+test('the film origin serves a project\'s files, with ranges, never .film/, and pages get the film clock', async () => {const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Pages') } })).json();writeFileSync(join(project.path, 'scene.html'), '<!doctype html><html><head><title>x</title><script>window.mine=1</script></head></html>');diff --git a/packages/openfilm/studio/server/stage.js b/packages/openfilm/studio/server/stage.jsindex 4534086..367a19f 100644--- a/packages/openfilm/studio/server/stage.js+++ b/packages/openfilm/studio/server/stage.js@@ -87,7 +87,7 @@for (const c of shown()) {if (pictures && c.kind === 'page') continue;const p = matrixOf(c).inverse().transformPoint(new DOMPoint(x, y));- if (p.x >= 0 && p.y >= 0 && p.x <= c.w && p.y <= c.h) return c;+ if (p.x >= 0 && p.y >= 0 && p.x <= c.w && p.y <= c.h && shownAt(c.el, p.x, p.y, c.w, c.h)) return c;}return null;};@@ -149,8 +149,10 @@/* an icon beside the words (a badge's ✓, a button's arrow) does not stop them being the element's text: its ownwords are typed in place, and the icon stays (a text override changes the element's own words only) */const ICON = new Set(['svg', 'img']);+ /** Words alone, or lines between <br>s: a `text` override changes all of them, a <br> at each line break. */+ const onlyBreaks = (el) => [...el.children].every((ch) => ch.localName === 'br');const textOf = (el) => {- if (el.childElementCount === 0) return stageText(el);+ if (onlyBreaks(el)) return stageText(el);if (![...el.children].every((c) => INLINE.has(c.tagName) || ICON.has(c.localName))) return '';return ownWords(el);};@@ -165,7 +167,12 @@const paints = (cs) => !transparent(cs.backgroundColor)|| (cs.backgroundImage && cs.backgroundImage !== 'none')|| (Number.parseFloat(cs.borderTopWidth) > 0 && !transparent(cs.borderTopColor))- || (cs.boxShadow && cs.boxShadow !== 'none');+ || (cs.boxShadow && cs.boxShadow !== 'none')+ || (Number.parseFloat(cs.outlineWidth) > 0 && cs.outlineStyle !== 'none' && !transparent(cs.outlineColor))+ || (cs.backdropFilter && cs.backdropFilter !== 'none');+ /** Whether the person changed how it looks in Studio (an override's style is written with priority): theirs to+ select again, though it paints nothing now (its fill taken off) */+ const restyled = (el) => [...el.style].some((p) => el.style.getPropertyPriority(p) === 'important');/** text, image, shape or box; null for an empty shell (a click there goes to what is under it). */const kindOf = (el) => {@@ -173,7 +180,7 @@const byTag = tagKind(el.localName.toLowerCase());if (byTag) return byTag;if (el.namespaceURI !== SVG_NS && textOf(el)) return 'text';- return paints(css(el)) ? 'box' : null;+ return paints(css(el)) || restyled(el) ? 'box' : null;};const angleDeg = (raw) => {@@ -259,6 +266,258 @@const dy = y - f.cy;return Math.abs(dx * Math.cos(rad) - dy * Math.sin(rad)) <= f.w / 2 + 0.5 && Math.abs(dx * Math.sin(rad) + dy * Math.cos(rad)) <= f.h / 2 + 0.5;};+ /* ── what a mask or a crop cuts away: nothing is found there (as in Photoshop and Figma) ── */+ /*+ * A point is tested against the box's `clip-path` (inset, circle, ellipse, polygon) and its `mask-image`, drawn+ * small on a canvas the way CSS draws it (linear and radial gradients, inline SVG, `mask-composite`) and read at the+ * point. A mask this cannot draw (a picture file, a repeating gradient, a size of its own) leaves the box whole.+ */+ const MASK_SIDE = 96;+ const masks = new Map();+ const svgs = new Map();+ /** A list's top-level parts: commas inside parentheses and quotes stay. */+ const splitTop = (v, sep = ',') => {+ const out = [];+ let depth = 0;+ let quote = '';+ let from = 0;+ for (let i = 0; i < v.length; i++) {+ const ch = v[i];+ if (quote) { if (ch === quote && v[i - 1] !== '\\') quote = ''; continue; }+ if (ch === '"' || ch === "'") quote = ch;+ else if (ch === '(') depth++;+ else if (ch === ')') depth--;+ else if (depth === 0 && (sep === ' ' ? /\s/.test(ch) : ch === sep)) { out.push(v.slice(from, i).trim()); from = i + 1; }+ }+ out.push(v.slice(from).trim());+ return out.filter(Boolean);+ };+ /** A length or % (of `of`), else NaN. */+ const lengthIn = (v, of) => {+ const m = /^(-?\d*\.?\d+(?:e-?\d+)?)(px|%)?$/.exec(v ?? '');+ if (!m) return NaN;+ return m[2] === '%' ? (Number(m[1]) / 100) * of : Number(m[1]);+ };+ const isColor = (v) => /^(rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(|^#|^(transparent|black|white|currentcolor)\b/i.test(v);+ /** Color stops at their positions along a line `L` long: missing positions spread as CSS does; hints dropped. */+ const stopsOf = (parts, L) => {+ const stops = [];+ for (const p of parts) {+ const words = splitTop(p, ' ');+ if (!words.length || !isColor(words[0])) continue;+ if (words.length === 1) stops.push({ color: words[0], at: NaN });+ for (const w of words.slice(1)) stops.push({ color: words[0], at: lengthIn(w, L) / L });+ }+ if (stops.length < 2) return null;+ if (Number.isNaN(stops[0].at)) stops[0].at = 0;+ if (Number.isNaN(stops[stops.length - 1].at)) stops[stops.length - 1].at = 1;+ for (let i = 1; i < stops.length; i++) {+ if (Number.isNaN(stops[i].at)) {+ let j = i;+ while (Number.isNaN(stops[j].at)) j++;+ for (let k = i; k < j; k++) stops[k].at = stops[i - 1].at + ((stops[j].at - stops[i - 1].at) * (k - i + 1)) / (j - i + 1);+ }+ stops[i].at = Math.max(stops[i].at, stops[i - 1].at);+ }+ return stops;+ };+ const addStops = (g, stops, lo, hi) => { for (const s of stops) g.addColorStop(Math.min(1, Math.max(0, (s.at - lo) / (hi - lo || 1))), s.color); };+ const ANGLES = { top: 0, right: 90, bottom: 180, left: 270 };+ const angleOf = (v, W, H) => {+ const m = /^(-?\d*\.?\d+)(deg|turn|rad|grad)$/.exec(v);+ if (m) return Number(m[1]) * { deg: 1, turn: 360, rad: 180 / Math.PI, grad: 0.9 }[m[2]];+ const to = /^to\s+(.+)$/.exec(v)?.[1]?.split(/\s+/);+ if (!to) return null;+ if (to.length === 1) return ANGLES[to[0]] ?? null;+ const sx = to.includes('right') ? 1 : -1;+ const sy = to.includes('bottom') ? 1 : -1;+ return (Math.atan2(sx * H, -sy * W) * 180) / Math.PI;+ };+ /** One mask layer drawn on `ctx` (W × H): false when it cannot be, null while its picture loads. */+ const drawLayer = (ctx, layer, W, H) => {+ const fn = /^([a-z-]+)\((.*)\)$/s.exec(layer);+ if (!fn) return layer === 'none' ? true : false;+ const [, name, body] = fn;+ if (name === 'url') {+ const src = body.trim().replace(/^(['"])(.*)\1$/s, '$2');+ if (!src.startsWith('data:image/svg+xml')) return false;+ let img = svgs.get(src);+ if (!img) { img = new Image(); img.src = src; svgs.set(src, img); }+ if (!img.complete) return null;+ if (!img.naturalWidth && !img.naturalHeight && img.width === 0) return false;+ ctx.drawImage(img, 0, 0, W, H);+ return true;+ }+ const parts = splitTop(body);+ if (name === 'linear-gradient') {+ let deg = 180;+ if (!isColor(parts[0])) { const a = angleOf(parts.shift(), W, H); if (a == null) return false; deg = a; }+ const r = (deg * Math.PI) / 180;+ const dx = Math.sin(r);+ const dy = -Math.cos(r);+ const L = Math.abs(W * dx) + Math.abs(H * dy);+ const stops = stopsOf(parts, L);+ if (!stops) return false;+ const lo = Math.min(0, stops[0].at);+ const hi = Math.max(1, stops[stops.length - 1].at);+ const x0 = W / 2 - (dx * L) / 2;+ const y0 = H / 2 - (dy * L) / 2;+ const g = ctx.createLinearGradient(x0 + dx * L * lo, y0 + dy * L * lo, x0 + dx * L * hi, y0 + dy * L * hi);+ addStops(g, stops, lo, hi);+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, W, H);+ return true;+ }+ if (name === 'radial-gradient') {+ let shape = 'ellipse';+ let size = 'farthest-corner';+ let cx = W / 2;+ let cy = H / 2;+ let rx = NaN;+ let ry = NaN;+ if (!isColor(parts[0])) {+ const [before, after] = parts.shift().split(/\s*\bat\b\s*/);+ if (after) {+ const pos = after.split(/\s+/);+ const KEY = { left: 0, top: 0, center: 50, right: 100, bottom: 100 };+ const ax = (w, of) => (w in KEY ? (KEY[w] / 100) * of : lengthIn(w, of));+ const [px, py = 'center'] = pos[0] === 'top' || pos[0] === 'bottom' ? [pos[1] ?? 'center', pos[0]] : pos;+ cx = ax(px, W);+ cy = ax(py, H);+ }+ const words = (before ?? '').split(/\s+/).filter(Boolean);+ const lens = words.filter((w) => !/^(circle|ellipse|closest-side|farthest-side|closest-corner|farthest-corner)$/.test(w));+ if (words.includes('circle') || lens.length === 1) shape = 'circle';+ size = words.find((w) => /-(side|corner)$/.test(w)) ?? size;+ if (lens.length === 1) { rx = lengthIn(lens[0], W); ry = rx; }+ if (lens.length === 2) { rx = lengthIn(lens[0], W); ry = lengthIn(lens[1], H); }+ }+ if (Number.isNaN(cx) || Number.isNaN(cy)) return false;+ if (Number.isNaN(rx)) {+ const sides = [cx, W - cx, cy, H - cy];+ const near = size.startsWith('closest');+ const pick = near ? Math.min : Math.max;+ if (shape === 'circle') {+ rx = size.endsWith('side') ? pick(...sides) : pick(...[[0, 0], [W, 0], [0, H], [W, H]].map(([x, y]) => Math.hypot(x - cx, y - cy)));+ ry = rx;+ } else {+ rx = pick(sides[0], sides[1]);+ ry = pick(sides[2], sides[3]);+ if (size.endsWith('corner')) { rx *= Math.SQRT2; ry *= Math.SQRT2; }+ }+ }+ if (!(rx > 0 && ry > 0)) return false;+ const stops = stopsOf(parts, rx);+ if (!stops) return false;+ const hi = Math.max(1, stops[stops.length - 1].at);+ ctx.save();+ ctx.translate(cx, cy);+ ctx.scale(1, ry / rx);+ const g = ctx.createRadialGradient(0, 0, 0, 0, 0, rx * hi);+ addStops(g, stops.map((s) => ({ ...s, at: Math.max(0, s.at) })), 0, hi);+ ctx.fillStyle = g;+ ctx.fillRect(-cx, -cy * (rx / ry), W, H * (rx / ry));+ ctx.restore();+ return true;+ }+ return false;+ };+ const COMPOSITE = { add: 'source-over', subtract: 'source-out', intersect: 'destination-in', exclude: 'xor' };+ /** The mask's alpha all over a W × H box, small: null when it cannot be drawn (or not yet). */+ const maskPixels = (image, composite, W, H) => {+ const key = `${image}|${composite}|${Math.round(W)}x${Math.round(H)}`;+ if (masks.has(key)) return masks.get(key);+ const k = MASK_SIDE / Math.max(W, H);+ const w = Math.max(1, Math.round(W * k));+ const h = Math.max(1, Math.round(H * k));+ const layers = splitTop(image);+ const ops = splitTop(composite || 'add');+ const out = document.createElement('canvas');+ out.width = w;+ out.height = h;+ const octx = out.getContext('2d', { willReadFrequently: true });+ if (masks.size > 64) masks.clear();+ for (let i = layers.length - 1; i >= 0; i--) {+ const one = document.createElement('canvas');+ one.width = w;+ one.height = h;+ const ctx = one.getContext('2d');+ ctx.scale(w / W, h / H);+ const drawn = drawLayer(ctx, layers[i], W, H);+ /* a picture still loading is tried again next time; one this cannot draw leaves the box whole */+ if (drawn === null) return null;+ if (drawn === false) { masks.set(key, null); return null; }+ octx.globalCompositeOperation = i === layers.length - 1 ? 'source-over' : COMPOSITE[ops[i % ops.length]] ?? 'source-over';+ octx.drawImage(one, 0, 0);+ }+ const value = { w, h, k: [w / W, h / H], data: octx.getImageData(0, 0, w, h).data };+ masks.set(key, value);+ return value;+ };+ /** Whether `clip-path` keeps point (x, y) of a W × H box (a shape this does not read keeps all of it). */+ const clipKeeps = (clip, x, y, W, H) => {+ const fn = /^(inset|circle|ellipse|polygon)\((.*)\)/s.exec(clip ?? '');+ if (!fn) return true;+ const [, name, body] = fn;+ if (name === 'inset') {+ const v = body.split(/\s+round\s+/)[0].trim().split(/\s+/);+ const [t, r = t, b = t, l = r] = v;+ return x >= lengthIn(l, W) && x <= W - lengthIn(r, W) && y >= lengthIn(t, H) && y <= H - lengthIn(b, H);+ }+ if (name === 'polygon') {+ const pts = splitTop(body).filter((p) => !/^(nonzero|evenodd)$/.test(p)).map((p) => p.split(/\s+/)).map(([px, py]) => [lengthIn(px, W), lengthIn(py, H)]);+ let inside = false;+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {+ const [xi, yi] = pts[i];+ const [xj, yj] = pts[j];+ if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;+ }+ return inside;+ }+ const [size, pos] = body.split(/\s*\bat\b\s*/);+ const [px = '50%', py = '50%'] = (pos ?? '').split(/\s+/).filter(Boolean).map((w) => ({ left: '0%', top: '0%', center: '50%', right: '100%', bottom: '100%' }[w] ?? w));+ const cx = lengthIn(px, W);+ const cy = lengthIn(py, H);+ const lens = (size ?? '').split(/\s+/).filter((w) => w && !/side$/.test(w));+ const rx = name === 'circle' ? lengthIn(lens[0] ?? '', Math.hypot(W, H) / Math.SQRT2) : lengthIn(lens[0] ?? '', W);+ const ry = name === 'circle' ? rx : lengthIn(lens[1] ?? '', H);+ if (!(rx > 0 && ry > 0)) return true;+ return ((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 <= 1;+ };+ /** Whether point (x, y) of element `el`'s W × H box is drawn: not cut away by its crop or mask. */+ const shownAt = (el, x, y, W, H) => {+ const s = view(el).getComputedStyle(el);+ if (!clipKeeps(s.clipPath, x, y, W, H)) return false;+ const image = s.maskImage || s.webkitMaskImage;+ if (!image || image === 'none') return true;+ const px = maskPixels(image, s.maskComposite || 'add', W, H);+ if (!px) return true;+ const i = Math.min(px.w - 1, Math.max(0, Math.floor(x * px.k[0])));+ const j = Math.min(px.h - 1, Math.max(0, Math.floor(y * px.k[1])));+ return px.data[(j * px.w + i) * 4 + 3] > 64;+ };+ /**+ * Whether a page's point (page px) is cut away from `el`: by its own crop or mask, or by one of its parents' (theirs,+ * or a parent that clips what overflows it).+ */+ const cutAway = (el, x, y) => {+ const root = el.ownerDocument.documentElement;+ for (let node = el; node && node !== root && node !== el.ownerDocument.body; node = node.parentElement) {+ const s = css(node);+ const clips = node !== el && s.overflow !== 'visible';+ if (!clips && s.clipPath === 'none' && (!s.maskImage || s.maskImage === 'none') && (!s.webkitMaskImage || s.webkitMaskImage === 'none')) continue;+ const f = frameOf(node);+ if (!(f.w > 0 && f.h > 0)) continue;+ const rad = (-f.r * Math.PI) / 180;+ const dx = x - f.cx;+ const dy = y - f.cy;+ const lx = dx * Math.cos(rad) - dy * Math.sin(rad) + f.w / 2;+ const ly = dx * Math.sin(rad) + dy * Math.cos(rad) + f.h / 2;+ if (clips && (lx < 0 || ly < 0 || lx > f.w || ly > f.h)) return true;+ if (!shownAt(node, lx, ly, f.w, f.h)) return true;+ }+ return false;+ };/** Override px → page px: `translate` is in the parent's coordinates, so the parent's own scale counts. */const localScale = (el) => {for (let p = el.parentElement; p; p = p.parentElement) {@@ -392,10 +651,16 @@/* styles the inspector shows per kind (computed: a page states none as source keys) */const TEXT_STYLE_KEYS = ['fontFamily', 'fontWeight', 'fontStyle', 'fontSize', 'lineHeight', 'letterSpacing', 'textAlign', 'color', 'opacity'];const SVG_TEXT_STYLE_KEYS = ['fontFamily', 'fontWeight', 'fontStyle', 'fontSize', 'letterSpacing', 'fill', 'opacity'];- const KIND_STYLE_KEYS = { text: [...TEXT_STYLE_KEYS, 'textTransform'], image: ['opacity', 'borderRadius', 'objectFit', 'objectPosition', 'clipPath'], shape: ['opacity'], box: ['backgroundColor', 'borderRadius', 'opacity', 'clipPath'] };- /* the look every kind shows (blend, adjustments and shadow, stroke, faded edges): as the page draws it, its CSS's or its own */- const LOOK_STYLE_KEYS = ['mixBlendMode', 'filter', 'border', 'maskImage', 'maskComposite'];- const LOOK_KEYS = new Set([...LOOK_STYLE_KEYS, 'textTransform', 'objectPosition', 'clipPath']);+ const KIND_STYLE_KEYS = {+ text: [...TEXT_STYLE_KEYS, 'textTransform', 'textDecorationLine'],+ image: ['opacity', 'borderRadius', 'objectFit', 'objectPosition', 'clipPath'],+ shape: ['opacity', 'fill'],+ box: ['backgroundColor', 'borderRadius', 'opacity', 'clipPath', 'boxShadow'],+ };+ /* the look every kind shows (blend, adjustments and shadow, stroke, faded edges, what is behind blurred): as the+ page draws it, its CSS's or its own */+ const LOOK_STYLE_KEYS = ['mixBlendMode', 'filter', 'border', 'outline', 'outlineOffset', 'backdropFilter', 'maskImage', 'maskComposite'];+ const LOOK_KEYS = new Set([...LOOK_STYLE_KEYS, 'textTransform', 'textDecorationLine', 'objectPosition', 'clipPath', 'boxShadow']);const UNITLESS = new Set(['opacity', 'fontWeight', 'lineHeight', 'zIndex', 'flex', 'flexGrow', 'flexShrink', 'order', 'zoom', 'scale', 'fillOpacity', 'strokeOpacity', 'strokeMiterlimit']);const isColorKey = (key) => /^(color|fill|stroke|background|backgroundColor|borderColor|outlineColor|stopColor)$/.test(key) || /Color$/.test(key);const pxNumber = (value) => {@@ -431,7 +696,12 @@if (key === 'fontFamily') return own(el, 'font-family') || cs.fontFamily || undefined;if (key === 'fontStyle') { const v = own(el, 'font-style') || cs.fontStyle; return v && v !== 'normal' ? v : undefined; }if (key === 'textAlign') { const v = own(el, 'text-align') || cs.textAlign; return v && v !== 'start' ? v : undefined; }- if (LOOK_KEYS.has(key)) { const v = own(el, name) || cs.getPropertyValue(name); return v && !/^(none|normal|add|50% 50%)$/.test(v) && !/^0px none\b/.test(v) ? v : undefined; }+ if (LOOK_KEYS.has(key)) {+ const v = own(el, name) || cs.getPropertyValue(name);+ /* an outline is computed color first: "rgb(0, 0, 0) none 0px" is none */+ if (key === 'outline' && /\bnone\b/.test(v)) return undefined;+ return v && !/^(none|normal|add|50% 50%)$/.test(v) && !/^0px none\b/.test(v) ? v : undefined;+ }if (UNITLESS.has(key)) {const mine = own(el, name);const n = Number(mine || cs.getPropertyValue(name));@@ -446,13 +716,16 @@const cs = css(el);let keys = [...(kind === 'text' && isSvgText(el) ? SVG_TEXT_STYLE_KEYS : KIND_STYLE_KEYS[kind]), ...LOOK_STYLE_KEYS];/* a line with its own fill (a badge, a tag) is a box too */- if (kind === 'text' && paints(cs)) keys.push('backgroundColor', 'borderRadius');+ if (kind === 'text' && paints(cs)) keys.push('backgroundColor', 'borderRadius', 'boxShadow');keys = [...new Set(keys)];for (const key of keys) {if (key === 'backgroundColor' && transparent(cs.backgroundColor)) continue;if (key === 'objectFit') { const fit = own(el, 'object-fit') || cs.objectFit; if (fit) style[key] = fit; continue; }if (key === 'borderRadius') {const mine = own(el, 'border-radius');+ /* four corners not alike: all four, as the shorthand writes them (top left, top right, bottom right, left) */+ const corners = [cs.borderTopLeftRadius, cs.borderTopRightRadius, cs.borderBottomRightRadius, cs.borderBottomLeftRadius];+ if (!mine && new Set(corners).size > 1 && corners.every((c) => pxNumber(c) != null)) { style[key] = corners.join(' '); continue; }const n = pxNumber(mine || cs.borderTopLeftRadius);if (n != null) style[key] = n; else if (mine) style[key] = mine;continue;@@ -501,6 +774,7 @@const kind = kindOf(el);if (!kind || invisible(el)) return;if (!includeLocked && lockedOf(c, el)) return;+ if (cutAway(el, x, y)) return;hits.push({ el, kind, rect, frame, area: frame.w * frame.h, order });});return hits.sort((a, b) => a.area - b.area || b.order - a.order);@@ -717,7 +991,7 @@if (kept) draft(c, edit.target, { text: value });post({ type: 'stage-event', event: 'text', handle: edit.handle, commit: Boolean(kept), ...(kept ? { value, before: edit.before } : {}) });};- const startText = ({ handle, multiline }) => {+ const startText = ({ handle }) => {const el = nodeOf(handle);const c = el && clipOfNode(el);if (!el || !c || editing) return false;@@ -726,7 +1000,8 @@const walker = doc.createTreeWalker(el, 4);for (let n = walker.nextNode(); n; n = walker.nextNode()) data.set(n, n.data);const attrs = { contentEditable: el.getAttribute('contenteditable'), style: el.getAttribute('style'), spellcheck: el.getAttribute('spellcheck') };- const overlay = isSvgText(el) || el.childElementCount > 0;+ /* typed in place, lines and all, where it can be: the line keeps its own width and wraps as it does */+ const overlay = isSvgText(el) || !onlyBreaks(el);const host = overlay ? openOverlay(el) : el;if (overlay) el.style.setProperty('visibility', 'hidden', 'important');try { host.contentEditable = 'plaintext-only'; } catch { host.contentEditable = 'true'; }@@ -735,11 +1010,12 @@for (const [name, value] of [['user-select', 'text'], ['-webkit-user-select', 'text'], ['cursor', 'text'], ['outline', 'none'], ['pointer-events', 'auto'], ['caret-color', BLUE]]) {host.style.setProperty(name, value, 'important');}- const lines = Boolean(multiline) && !overlay;+ /* Shift+Enter breaks the line (where the words can hold one); Enter keeps them, Esc gives them up */+ const lines = !overlay;const onKey = (e) => {e.stopPropagation();if (e.key === 'Escape') { e.preventDefault(); finishText(false); }- else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey || !lines)) { e.preventDefault(); finishText(true); }+ else if (e.key === 'Enter' && !(lines && e.shiftKey)) { e.preventDefault(); finishText(true); }};const onBlur = () => finishText(true);host.addEventListener('keydown', onKey);@@ -767,7 +1043,8 @@if (editing || typing(e.target)) return;const mod = e.metaKey || e.ctrlKey;const k = e.key.toLowerCase();- if ((EDITOR_KEYS.has(e.key) && !mod) || (mod && (k === 'z' || (e.shiftKey && (k === 'h' || k === 'l'))))) e.preventDefault();+ /* ⌘A is the editor's select-all, not the page's text selected */+ if ((EDITOR_KEYS.has(e.key) && !mod) || (mod && (k === 'z' || (k === 'a' && !e.shiftKey && !e.altKey) || (e.shiftKey && (k === 'h' || k === 'l'))))) e.preventDefault();post({ type: 'stage-event', event: 'key', key: e.key, code: e.code, repeat: e.repeat, metaKey: e.metaKey, ctrlKey: e.ctrlKey, shiftKey: e.shiftKey, altKey: e.altKey });};const listening = new WeakSet();diff --git a/packages/openfilm/studio/server/stage.test.mjs b/packages/openfilm/studio/server/stage.test.mjsnew file mode 100644index 0000000..665bdd8--- /dev/null+++ b/packages/openfilm/studio/server/stage.test.mjs@@ -0,0 +1,80 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { launch } from '../../src/host.mjs';++/* the stage script in a page of its own, one page clip on it: asked as the editor asks, from the page's own origin */+const ORIGIN = 'http://stage.test';+const STAGE = readFileSync(new URL('./stage.js', import.meta.url), 'utf8').replace('__EDITOR__', JSON.stringify(ORIGIN));+const PAGE = `<!doctype html><body style="margin:0;background:#000">+<div id="a" style="position:absolute;left:20px;top:20px;width:100px;height:100px;background:#f00"></div>+<div id="b" style="position:absolute;left:150px;top:50px;width:100px;height:100px;background:#0f0">+<div id="c" style="position:absolute;left:80px;top:0;width:100px;height:100px"></div></div></body>`;+const HOST = `<!doctype html><body style="margin:0">+<iframe id="p" style="position:absolute;left:0;top:0;width:400px;height:200px;border:0;visibility:visible" srcdoc="${PAGE.replace(/"/g, '"')}"></iframe>+<script>+ const el = document.getElementById('p');+ const clips = [{ id: 'p', kind: 'page', el, w: 400, h: 200, ti: 0, overrides: [], get win() { return el.contentWindow; } }];+ window.__filmEditor = { stage: { clips: () => clips } };+ window.film = { ready: new Promise((r) => el.addEventListener('load', r)) };+</script>+<script>${STAGE}</script></body>`;++async function stage() {+ const browser = await launch();+ const page = await browser.newPage();+ await page.route(`${ORIGIN}/**`, (route) => route.fulfill({ contentType: 'text/html', body: HOST }));+ await page.goto(`${ORIGIN}/`);+ await page.evaluate(() => window.film.ready);+ const ask = (op, args) => page.evaluate(([op, args]) => new Promise((resolve) => {+ const seq = Math.random();+ addEventListener('message', function on(e) {+ if (e.data?.source !== 'openfilm-film' || e.data.seq !== seq) return;+ removeEventListener('message', on);+ resolve(e.data.result);+ });+ postMessage({ source: 'openfilm-studio', type: 'stage', seq, op, ...args }, '*');+ }), [op, args]);+ const style = (sel, css) => page.evaluate(([sel, css]) => {+ const el = sel === 'clip' ? document.getElementById('p') : document.getElementById('p').contentDocument.querySelector(sel);+ el.style.cssText += css;+ }, [sel, css]);+ const layer = async (x, y) => (await ask('hit', { x, y, detail: true }))?.at ?? null;+ return { browser, ask, style, layer };+}++test('what a mask or a crop cuts away is not found: the clip and its layers', { timeout: 60_000 }, async () => {+ const { browser, ask, style, layer } = await stage();+ try {+ assert.equal(await ask('clipAt', { x: 10, y: 10 }), 'p');+ assert.equal(await layer(30, 30), '#a');++ /* the clip's circle: its corners are not the clip, nor its layers */+ await style('clip', 'mask-image: radial-gradient(25% 50% at 50% 50%, #000 99%, transparent 100%)');+ assert.equal(await ask('clipAt', { x: 10, y: 10 }), null);+ assert.equal(await layer(30, 30), null);+ assert.equal(await ask('clipAt', { x: 200, y: 100 }), 'p');+ assert.equal(await layer(200, 100), '#b');+ assert.equal(await layer(115, 100), '#a');++ /* a crop (clip-path) cuts the same way */+ await style('clip', 'mask-image: none; clip-path: inset(0 50% 0 0)');+ assert.equal(await ask('clipAt', { x: 300, y: 100 }), null);+ assert.equal(await ask('clipAt', { x: 100, y: 100 }), 'p');++ /* a layer's own mask, two layers intersected: only where both show */+ await style('clip', 'clip-path: none');+ await style('#a', 'mask-image: linear-gradient(to right, #000 50%, transparent 50%), linear-gradient(#000 50%, transparent 50%); mask-composite: intersect');+ assert.equal(await layer(40, 40), '#a');+ assert.equal(await layer(100, 40), null);+ assert.equal(await layer(40, 100), null);++ /* a parent that clips what overflows it: its child past its edge is not found there */+ await style('#b', 'overflow: hidden');+ await style('#c', 'background: #00f');+ assert.equal(await layer(240, 100), '#c');+ assert.equal(await layer(300, 100), null);+ } finally {+ await browser.close();+ }+});diff --git a/packages/openfilm/studio/ui/src/App.tsx b/packages/openfilm/studio/ui/src/App.tsxindex 910e6d5..648a82f 100644--- a/packages/openfilm/studio/ui/src/App.tsx+++ b/packages/openfilm/studio/ui/src/App.tsx@@ -12,12 +12,24 @@ import { BrandLoadingScreen } from './components/BrandLoadingScreen';import { ProjectsPopover } from './components/ProjectsLibrary';import { studioHost } from './lib/host';+/**+ * `to` with this page's key in its address (the server puts it there): the address bar is what a person copies, and+ * with the key a copied address opens Studio in any browser on this machine, or in an agent's preview.+ */+const keepKey = (to: string) => {+ const key = new URLSearchParams(location.search).get('key');+ if (!key) return to;+ const at = new URL(to, location.origin);+ at.searchParams.set('key', key);+ return at.pathname + at.search;+};+const projectIn = (path: string) => /^\/projects\/([\w-]+)/.exec(path)?.[1] ?? null;export function App() {const [path, setPath] = useState(location.pathname);const go = (to: string, replace = false) => {- if (to !== location.pathname) (replace ? history.replaceState : history.pushState).call(history, null, '', to);+ if (to !== location.pathname) (replace ? history.replaceState : history.pushState).call(history, null, '', keepKey(to));setPath(to);};diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.tsindex 0945d28..f1f95c4 100644--- a/packages/openfilm/studio/ui/src/api.ts+++ b/packages/openfilm/studio/ui/src/api.ts@@ -32,7 +32,7 @@ export type Op =| { op: 'insert'; clip?: Partial<Clip> & { src: string }; from?: string; at?: number; after?: string; track?: number | { insert: number }; newTrack?: number; link?: string | null }| { op: 'remove'; clip: string }| { op: 'split'; clip: string; at: number; time: [number, number]; restTime: [number, number] }- | { op: 'split'; clip: string; left: Record<string, PropValue>; right: Record<string, PropValue> }+ | { op: 'split'; clip: string; left: Record<string, PropValue>; right: Record<string, PropValue>; rightId?: string }| { op: 'track'; track: number; field: 'locked' | 'hidden' | 'muted'; value: boolean }| { op: 'reorder'; from: number; to: number }| { op: 'props'; edits: PropEdit[] }@@ -74,10 +74,20 @@ async function call<T>(path: string, init: RequestInit & { json?: unknown } = {}const p = (id: string) => `projects/${encodeURIComponent(id)}`;+/** Studio's own preferences, the same for every project (studio/server/prefs.mjs). */+export interface StudioPrefs { proxies: { on: boolean; height: 540 | 720 | 1080 } }+/** Said on the window when they change, for what plays by them (the preview's proxies). */+export const PREFS_EVENT = 'openfilm:prefs';+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),+ prefs: () => call<StudioPrefs>('prefs'),+ setPrefs: (patch: { proxies?: Partial<StudioPrefs['proxies']> }) => call<StudioPrefs>('prefs', { method: 'PATCH', json: patch }).then((prefs) => {+ window.dispatchEvent(new Event(PREFS_EVENT));+ return prefs;+ }),/** the system's folder dialog, opened by Studio (a page in a browser cannot learn a path): the folder, or null whencancelled; 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),diff --git a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx b/packages/openfilm/studio/ui/src/components/FilmInspector.tsxindex 5c0a051..433a611 100644--- a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx@@ -27,7 +27,7 @@ import {parseFilmDocLoc, type FilmOverride,} from '@/lib/film';import { useT } from '@/i18n';-import { wrapDeg } from '@/lib/stage-gesture';+import { groupDragged, wrapDeg, type GroupDrag } from '@/lib/stage-gesture';import {compactScale, isSvgTextTag, scalePair, sourceLocBare,type MgBox, type MgTransform, type NodeOverride, type OverridePivot, type StageElement, type StageElementStyle, type StageGeometry,@@ -40,20 +40,23 @@ import { editsForMoves } from '@/lib/timeline-drag';import { useTimelinePrefs } from '@/lib/timeline-prefs';import { formatTimecode, FRAME_RATES, timecodeFps, useTimecodeFps } from '@/lib/timecode';import { MenuSelect } from './MenuSelect';+import { CANVAS_SIDE, canvasSide } from '@/lib/canvas-fit';import { filmFrameOf, filmFrameRatio, type FilmFrameId } from '@/lib/film-frame';-import { CANVAS_RATIOS, canvasRatioLabel } from './FramePicker';+import { CANVAS_RATIOS, canvasRatioLabel, shaped } 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, SliderField,+ ICON, MIXED, NumField, Row, RotateGlyph, Section, SectionAction, Segmented, SliderField,useTimeUnit, type FieldApply, type Mixed,} from './inspector-fields';import {- AdjustSection, AdvancedSection, AppearanceSection, CropSection, EffectsSection, MaskSection, NEUTRAL, TypographySection, camelOf,+ AdjustSection, AdvancedSection, AppearanceSection, CropSection, EffectsSection, FillSection, MaskSection, NEUTRAL, StrokeSection,+ TypographySection, camelOf,isNeutral, kebabOf, makeLook, rawDeclarations, type Look, type LookRead, type LookSet,} from './inspector-look';import type { MaskSession } from '@/lib/stage-mask';+import type { MaskShape } from '@/lib/clip-mask';import type { FadeMs } from '@/lib/clip-fade';import type { FoundKind } from '@/lib/transitions';@@ -133,6 +136,7 @@ function useCommitBeforeLeaving(): void {export const FilmInspector = React.memo(function FilmInspector({element,clips,+ mainTrack,onEditClips,width,onClose,@@ -153,10 +157,15 @@ export const FilmInspector = React.memo(function FilmInspector({stage,onStartCrop,onEditMask,+ maskAsk,+ onMaskAsked,film,onCanvas,+ onCanvasPreview,+ canvasDraft,layers,onEditLayers,+ onPlaceLayers,locked = false,rate,fades,@@ -165,6 +174,8 @@ export const FilmInspector = React.memo(function FilmInspector({element: StageElement | null;/** The clips selected on the timeline. A layer picked on the picture wins: one selection at a time. */clips?: readonly TimelineBlock[];+ /** The main track's film.html index (timeline-edit mainTrackOf): the magnet acts there alone. */+ mainTrack?: number | null;/** Writes clip properties, through the same queue as dragging on the timeline. Resolves to an error when refused. */onEditClips?: (edits: ClipEdit[]) => Promise<string | null>;/** The pane's width (dragged at the divider beside the viewer). */@@ -206,13 +217,22 @@ export const FilmInspector = React.memo(function FilmInspector({onStartCrop?: () => void;/** The Mask section's "Edit on picture": the mask's handles over the thing in hand (null: none). */onEditMask?: (session: MaskSession | null) => void;+ /** A mask shape picked on the picture for clip `clipLoc`: its Mask section puts it on, then says so. */+ maskAsk?: { shape: MaskShape | 'none'; clipLoc: string; n: number } | null;+ onMaskAsked?: () => void;/** The film when nothing is selected. */film?: FilmSummary | 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;+ /** Show the canvas at a size not kept yet, as its width or height is dragged (null: as it is again). */+ onCanvasPreview?: (size: { w: number; h: number } | null) => void;+ /** That size, while it is shown. */+ canvasDraft?: { w: number; h: number } | null;/** Several layers selected on the picture, and how to write them at once. */layers?: readonly StageElement[];onEditLayers?: (list: LayerEdit[]) => Promise<string | null>;+ /** Several layers' bounds typed: moved or scaled together on the picture (FilmStageControl.placeLayers). */+ onPlaceLayers?: (to: { x?: number; y?: number; w?: number; h?: number }) => void;/** What is selected is on a locked track: shown, not changed (its fields are off, and say why). */locked?: boolean;/** The project's frame rate (the film's panel): its value, whether it was taken from the footage, and a new one. */@@ -275,6 +295,7 @@ export const FilmInspector = React.memo(function FilmInspector({<ClipPanelkey={clip.id}block={clip}+ onMain={mainTrack != null && parseFilmDocLoc(clip.loc ?? '')?.track === mainTrack}geometry={geometry && geometry.kind === 'clip' && geometry.loc === clip.loc ? geometry : null}onEdit={onEditClips}onPreviewClip={onPreviewClip}@@ -283,6 +304,8 @@ export const FilmInspector = React.memo(function FilmInspector({{...(onPreviewLook ? { onPreviewLook } : {})}{...(onStartCrop ? { onStartCrop } : {})}{...(onEditMask ? { onEditMask } : {})}+ {...(maskAsk && maskAsk.clipLoc === clip.loc ? { maskAsk } : {})}+ {...(onMaskAsked ? { onMaskAsked } : {})}badges={film?.badges}stage={stageSize}{...(fades ? { fades } : {})}@@ -299,9 +322,9 @@ export const FilmInspector = React.memo(function FilmInspector({) : transition ? (<TransitionPanel t={t} pick={transition} />) : geometry?.kind === 'group' && geometry.group ? (- <GroupPanel geometry={geometry} group={geometry.group} layers={layers} onEditLayers={onEditLayers} t={t} />+ <GroupPanel geometry={geometry} group={geometry.group} layers={layers} onEditLayers={onEditLayers} {...(onPlaceLayers ? { onPlace: onPlaceLayers } : {})} t={t} />) : (- <FilmPanel t={t} stage={stageSize} film={film ?? null} onCanvas={onCanvas} rate={rate ?? null} />+ <FilmPanel t={t} stage={stageSize} draft={canvasDraft} film={film ?? null} onCanvas={onCanvas} onCanvasPreview={onCanvasPreview} rate={rate ?? null} />)}</div></fieldset>@@ -313,7 +336,6 @@ export const FilmInspector = React.memo(function FilmInspector({/** 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@@ -354,20 +376,25 @@ function RedesignHint({ t, stage }: { t: T; stage: { w: number; h: number } }) {* (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, rate,+ t, stage: kept, draft, film, onCanvas, onCanvasPreview, rate,}: {t: T;stage: { w: number; h: number };+ /** The canvas size shown while W or H is dragged, not kept yet. */+ draft?: { w: number; h: number } | null;film: FilmSummary | null;onCanvas?: (next: FilmFrameId, size?: { w: number; h: number }) => void;+ onCanvasPreview?: (size: { w: number; h: number } | null) => void;rate: { fps: number; fromFootage: boolean; onChange: (fps: number) => void } | null;}) {const canvas = Boolean(onCanvas);+ /* what the picture shows: the size being dragged, else the film's */+ const stage = draft ?? kept;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 preset = CANVAS_RATIOS.find((r) => shaped(stage, filmFrameRatio(r.id, stage)));const setSize = (w: number, h: number) => {- const size = { w: even(w), h: even(h) };- if (size.w === stage.w && size.h === stage.h) return;+ const size = { w, h };+ if (size.w === kept.w && size.h === kept.h) { onCanvasPreview?.(null); return; }onCanvas?.(filmFrameOf(size), size);};const info = (label: string, value: string) => (@@ -389,7 +416,7 @@ function FilmPanel({label={t('inspector.stageShape')}value={preset?.id ?? 'custom'}groups={[- { choices: preset ? [] : [{ value: 'custom', label: `${t('viewer.frameCustom')} · ${stage.w}×${stage.h}` }] },+ { choices: preset ? [] : [{ value: 'custom', label: t('viewer.frameCustom') }] },{ 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)}@@ -397,8 +424,11 @@ function FilmPanel({/>) : 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)} />+ {/* dragged, the canvas changes on the picture as the mark moves; kept when it is let go */}+ <NumField label={t('inspector.width')} prefix="W" value={stage.w} unit="px" step={8} min={CANVAS_SIDE.min} max={CANVAS_SIDE.max} disabled={!canvas}+ onCommit={(w) => setSize(canvasSide(w, kept.h), kept.h)} onPreview={(w) => onCanvasPreview?.({ w: canvasSide(w, kept.h), h: kept.h })} onRevert={() => onCanvasPreview?.(null)} />+ <NumField label={t('inspector.height')} prefix="H" value={stage.h} unit="px" step={8} min={CANVAS_SIDE.min} max={CANVAS_SIDE.max} disabled={!canvas}+ onCommit={(h) => setSize(kept.w, canvasSide(h, kept.w))} onPreview={(h) => onCanvasPreview?.({ w: kept.w, h: canvasSide(h, kept.w) })} onRevert={() => onCanvasPreview?.(null)} /></Row>{/* with clips: the words that ask the agent to lay the film out again for this canvas */}{placed ? <RedesignHint t={t} stage={stage} /> : null}@@ -867,14 +897,8 @@ function LayerPanel({const bgProp = declaredKeys.has('background') ? 'background' : 'background-color';/* text in an SVG (`<text>` / `<tspan>`): no line layout, its color is fill — those sections look different */const svgText = kind === 'text' && isSvgTextTag(element.tag ?? '');- const fill = (prop: string, label: string) => (- <ColorField- label={label}- value={look.common((read) => read(prop) ?? '')}- onPreview={(c) => look.preview(() => ({ [prop]: c }))}- onCommit={(c) => look.commit(() => ({ [prop]: c }))}- />- );+ /* a line with its own fill (a badge, a tag): it has a background and corners, as a box */+ const textFilled = kind === 'text' && !svgText && style.backgroundColor != null;/* the override's own CSS, as declarations: what Advanced shows of it */const overrideCss = Object.entries(overrideStyle).map(([k, v]) => `${kebabOf(k)}: ${typeof v === 'number' && !/opacity|z-index|font-weight|line-height|flex/.test(kebabOf(k)) ? `${v}px` : v}`)@@ -1028,30 +1052,23 @@ function LayerPanel({{...(onEditMask ? { onEditMask } : {})}/>- <AppearanceSection look={look} t={t}>- {kind === 'box' ? fill(bgProp, t('inspector.fill')) : null}- {kind === 'shape' && declaredKeys.has('fill') ? fill('fill', t('inspector.fill')) : null}- {kind === 'text' && !svgText && style.backgroundColor != null ? (- <>- {fill(bgProp, t('inspector.background'))}- <Row>- <NumField- label={t('inspector.radius')}- prefix={<RadiusGlyph />}- value={look.common((read) => Number.parseFloat(read('border-radius') ?? '0') || 0)}- unit="px"- min={0}- onPreview={(n) => look.preview(() => ({ 'border-radius': n > 0 ? `${n}px` : null }))}- onCommit={(n) => look.commit(() => ({ 'border-radius': n > 0 ? `${n}px` : null }))}- onRevert={() => look.revert()}- />- <span />- </Row>- </>- ) : null}- </AppearanceSection>+ {/* Figma's order: appearance, fill, stroke, effects; then the picture's color adjustments */}+ <AppearanceSection look={look} t={t} radius={kind === 'box' || kind === 'image' || textFilled} />+ <FillSection+ look={look}+ t={t}+ fills={[+ ...(kind === 'text' ? [{ prop: svgText ? 'fill' : 'color', label: svgText ? t('inspector.fill') : t('inspector.color') }] : []),+ ...(textFilled ? [{ prop: bgProp, label: t('inspector.background'), removable: true }] : []),+ ...(kind === 'box' && style.backgroundColor != null ? [{ prop: bgProp, label: t('inspector.fill'), removable: true }] : []),+ /* a shape's fill, as its CSS or its own fill="" attribute paints it */+ ...(kind === 'shape' && (style.fill != null || declaredKeys.has('fill')) ? [{ prop: 'fill', label: t('inspector.fill') }] : []),+ ]}+ add={kind === 'box' && style.backgroundColor == null ? { prop: bgProp, label: t('inspector.fill'), value: '#ffffff' } : null}+ />+ {kind === 'shape' || svgText ? null : <StrokeSection look={look} t={t} />}+ <EffectsSection look={look} t={t} inner={kind === 'box' || textFilled} /><AdjustSection look={look} t={t} />- <EffectsSection look={look} t={t} />{onEditOverride ? (<AdvancedSectiont={t}@@ -1177,18 +1194,28 @@ function TextSection({* the picture (dragged, nudged, aligned from the menu); here what they share: their look, and their type when all* are text.*/-function GroupPanel({ geometry, group, layers, onEditLayers, t }: {+function GroupPanel({ geometry, group, layers, onEditLayers, onPlace, t }: {geometry: StageGeometry;group: NonNullable<StageGeometry['group']>;layers?: readonly StageElement[];onEditLayers?: (list: LayerEdit[]) => Promise<string | null>;+ /** Their bounds typed: moved (x, y) or scaled in proportion (w, h), as Figma's fields do a selection. */+ onPlace?: (to: { x?: number; y?: number; w?: number; h?: number }) => void;t: T;}) {const [refusal, setRefusal] = React.useState<string | null>(null);- const cell = (label: string, value: number) => (- <NumField label={label} prefix={label.slice(0, 1)} value={Math.round(value * 10) / 10} disabled onCommit={() => {}} />+ const cell = (label: string, value: number, key: 'x' | 'y' | 'w' | 'h') => (+ <NumField+ label={label}+ prefix={label.slice(0, 1)}+ value={Math.round(value * 10) / 10}+ {...(key === 'w' || key === 'h' ? { min: 1 } : {})}+ disabled={!onPlace}+ onCommit={(n) => onPlace?.({ [key]: n })}+ />);- const targets = layers?.filter((l) => l.clipLoc) ?? [];+ /* the layers selected: the app's list, else the picture's own (a marquee's, a Shift-click's) */+ const targets = (layers ?? group.elements ?? []).filter((l) => l.clipLoc);const look = targets.length && onEditLayers ? makeLook(targets, layerRead, {commit: (sets) => {setRefusal(null);@@ -1206,16 +1233,18 @@ function GroupPanel({ geometry, group, layers, onEditLayers, t }: {/>{refusal ? <RefusalBanner message={refusal} onDismiss={() => setRefusal(null)} t={t} /> : null}<Section id="position" title={t('inspector.position')}>- <Row>{cell(t('inspector.x'), geometry.x)}{cell(t('inspector.y'), geometry.y)}</Row>- <Row>{cell(t('inspector.width'), geometry.w)}{cell(t('inspector.height'), geometry.h)}</Row>+ <Row>{cell(t('inspector.x'), geometry.x, 'x')}{cell(t('inspector.y'), geometry.y, 'y')}</Row>+ <Row>{cell(t('inspector.width'), geometry.w, 'w')}{cell(t('inspector.height'), geometry.h, 'h')}</Row><p className="text-[11px] leading-[16px] text-[var(--text-faint)]">{t('inspector.multiLayersHint')}</p></Section>{look ? (<>{allText ? <TypographySection look={look} t={t} sample={targets[0]?.text?.value ?? ''} /> : null}- <AppearanceSection look={look} t={t} />+ <AppearanceSection look={look} t={t} radius={targets.every((l) => l.kind === 'box' || l.kind === 'image')} />+ {allText ? <FillSection look={look} t={t} fills={[{ prop: 'color', label: t('inspector.color') }]} /> : null}+ {targets.some((l) => l.kind === 'shape') ? null : <StrokeSection look={look} t={t} />}+ <EffectsSection look={look} t={t} inner={targets.every((l) => l.kind === 'box')} /><AdjustSection look={look} t={t} />- <EffectsSection look={look} t={t} /></>) : null}</>@@ -1305,10 +1334,12 @@ function clipsLook(* can only be looked at.*/function ClipPanel({- block, geometry, stage, badges, onEdit, onPreviewClip, pageChangesOf, clipLookOf, onPreviewLook, onStartCrop, onEditMask, fades,+ block, onMain, geometry, stage, badges, onEdit, onPreviewClip, pageChangesOf, clipLookOf, onPreviewLook, onStartCrop, onEditMask, maskAsk, onMaskAsked, fades,}: {fades?: ReadonlyMap<string, FadeMs>;block: TimelineBlock;+ /** On the main track, where the magnet acts. */+ onMain: boolean;geometry?: StageGeometry | null;/** The film's stage: with the clip's own size, where it lands when it is not on screen to measure. */stage: { w: number; h: number };@@ -1320,6 +1351,8 @@ function ClipPanel({onPreviewLook?: (clipLoc: string, css: string | null) => void;onStartCrop?: () => void;onEditMask?: (session: MaskSession | null) => void;+ maskAsk?: { shape: MaskShape | 'none'; n: number } | null;+ onMaskAsked?: () => void;}) {const t = useT();const [refusal, setRefusal] = React.useState<string | null>(null);@@ -1396,13 +1429,16 @@ function ClipPanel({box={geo ? { w: geo.w, h: geo.h } : null}target={{ kind: 'clip', clipLoc: target!.loc }}{...(onEditMask ? { onEditMask } : {})}+ {...(maskAsk ? { ask: maskAsk } : {})}+ {...(onMaskAsked ? { onAsked: onMaskAsked } : {})}/>- <AppearanceSection look={look} t={t} />- <AdjustSection look={look} t={t} />+ <AppearanceSection look={look} t={t} radius />+ <StrokeSection look={look} t={t} /><EffectsSection look={look} t={t} />+ <AdjustSection look={look} t={t} /></>) : null}- {block.anchor?.move || block.anchor?.resize === 'end' ? <TimingSection t={t} block={block} commit={commit} /> : null}+ {block.anchor?.move || block.anchor?.resize === 'end' ? <TimingSection t={t} block={block} onMain={onMain} commit={commit} /> : null}{docLoc && block.clipId ? <FadeSection t={t} blocks={[block]} fades={fades} commit={commit} /> : null}{blockHasVolume(block) ? (<Section id="sound" title={t('inspector.sound')}>@@ -1445,13 +1481,14 @@ function ClipPanel({* `at` is written the way dragging writes it, from the parent window; `end` is `in point + length` in source time* when there is an in point, else (a still) the right edge in the parent window.*/-function TimingSection({ t, block, commit }: { t: T; block: TimelineBlock; commit: (edits: ClipEdit[]) => void }) {+function TimingSection({ t, block, onMain, commit }: { t: T; block: TimelineBlock; onMain: boolean; commit: (edits: ClipEdit[]) => void }) {const [unit, setUnit] = useTimeUnit();const loc = block.loc!;const parentSec = (block.anchor?.parentStartMs ?? 0) / 1000;const durSec = (block.endMs - block.startMs) / 1000;- /* the timeline's magnet: a longer clip pushes the next one along (a ripple), so the next one is no limit */- const { magnet } = useTimelinePrefs();+ /* the timeline's magnet, on the main track: a longer clip pushes the next one along (a ripple), so the next one is+ no limit */+ const magnet = useTimelinePrefs().magnet && onMain;const maxDurSec = longestSec(block, durSec, magnet);const k = block.speed ?? 1;/* slowed down, the clip gets longer on the film: without the magnet, no slower than fits before the next clip */@@ -1468,6 +1505,12 @@ function TimingSection({ t, block, commit }: { t: T; block: TimelineBlock; commistep: 1 / fps,...(timecode ? { format: (s: number) => formatTimecode(s * 1000) } : { unit: 's' }),};+ /* the clip keeps its length, so the in point goes as far as the source left after the clip: further, its end would+ pass the end of the file. A clip that plays all of its file has nowhere to slip. */+ const inMax = trimFrom == null ? 0 : block.room?.tailMs != null+ ? round3(trimFrom + (block.room.tailMs / 1000) * k)+ : round3(Math.max(0, trimFrom + durSec * k - 0.01));+ const wholeFile = trimFrom != null && trimFrom <= 0 && inMax <= 0;const slipTo = (n: number) => {/* the in point slips the source, it does not change the length: the clip stays where and as long as it is */const span = durSec * k;@@ -1541,11 +1584,8 @@ function TimingSection({ t, block, commit }: { t: T; block: TimelineBlock; commiprefix={<Scissors size={11} />}value={round3(trimFrom)}min={0}- /* the clip keeps its length, so the in point goes as far as the source left after the clip: further, its- end would pass the end of the file */- max={block.room?.tailMs != null- ? round3(trimFrom + (block.room.tailMs / 1000) * k)- : round3(Math.max(0, trimFrom + durSec * k - 0.01))}+ max={inMax}+ disabled={wholeFile}{...time}onCommit={slipTo}/>@@ -1568,6 +1608,11 @@ function TimingSection({ t, block, commit }: { t: T; block: TimelineBlock; commi) : <span />}</Row>) : null}+ {wholeFile ? (+ <p data-in-point-limit="" className="px-0.5 text-[10.5px] leading-snug text-[var(--text-faint)]">+ {t('inspector.inPointWhole')}+ </p>+ ) : null}{/* why it cannot get slower: the next clip; the magnet would push it along instead */}{trimFrom != null && canSpeed && !magnet && minSpeed > FILM_SPEED_MIN ? (<p data-speed-limit="" className="px-0.5 text-[10.5px] leading-snug text-[var(--text-faint)]">@@ -1821,6 +1866,23 @@ function MultiClipPanel({const before = compactBox(p.value, p.own);return JSON.stringify(next) === JSON.stringify(before) ? [] : [{ loc: p.loc, prop: 'box', value: next }];});+ /* their bounds, as Figma shows a selection's: typed, the X / Y move them all and the W / H scale them all, in+ proportion, about the bounds' top left */+ const bounds = allPlaced?.length ? (() => {+ const x0 = Math.min(...allPlaced.map((p) => p.x)), y0 = Math.min(...allPlaced.map((p) => p.y));+ return { x: x0, y: y0, w: Math.max(...allPlaced.map((p) => p.x + p.w)) - x0, h: Math.max(...allPlaced.map((p) => p.y + p.h)) - y0 };+ })() : null;+ const groupEdit = (d: Partial<GroupDrag>) => {+ const drag: GroupDrag = { kind: 'move', dx: 0, dy: 0, kx: 1, ky: 1, turn: 0, anchor: { x: 0, y: 0 }, ...d };+ commit(boxEdits((p) => {+ /* the transform counts from the box's own offset: the anchor too */+ const next = groupDragged({ ...drag, anchor: { x: drag.anchor.x - (p.own.x ?? 0), y: drag.anchor.y - (p.own.y ?? 0) } }, p.value, p.own);+ return { x: next.x, y: next.y, scaleX: next.scaleX, scaleY: next.scaleY };+ }));+ };+ const scaleBounds = (k: number) => {+ if (bounds && k > 0 && Number.isFinite(k) && k !== 1) groupEdit({ kind: 'scale', kx: k, ky: k, anchor: { x: bounds.x, y: bounds.y } });+ };const common = (fn: (p: Placed) => number) => {if (!allPlaced) return MIXED;const v = round1(fn(allPlaced[0]!));@@ -1869,16 +1931,16 @@ function MultiClipPanel({<Section id="position" title={t('inspector.position')}><AlignBar t={t} onAlign={alignTo} {...(allPlaced.length >= 3 ? { onDistribute: distribute } : {})} /><Row>- <NumField label={t('inspector.x')} prefix="X" value={common((p) => p.x)} min={-COORD_LIMIT} max={COORD_LIMIT} ctx={{ percent: stage.w }}- onCommit={(_, apply) => commit(boxEdits((p) => clipFieldPart('x', apply(p.x), p.own)))} />- <NumField label={t('inspector.y')} prefix="Y" value={common((p) => p.y)} min={-COORD_LIMIT} max={COORD_LIMIT} ctx={{ percent: stage.h }}- onCommit={(_, apply) => commit(boxEdits((p) => clipFieldPart('y', apply(p.y), p.own)))} />+ <NumField label={t('inspector.x')} prefix="X" value={bounds ? round1(bounds.x) : MIXED} min={-COORD_LIMIT} max={COORD_LIMIT} ctx={{ percent: stage.w }}+ onCommit={(x) => { if (bounds) groupEdit({ dx: x - bounds.x }); }} />+ <NumField label={t('inspector.y')} prefix="Y" value={bounds ? round1(bounds.y) : MIXED} min={-COORD_LIMIT} max={COORD_LIMIT} ctx={{ percent: stage.h }}+ onCommit={(y) => { if (bounds) groupEdit({ dy: y - bounds.y }); }} /></Row><div className="grid grid-cols-[1fr_1fr_24px] items-center gap-1.5">- <NumField label={t('inspector.width')} prefix="W" value={common((p) => p.w)} min={1} max={COORD_LIMIT} ctx={{ percent: stage.w }}- onCommit={(_, apply) => commit(boxEdits((p) => clipFieldPart('w', apply(p.w), p.own)))} />- <NumField label={t('inspector.height')} prefix="H" value={common((p) => p.h)} min={1} max={COORD_LIMIT} ctx={{ percent: stage.h }}- onCommit={(_, apply) => commit(boxEdits((p) => clipFieldPart('h', apply(p.h), p.own)))} />+ <NumField label={t('inspector.width')} prefix="W" value={bounds ? round1(bounds.w) : MIXED} min={1} max={COORD_LIMIT} ctx={{ percent: stage.w }}+ onCommit={(w) => { if (bounds) scaleBounds(w / bounds.w); }} />+ <NumField label={t('inspector.height')} prefix="H" value={bounds ? round1(bounds.h) : MIXED} min={1} max={COORD_LIMIT} ctx={{ percent: stage.h }}+ onCommit={(h) => { if (bounds) scaleBounds(h / bounds.h); }} /><LockToggle t={t} locked /></div><Row>@@ -1890,9 +1952,10 @@ function MultiClipPanel({) : null}{look ? (<>- <AppearanceSection look={look} t={t} />- <AdjustSection look={look} t={t} />+ <AppearanceSection look={look} t={t} radius />+ <StrokeSection look={look} t={t} /><EffectsSection look={look} t={t} />+ <AdjustSection look={look} t={t} /></>) : null}{onEdit && blocks.every((b) => b.clipId && b.loc && parseFilmDocLoc(b.loc) != null) ? <FadeSection t={t} blocks={blocks} fades={fades} commit={commit} /> : null}diff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsxindex bb09d45..31f14e4 100644--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx@@ -33,6 +33,7 @@* point winning. What is written is always film.html: a clip's `box`, a page's `overrides`, through the callbacks.*/import * as React from 'react';+import { isSelectAll as isSelectAllKey, type KeyLike } from '@/lib/select-all-key';import {AlignCenterHorizontal, AlignCenterVertical, AlignEndHorizontal, AlignEndVertical, AlignHorizontalDistributeCenter,AlignStartHorizontal, AlignStartVertical, AlignVerticalDistributeCenter, Crop as CropIcon, MessageSquarePlus,@@ -61,12 +62,14 @@ import {positionOf, roundOf, transformOfVisible, visibleFrame, type CropAspect, type Rect,} from '@/lib/stage-crop';import {- alignShift, HANDLE_AT, insideBox, insideFrame, movedOffset, pivotCenter, resizedFrame, sameClientRect, sameGuides,+ alignShift, groupDragged, type GroupDrag, HANDLE_AT, insideBox, insideFrame, movedOffset, pivotCenter, resizedFrame, sameClientRect, sameGuides,sameLayerGeometry, scaledLayer, turnedLayer, unionRect, type AlignEdge, type ClientBox, type FramePivot,type LayerGeometry, type StageFrame,} from '@/lib/stage-gesture';import { measureGaps, type MeasureLine } from '@/lib/stage-measure';import type { MaskSession } from '@/lib/stage-mask';+import { MASK_SHAPES, maskOf, type MaskShape } from '@/lib/clip-mask';+import { MaskGlyph } from '@/components/inspector-look';import { layerTarget } from '@/lib/stage-layers';import { regionBox, regionClipIds, regionTexts } from '@/lib/studio-refs';import type { StageBox } from '@/lib/host';@@ -98,6 +101,8 @@ const staleBucket = (timeMs: number): number => Math.round(timeMs / STALE_BUCKETconst MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);const REGION_KEY = MAC ? 'Meta' : 'Control';const regionKeyHeld = (e: { metaKey: boolean; ctrlKey: boolean }) => (MAC ? e.metaKey : e.ctrlKey);+/** ⌘A (Ctrl+A elsewhere): every layer on the picture, as Figma selects all. */+const isSelectAll = (e: KeyLike) => isSelectAllKey(e, MAC);/** Arrow keys write what they moved this long after the last one (held down they come thirty a second). */const NUDGE_WRITE_MS = 350;const NO_CROP: Crop = [0, 0, 0, 0];@@ -138,11 +143,19 @@ export interface StageLayer {};}-/** Just where a hovered layer is. */+/** A whole clip dragged with others: where it was, and its picture's own size. */+interface ClipsDragItem { loc: string; id: string; t0: MgTransform; box: MgBox }+++/** A clip as the film's stage tells it: where its picture is drawn (stage px), and whether it shows now. */+interface StageClipBox { id: string; visible: boolean; x: number; y: number; w: number; h: number }++/** Just where a hovered layer is; a whole clip hovered (a page's empty part, a video, a still) has its id. */interface StageOutline {handle: number;rect: ClientBox;frame?: StageFrame;+ clip?: string;}/** A clip's edit from the stage: its film.html `box`, or its own CSS (`style`: a crop). */@@ -177,6 +190,11 @@ export interface FilmStageControl {picked(): StagePick[];/** Write now what the arrow keys moved and is not written yet: before an undo, or any other edit. */flushPending(): void;+ /**+ * Several layers in hand: their bounds put at `x` / `y` (all moved alike), or made `w` / `h` wide (all scaled alike,+ * in proportion, about the bounds' top left), as Figma's fields move and scale a selection. Stage px.+ */+ placeLayers(to: { x?: number; y?: number; w?: number; h?: number }): void;}/** One thing in hand on the picture, for a reference: what it is, and its box (stage px) when it is a layer. */@@ -210,6 +228,8 @@ function sameLinkedMarks(a: readonly LinkedMark[], b: readonly LinkedMark[]): boconst scaleBox = (b: ClientBox, k: number): ClientBox => ({ left: b.left * k, top: b.top * k, width: b.width * k, height: b.height * k });const scaleFrame = (f: StageFrame, k: number): StageFrame => ({ cx: f.cx * k, cy: f.cy * k, w: f.w * k, h: f.h * k, r: f.r });+/** Whether `r` is wholly inside `area` (a px to spare for rounding). */+const rectInside = (r: Rect, area: Rect) => r.x >= area.x - 1 && r.y >= area.y - 1 && r.x + r.w <= area.x + area.w + 1 && r.y + r.h <= area.y + area.h + 1;const clientOf = (r: Rect): ClientBox => ({ left: r.x, top: r.y, width: r.w, height: r.h });/**@@ -321,6 +341,8 @@ interface FilmStageSelectProps {onEditClip?: (edits: StageClipEdit[]) => Promise<string | null>;/** The clips selected elsewhere (`film.html#<track>.<clip>`): one is in hand here, several are outlined. */linkedLocs?: readonly string[];+ /** Select these clips whole (a marquee around several): the timeline selects them, and they are outlined here. */+ onSelectClips?: (locs: readonly string[]) => void;/*** Select the layer at `loc` in the clip at `clipLoc` (the inspector's breadcrumb, the menu's Select parent). `seq`* goes up each time, so the same layer can be asked for twice.@@ -367,8 +389,8 @@ interface FilmStageSelectProps {selectionBar?: boolean;/** The bar's first button, "Add to chat": what is in hand. Without it the bar has no such button. */onRefer?: (picks: StagePick[]) => void;- /** The bar's Mask: the inspector's Mask section, for the clip in hand. */- onStartMask?: () => void;+ /** The bar's Mask, a menu of shapes: the one picked is put on the clip in hand, its handles on the picture. */+ onStartMask?: (shape: MaskShape | 'none', clipLoc: string) => void;/** A layer pointed at from elsewhere (a row of the Layers panel), outlined as the one under the pointer is. */pointLayer?: { clipId: string; loc: string } | null;/**@@ -379,7 +401,7 @@ interface FilmStageSelectProps {}function FilmStageSelectImpl({- previewRef, stage, doc, spans, timeMs, playing, onPause, onSelectElement, onEditClip, linkedLocs, selectRequest,+ previewRef, stage, doc, spans, timeMs, playing, onPause, onSelectElement, onEditClip, linkedLocs, onSelectClips, selectRequest,clipPreviewRef, lookPreviewRef, controlRef, onTransformLayer, onTransformLayers, onEditTextInline, onGeometry, menuFor, recoveryMenu,onRegion, regionHint, flashBox, chat, onHoverLayer, selectionBar = false, onRefer, onStartMask, pointLayer, arrowsMove = true,}: FilmStageSelectProps) {@@ -517,6 +539,34 @@ function FilmStageSelectImpl({const live = lookLiveRef.current;return clipInfo(docRef.current, spansRef.current, stage, loc, live?.clipLoc === loc ? live : null);};+ /**+ * The clips a marquee `area` goes around (stage px), by the part of each on the canvas (a part past its edge cannot+ * be boxed), as Figma takes the frames a box goes around.+ */+ const clipsInside = (list: readonly StageClipBox[], area: Rect): { id: string; loc: string }[] => {+ const onCanvas = (r: Rect): Rect => {+ const x = Math.max(0, r.x), y = Math.max(0, r.y);+ return { x, y, w: Math.min(stage.w, r.x + r.w) - x, h: Math.min(stage.h, r.y + r.h) - y };+ };+ return list.flatMap((c) => {+ const shown = onCanvas(shownBoxOf(c));+ const loc = c.visible && shown.w > 0 && shown.h > 0 && rectInside(shown, area) ? clipLocOf(docRef.current, c.id) : undefined;+ return loc ? [{ id: c.id, loc }] : [];+ });+ };+ const clipsInsideRef = React.useRef(clipsInside);+ clipsInsideRef.current = clipsInside;+ /** A whole clip's outline for the hover: the part of it that shows, turned with it. */+ const clipOutline = (id: string): StageOutline | null => {+ const loc = clipLocOf(docRef.current, id);+ const info = loc ? infoOf(loc) : null;+ if (!info?.box) return null;+ const frame = visibleFrame(info.t, info.box, info.crop);+ const r = frameAabb(frame);+ return { handle: -1, clip: id, rect: clientOf(r), ...(frame.r ? { frame } : {}) };+ };+ const clipOutlineRef = React.useRef(clipOutline);+ clipOutlineRef.current = clipOutline;/** Another clip as a snap or measuring target: the part its crop leaves (the film's stage tells whole boxes). */const shownBoxOf = (c: { id: string; x: number; y: number; w: number; h: number }): Rect => {const loc = clipLocOf(docRef.current, c.id);@@ -587,6 +637,16 @@ function FilmStageSelectImpl({/* ── several layers moved together ── */type MultiDragItem = MultiItem & { base: LayerGeometry; scale: number; now: LayerGeometry };const multiDrag = React.useRef<{ x: number; y: number; moved: boolean; rect0: ClientBox; items: MultiDragItem[] } | null>(null);+ /* several whole clips selected (on the timeline, or by a marquee): a press on one of them drags them all */+ const clipsDrag = React.useRef<(GroupDrag & {+ x: number; y: number; moved: boolean; items: ClipsDragItem[];+ /* scaling: the corner or edge pulled ('n', 'se'…) and where it was (stage px); turning: the pointer's first angle */+ handle: string | null; from: { x: number; y: number }; a0: number; box0: ClientBox;+ }) | null>(null);+ /** The frame around several clips while they are turned: the frame they had, turned as far (Figma's). */+ const [groupTurn, setGroupTurn] = React.useState<{ box: ClientBox; turn: number } | null>(null);+ /** Where the clips being dragged are drawn now (their outlines follow the hand; film.html is written at the release). */+ const [clipsMoved, setClipsMoved] = React.useState<readonly LinkedMark[] | null>(null);const multiItemsNow = (): MultiDragItem[] => {const vs = viewScaleNow();return (multiRef.current ?? []).map((it) => ({ ...it, base: it.layer.geo.g, now: it.layer.geo.g, scale: it.layer.geo.k * vs }));@@ -611,6 +671,33 @@ function FilmStageSelectImpl({items.forEach((it, i) => { it.now = { ...it.base, t: movedOffset(it.base, dxOf(i), dyOf(i), it.layer.geo.parentR, it.scale) }; });multiPaint.push(items.map((it) => ({ ...it })));};+ /** Several layers' bounds moved or scaled as the inspector's typed numbers say (FilmStageControl.placeLayers). */+ const placeLayers = async (to: { x?: number; y?: number; w?: number; h?: number }) => {+ const items = multiItemsNow();+ const held = pickedRef.current;+ if (items.length < 2 || !held || !onTransformLayers) return;+ const b = held.rect;+ if (to.x != null || to.y != null) {+ const vs = viewScaleNow();+ const dx = ((to.x ?? b.left) - b.left) * vs, dy = ((to.y ?? b.top) - b.top) * vs;+ shiftLayers(items, () => dx, () => dy);+ onTransformLayers(items.map((it) => ({ element: it.element, g: it.now })));+ return;+ }+ const k = to.w != null ? to.w / b.width : to.h != null ? to.h / b.height : 1;+ if (!(k > 0) || !Number.isFinite(k) || k === 1) return;+ /* each one scaled by k about its own center, that center then moved as the bounds scale about their top left */+ const scaled = await Promise.all(items.map(async (it) => {+ const r = it.layer.rect;+ const center = { x: b.left + (r.left + r.width / 2 - b.left) * k, y: b.top + (r.top + r.height / 2 - b.top) * k };+ const g: LayerGeometry = { ...it.base, s: [it.base.s[0] * k, it.base.s[1] * k] };+ const out = await ask<{ g: LayerGeometry }>('paint', { handle: it.layer.handle, g, center });+ return { element: it.element, g: out?.g ?? g };+ }));+ onTransformLayers(scaled);+ };+ const placeLayersRef = React.useRef<(to: { x?: number; y?: number; w?: number; h?: number }) => void>(() => {});+ placeLayersRef.current = (to) => { void placeLayers(to); };/** Line several layers up with an edge / middle of their union box. */const alignMany = (edge: AlignEdge) => {const items = multiItemsNow();@@ -723,12 +810,21 @@ function FilmStageSelectImpl({/* the playhead moved a bucket on: what is selected stays selected, only where it is changed. A layer whose clip isnot on screen any more lets go: its box would stand over a picture it is not in */const stale = staleBucket(timeMs);+ /** Whether the clip `id` is on screen at the playhead (unknown yet: taken as on). */+ const shownNow = (id: string) => {+ const span = spans.find((s) => s.id === id);+ return !span || spanShows(span, timeMs);+ };React.useEffect(() => {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)) {+ /* several layers: one whose clip went lets them all go, as one does */+ const clips = multiRef.current ? multiRef.current.map((i) => i.layer.clip) : [held.element?.kind !== 'clip' ? held.layer?.clip : undefined];+ const gone = clips.some((clip) => {+ const span = clip ? spans.find((s) => s.id === clip) : undefined;+ return span && !spanShows(span, timeMs);+ });+ if (gone) {dropPick();onSelectElement?.(null);return;@@ -932,7 +1028,7 @@ function FilmStageSelectImpl({setEditingText(element.loc);setHover(null);previewRef.current?.focus?.();- void ask<boolean>('textStart', { handle: layer.handle, multiline: element.text.shape === 'children' }).then((started) => {+ void ask<boolean>('textStart', { handle: layer.handle }).then((started) => {if (started || textEdit.current?.layer.handle !== layer.handle) return;textEdit.current = null;setEditingText(null);@@ -1065,7 +1161,7 @@ function FilmStageSelectImpl({|| el?.closest('[role="listbox"]')|| el?.closest('[data-popover-panel]')) return;- if (el?.closest('[data-timeline]') && (!pickedRef.current?.element || pickedRef.current.element.kind === 'clip')) return;+ if (el?.closest('[data-timeline]') && !multiRef.current && (!pickedRef.current?.element || pickedRef.current.element.kind === 'clip')) return;dropPick();onSelectElement?.(null);};@@ -1080,13 +1176,40 @@ function FilmStageSelectImpl({// eslint-disable-next-line react-hooks/exhaustive-deps}, [dropPick, onSelectElement, picked]);+ /* ⌘A: the outermost layers on the picture, as a marquee around the whole canvas; from the window when the keyboard+ is not in a field, the timeline or another panel (the picture's own keys come from the film, below) */+ const selectAll = async () => {+ const all = await ask<StageLayer[]>('box', { x: 0, y: 0, w: stage.w, h: stage.h }) ?? [];+ if (all.length) selectMany(all);+ };+ const selectAllRef = React.useRef(selectAll);+ selectAllRef.current = selectAll;+ React.useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (!isSelectAll(e) || textEdit.current || cropRef.current) return;+ const el = e.target as HTMLElement | null;+ if (el && el !== document.body && !el.closest('[data-viewer-pane]') && !el.closest('[data-film-select]')) return;+ if (el?.closest('input, textarea, select, [contenteditable="true"]')) return;+ e.preventDefault();+ void selectAllRef.current();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, []);+/* the film's own events: an in-place edit ended, a key pressed in the picture, another load of the film shown */React.useEffect(() => {const preview = previewRef.current;if (!preview?.onStage) return undefined;return preview.onStage((e) => {if (e.event === 'text') onTextDoneRef.current(e);- else if (e.event === 'key') keyHandler.current?.(e.key);+ else if (e.event === 'key') {+ const k = e.key;+ if (isSelectAll(k)) { if (!textEdit.current && !cropRef.current) void selectAllRef.current(); }+ /* several clips selected: the picture's arrow keys move them all */+ else if (k.key.startsWith('Arrow') && arrowsMoveRef.current && !k.metaKey && !k.ctrlKey && !k.altKey && nudgeGroupRef.current(k)) return;+ else keyHandler.current?.(k);+ }else {if (textEdit.current) { textEdit.current = null; setEditingText(null); }syncFilmOffsetRef.current();@@ -1103,10 +1226,12 @@ function FilmStageSelectImpl({const next: LinkedMark[] = [];for (const loc of linkedLocs ?? []) {const info = clipInfo(doc, spans, stage, loc);- if (info?.box) next.push({ loc, t: info.t, box: info.box });+ /* only a clip on screen now: one selected elsewhere in time has nothing here to outline */+ if (info?.box && shownNow(info.id)) next.push({ loc, t: info.t, box: info.box });}setLinkedMarks((cur) => (sameLinkedMarks(cur, next) ? cur : next));- }, [doc, spans, stage, linkedLocs]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [doc, spans, stage, linkedLocs, stale]);/*** One block selected on the timeline is in hand here at once (a frame with handles, not an outline): selecting it@@ -1122,8 +1247,10 @@ function FilmStageSelectImpl({}const only = locs[0]!;const held = pickedRef.current?.element;- if (held?.isMgOuter && held.clipLoc === only) return;const info = clipInfo(doc, spans, stage, only);+ /* not on screen now (the playhead elsewhere): no frame over a picture it is not in; it comes back with it */+ if (info && !shownNow(info.id)) { if (held?.isMgOuter) dropPick(); return; }+ if (held?.isMgOuter && held.clipLoc === only) return;/* a sound has no picture: the handles of the clip held before go */if (!info) { if (pickedRef.current?.element?.isMgOuter) dropPick(); return; }/* the inspector's preview was of the clip held before */@@ -1209,6 +1336,7 @@ function FilmStageSelectImpl({editMask: setMaskSession,picked: () => pickedItemsRef.current(),flushPending: () => flushPendingRef.current(),+ placeLayers: (to) => placeLayersRef.current(to),};return () => { controlRef.current = null; };}, [ask, controlRef, elementOf, syncGeomSoon]);@@ -1234,14 +1362,37 @@ function FilmStageSelectImpl({const moveRaf = React.useRef(0);const moveAt = React.useRef<{ cx: number; cy: number; shift?: boolean; alt?: boolean } | null>(null);React.useEffect(() => () => { if (moveRaf.current) cancelAnimationFrame(moveRaf.current); }, []);+ /* every thing a click can take is outlined under the pointer: a page's layer, else the clip there (a page by its+ empty part, as its layers are: several pages on the picture are each found) */const hoverQueue = React.useMemo(() => new Latest<{ x: number; y: number; from: number | null }>(async (p) => {- const found = await ask<StageOutline>('hit', p);+ let found = await ask<StageOutline>('hit', p);+ if (!found) {+ const id = await ask<string>('clipAt', { x: p.x, y: p.y });+ found = id ? clipOutlineRef.current(id) : null;+ }if (!moveAt.current) return;- /* the same layer in the same place: keep the object (sixty questions a second must not redraw the outline) */+ /* the same thing in the same place: keep the object (sixty questions a second must not redraw the outline) */setHover((cur) => (found- ? (cur && cur.handle === found.handle && sameClientRect(cur.rect, found.rect) ? cur : found)+ ? (cur && cur.handle === found.handle && cur.clip === found.clip && sameClientRect(cur.rect, found.rect) ? cur : found): (cur ? null : cur)));}), [ask]);+ /* while a marquee is drawn: what letting go would select, outlined as it goes (Figma) — the clips it goes around,+ else the layers wholly inside it. The clips are asked once, at the press */+ const marqueeClips = React.useRef<Promise<StageClipBox[] | null> | null>(null);+ const [marqueeHits, setMarqueeHits] = React.useState<readonly StageOutline[]>([]);+ const marqueeQueue = React.useMemo(() => new Latest<Rect | null>(async (area) => {+ if (!area) { setMarqueeHits([]); return; }+ const clips = clipsInsideRef.current((await marqueeClips.current) ?? [], area);+ if (!draftRef.current) return;+ if (clips.length) {+ setMarqueeHits(clips.flatMap((c) => clipOutlineRef.current(c.id) ?? []));+ return;+ }+ const layers = await ask<StageLayer[]>('box', area) ?? [];+ if (!draftRef.current) return;+ setMarqueeHits(layers.map((l) => ({ handle: l.handle, rect: l.rect, ...(l.frame.r ? { frame: l.frame } : {}) })));+ }), [ask]);+ React.useEffect(() => { if (!draft) { marqueeQueue.push(null); marqueeClips.current = null; } }, [draft, marqueeQueue]);/* a layer pointed at from the Layers panel: outlined where it is drawn, until the pointer leaves the row */const pointClip = pointLayer?.clipId;const pointLoc = pointLayer?.loc;@@ -1259,12 +1410,8 @@ function FilmStageSelectImpl({});return () => { live = false; };}, [pointClip, pointLoc, ask]);- /** Only with no clip in hand: a clip in hand owns the picture. */- const hoverEnabled = !picked?.element?.isMgOuter;- const hoverEnabledRef = React.useRef(hoverEnabled);- hoverEnabledRef.current = hoverEnabled;/* the layer under the pointer, told to the app: asked of the stage once each time it is another one */- const hoverHandle = hover?.handle ?? null;+ const hoverHandle = hover && !hover.clip ? hover.handle : null;React.useEffect(() => {if (!onHoverLayer) return undefined;if (hoverHandle == null) { onHoverLayer(null); return undefined; }@@ -1278,6 +1425,9 @@ function FilmStageSelectImpl({/* ── a whole clip in hand: moved, scaled, turned ── */const clipPlace = React.useMemo(() => new Latest<{ clip: string; box: FilmBox | null }>(async (a) => { await ask('place', a); }), [ask]);+ const clipsPlace = React.useMemo(() => new Latest<{ clip: string; box: FilmBox | null }[]>(async (list) => {+ await Promise.all(list.map((a) => ask('place', a)));+ }), [ask]);const applyMgGesture = (stagePt: { x: number; y: number }, shift: boolean, alt: boolean) => {const g = gestureRef.current;if (!g) return;@@ -1407,10 +1557,55 @@ function FilmStageSelectImpl({return true;};+ /* several clips selected: the arrow keys move them all (Shift: 10 px), shown at once and written once they stop */+ const groupNudge = React.useRef<{ items: ClipsDragItem[]; dx: number; dy: number; timer: ReturnType<typeof setTimeout> | null } | null>(null);+ const flushGroupNudge = () => {+ const n = groupNudge.current;+ groupNudge.current = null;+ if (!n) return;+ if (n.timer) clearTimeout(n.timer);+ const moved = n.items.map((it) => ({ loc: it.loc, box: it.box, t: { ...it.t0, x: it.t0.x + n.dx, y: it.t0.y + n.dy } }));+ setLinkedMarks((marks) => marks.map((m) => moved.find((it) => it.loc === m.loc) ? { ...m, t: moved.find((it) => it.loc === m.loc)!.t } : m));+ setClipsMoved(null);+ void clipsPlace.idle().then(() => onEditClip?.(moved.map((it) => ({ loc: it.loc, prop: 'box' as const, value: compactBox(it.t, it.box) }))));+ };+ const nudgeGroup = (e: KeyboardEvent): boolean => {+ const locs = linkedLocs ?? [];+ if (!onEditClip || locs.length < 2 || clipsDrag.current || cropRef.current || locs.some((loc) => lockedClip(loc))) return false;+ e.preventDefault();+ const step = e.shiftKey ? 10 : 1;+ const n = groupNudge.current ?? {+ items: locs.flatMap((loc) => { const info = infoOf(loc); return info?.box ? [{ loc, id: info.id, t0: info.t, box: info.box }] : []; }),+ dx: 0, dy: 0, timer: null,+ };+ n.dx += e.key === 'ArrowLeft' ? -step : e.key === 'ArrowRight' ? step : 0;+ n.dy += e.key === 'ArrowUp' ? -step : e.key === 'ArrowDown' ? step : 0;+ const moved = n.items.map((it) => ({ loc: it.loc, box: it.box, t: { ...it.t0, x: it.t0.x + n.dx, y: it.t0.y + n.dy } }));+ setClipsMoved(moved);+ clipsPlace.push(n.items.map((it, i) => ({ clip: it.id, box: compactBox(moved[i]!.t, it.box) })));+ if (n.timer) clearTimeout(n.timer);+ n.timer = setTimeout(flushGroupNudge, NUDGE_WRITE_MS);+ groupNudge.current = n;+ return true;+ };+ const nudgeGroupRef = React.useRef(nudgeGroup);+ nudgeGroupRef.current = nudgeGroup;+ React.useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (!e.key.startsWith('Arrow') || !arrowsMoveRef.current || e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;+ const el = e.target as HTMLElement | null;+ if (el?.closest('input, textarea, select, [contenteditable="true"], [data-timeline]')) return;+ nudgeGroupRef.current(e);+ };+ window.addEventListener('keydown', onKey, true);+ return () => window.removeEventListener('keydown', onKey, true);+ }, []);+/* what the arrow keys moved and is not written yet, written now (the editor asks before an undo or another edit) */flushPendingRef.current = () => {if (nudge.current) flushNudge();if (clipNudge.current) flushClipNudge();+ if (groupNudge.current) flushGroupNudge();};/* ── crop mode: a video or still in hand, cropped in place ── */@@ -1762,11 +1957,14 @@ function FilmStageSelectImpl({return;}if (draftRef.current) {- draftRef.current = { ...draftRef.current, x2: x, y2: y };- setDraft(draftRef.current);+ const d = draftRef.current = { ...draftRef.current, x2: x, y2: y };+ setDraft(d);+ const area = { x: Math.min(d.x1, d.x2) / vs, y: Math.min(d.y1, d.y2) / vs, w: Math.abs(d.x2 - d.x1) / vs, h: Math.abs(d.y2 - d.y1) / vs };+ marqueeQueue.push(area.w >= MARQUEE_MIN_PX && area.h >= MARQUEE_MIN_PX ? area : null);return;}- if (!hoverEnabledRef.current || textEdit.current) return;+ /* with a clip in hand too: what is in it and around it is still found (its own outline is its frame) */+ if (textEdit.current) return;hoverQueue.push({ x: x / vs, y: y / vs, from: pickedRef.current?.layer?.handle ?? null });};const flushMoveRef = React.useRef(flushMove);@@ -1823,7 +2021,7 @@ function FilmStageSelectImpl({h: round(picked.rect.height),r: 0,unit: 1,- group: { n: multi.length, kinds: [...new Set(multi.map((i) => i.layer.kind))] },+ group: { n: multi.length, kinds: [...new Set(multi.map((i) => i.layer.kind))], elements: multi.map((i) => i.element) },stage,});return;@@ -1898,6 +2096,36 @@ function FilmStageSelectImpl({if (box) void pointAt(box);return;}+ const cd = clipsDrag.current;+ if (cd) {+ clipsDrag.current = null;+ e.stopPropagation();+ setDragging(false);+ if (!cd.moved) {+ setGroupTurn(null);+ /* not pulled: a click on one of them takes that one alone */+ const p = local(e);+ const token = ++pressSeq.current;+ void ask<string>('clipAt', { x: p.x / vs, y: p.y / vs }).then((id) => {+ if (token !== pressSeq.current) return;+ const loc = id ? clipLocOf(docRef.current, id) : undefined;+ const info = loc ? infoOf(loc) : null;+ if (info) commitHit(describeClip(info, stage));+ });+ return;+ }+ const moved = cd.items.map((it) => ({ ...it, t: groupDragged(cd, it.t0, it.box) }));+ setGroupTurn(null);+ /* the outlines stay where they were let go (film.html follows a moment later) */+ setLinkedMarks((marks) => marks.map((m) => moved.find((it) => it.loc === m.loc) ? { ...m, t: moved.find((it) => it.loc === m.loc)!.t } : m));+ setClipsMoved(null);+ void clipsPlace.idle().then(() => onEditClip?.(moved.map((it) => ({ loc: it.loc, prop: 'box' as const, value: compactBox(it.t, it.box) })))).then((failed) => {+ if (!failed) return;+ clipsPlace.push(cd.items.map((it) => ({ clip: it.id, box: null })));+ setLinkedMarks((marks) => marks.map((m) => cd.items.find((it) => it.loc === m.loc) ? { ...m, t: cd.items.find((it) => it.loc === m.loc)!.t0 } : m));+ });+ return;+ }const md = multiDrag.current;if (md) {multiDrag.current = null;@@ -1947,7 +2175,8 @@ function FilmStageSelectImpl({e.stopPropagation();const p = local(e);if (gestureRef.current.pendingClick) {- /* a click on the clip in hand: the top clip under the pointer is taken in hand */+ /* a click on the clip in hand (a drag moves it): the layer of a page under the pointer is taken in hand, as+ a click in a selected frame selects what is in it (Figma); else the top clip there */const g = gestureRef.current;gestureRef.current = null;liveTRef.current = null;@@ -1955,12 +2184,16 @@ function FilmStageSelectImpl({setLiveT(null);const at = g.hit ?? p;const token = ++pressSeq.current;- void ask<string>('clipAt', { x: at.x / vs, y: at.y / vs }).then((id) => {+ void (async () => {+ const layer = await ask<StageLayer>('hit', { x: at.x / vs, y: at.y / vs, detail: true });+ if (token !== pressSeq.current) return;+ if (layer) { setHover(null); commitHit(hitOf(layer)); return; }+ const id = await ask<string>('clipAt', { x: at.x / vs, y: at.y / vs });if (token !== pressSeq.current) return;const loc = id ? clipLocOf(docRef.current, id) : undefined;const info = loc ? infoOf(loc) : null;commitHit(info ? describeClip(info, stage) : null);- });+ })();return;}applyMgGesture({ x: p.x / vs, y: p.y / vs }, e.shiftKey, e.altKey);@@ -1989,8 +2222,26 @@ function FilmStageSelectImpl({if (token !== pressSeq.current) return;/* the threshold is in stage px: the same gesture is a click in a small window and in full screen alike */if (box.width / vs >= MARQUEE_MIN_PX && box.height / vs >= MARQUEE_MIN_PX) {- /* the outermost layers wholly inside are selected (Figma); Shift adds them to what was selected */- const inside = await ask<StageLayer[]>('box', { x: box.left / vs, y: box.top / vs, w: box.width / vs, h: box.height / vs }) ?? [];+ const area = { x: box.left / vs, y: box.top / vs, w: box.width / vs, h: box.height / vs };+ /* clips wholly inside (a page, a video, a still, by the part on the canvas) are selected whole, as Figma takes+ a frame the box goes around; Shift adds them to the clips selected */+ const clips = onSelectClips ? await (marqueeClips.current ?? ask<StageClipBox[]>('clips')) ?? [] : [];+ if (token !== pressSeq.current) return;+ const around = clipsInside(clips, area).map((c) => c.loc);+ if (around.length) {+ const locs = [...new Set([...(shift ? linkedLocs ?? [] : []), ...around])];+ setHover(null);+ if (locs.length === 1) {+ const info = infoOf(locs[0]!);+ commitHit(info ? describeClip(info, stage) : null);+ } else {+ dropPick();+ onSelectClips!(locs);+ }+ return;+ }+ /* else the outermost layers wholly inside (a box within a page: its layers); Shift adds them */+ const inside = await ask<StageLayer[]>('box', area) ?? [];if (token !== pressSeq.current) return;const prior = shift ? (base ?? []) : [];const all = [...prior, ...inside.filter((l) => !prior.some((b) => b.handle === l.handle))];@@ -1998,7 +2249,7 @@ function FilmStageSelectImpl({else commitHit(null);return;}- /* not pulled open far enough: a click. A layer of a page is selected, else a video or still; on nothing, nothing is */+ /* not pulled open far enough: a click. A layer of a page is selected, else the clip; on nothing, nothing is */const layer = await ask<StageLayer>('hit', { x: p.x / vs, y: p.y / vs, cycleFrom: cycle, from, detail: true });if (token !== pressSeq.current) return;/* Shift-click adds to / takes from the selection (Figma) */@@ -2013,8 +2264,9 @@ function FilmStageSelectImpl({commitHit(hitOf(layer));return;}- /* no layer of a page there: the video or still under the pointer is taken in hand, as on the timeline */- const id = !base && onEditClip ? await ask<string>('clipAt', { x: p.x / vs, y: p.y / vs, pictures: true }) : null;+ /* no layer there: the clip under the pointer is taken in hand, as on the timeline (a page by its empty part: a+ page smaller than the canvas is moved and sized as a video is) */+ const id = !base && onEditClip ? await ask<string>('clipAt', { x: p.x / vs, y: p.y / vs }) : null;if (token !== pressSeq.current) return;const loc = id ? clipLocOf(docRef.current, id) : undefined;const info = loc ? infoOf(loc) : null;@@ -2033,6 +2285,10 @@ function FilmStageSelectImpl({? { left: Math.min(draft.x1, draft.x2), top: Math.min(draft.y1, draft.y2), width: Math.abs(draft.x2 - draft.x1), height: Math.abs(draft.y2 - draft.y1) }: null;const linkedShown = linkedOutlines(linkedMarks, picked?.element?.clipLoc, dragging);+ /* several clips selected: one frame around them all, as Figma draws a selection (it moves with them) */+ const groupMarks = clipsMoved ?? (linkedShown.length > 1 ? linkedShown : null);+ const groupStretch = Boolean(groupMarks?.every((m) => infoOf(m.loc)?.kind === 'video'));+ const groupBox = groupMarks ? unionRect(groupMarks.map((m) => clientOf(frameAabb(visibleFrame(m.t, m.box, infoOf(m.loc)?.crop ?? NO_CROP))))) : null;/* the clip of a pill hovered in the app's chat, where it is drawn now */const chatClip = chat?.clipLoc ? clipInfo(doc, spans, stage, chat.clipLoc) : null;@@ -2086,7 +2342,27 @@ function FilmStageSelectImpl({if (barKind === 'layer') for (const id of ['edit-text', 'front', 'back', 'hide', 'reset']) fromMenu(id);if (barKind === 'clip') {if (heldEl?.clipKind === 'video' && onEditClip) tools.push({ id: 'crop', label: t('selectionBar.crop'), icon: <CropIcon size={14} />, shortcut: 'C', onSelect: () => { startCrop(); } });- if (onStartMask) tools.push({ id: 'mask', label: t('selectionBar.mask'), icon: <SquareDashed size={14} />, onSelect: onStartMask });+ if (onStartMask && heldEl?.clipLoc) {+ const clipLoc = heldEl.clipLoc;+ tools.push({+ id: 'mask', label: t('selectionBar.mask'), icon: <SquareDashed size={14} />,+ onSelect: (button) => {+ const r = button.getBoundingClientRect();+ const at = parseFilmDocLoc(clipLoc);+ const style = at ? docRef.current.tracks[at.track]?.clips[at.clip]?.style ?? '' : '';+ const box = heldEl?.mgBox ?? null;+ const now = maskOf(declared(style, 'mask-image'), declared(style, 'mask-composite'), box);+ const shapeNow = now === undefined ? 'none' : now?.shape ?? null;+ openMenuAt({ x: r.left, y: r.bottom + 4 }, (['none', ...MASK_SHAPES] as const).map((shape) => ({+ id: `mask-${shape}`,+ label: t(`inspector.maskShapes.${shape}`),+ icon: <MaskGlyph shape={shape} />,+ checked: shape === shapeNow,+ onSelect: () => onStartMask(shape, clipLoc),+ })));+ },+ });+ }fromMenu('reset');}if (barKind === 'layers') {@@ -2257,6 +2533,36 @@ function FilmStageSelectImpl({});return;}+ /* several clips selected: a press on one of them drags them all, as Figma moves a selection (Shift: a marquee+ that adds to them instead) */+ const linkedNow = linkedLocs ?? [];+ const groupHit = target?.closest('[data-group-kind]') as HTMLElement | null;+ if (linkedNow.length > 1 && groupBox && onEditClip && !e.shiftKey && !linkedNow.some((loc) => lockedClip(loc))+ && (groupHit || insideBox(groupBox, stagePt.x, stagePt.y))) {+ const items = linkedNow.flatMap((loc) => {+ const info = infoOf(loc);+ return info?.box ? [{ loc, id: info.id, t0: info.t, box: info.box }] : [];+ });+ const kind = groupHit?.getAttribute('data-group-kind');+ const handle = kind === 'scale' || kind === 'stretch' || kind === 'rotate' ? groupHit!.getAttribute('data-group-handle') : null;+ const g = groupBox;+ const mid = { x: g.left + g.width / 2, y: g.top + g.height / 2 };+ /* a corner or an edge's middle, on the side pulled (`far`: the opposite one, which stays) */+ const at = (h: string, far: boolean) => ({+ x: h.includes('e') || h.includes('w') ? g.left + (h.includes('e') !== far ? g.width : 0) : mid.x,+ y: h.includes('n') || h.includes('s') ? g.top + (h.includes('s') !== far ? g.height : 0) : mid.y,+ });+ const turning = kind === 'rotate';+ clipsDrag.current = {+ kind: turning ? 'rotate' : handle ? 'scale' : 'move', handle: turning ? null : handle,+ x: p.x, y: p.y, moved: false, items, dx: 0, dy: 0, kx: 1, ky: 1, turn: 0, box0: g,+ anchor: turning ? mid : handle ? at(handle, true) : { x: 0, y: 0 },+ from: handle && !turning ? at(handle, false) : { x: 0, y: 0 },+ a0: Math.atan2(stagePt.y - mid.y, stagePt.x - mid.x),+ };+ currentTarget.setPointerCapture(pointerId);+ return;+ }/* several selected: a press inside their box drags them all (Shift adds / takes away instead) */const many = multiRef.current;const held0 = pickedRef.current;@@ -2341,6 +2647,7 @@ function FilmStageSelectImpl({}/* a click or a marquee is decided at the release */currentTarget.setPointerCapture(pointerId);+ marqueeClips.current = onSelectClips ? ask<StageClipBox[]>('clips') : null;draftRef.current = { x1: p.x, y1: p.y, x2: p.x, y2: p.y };setDraft(draftRef.current);}}@@ -2367,6 +2674,36 @@ function FilmStageSelectImpl({return;}if (altHeld.current) measureAt(null);+ if (clipsDrag.current) {+ const d = clipsDrag.current;+ const p = local(e);+ const vs = viewScaleNow();+ if (!d.moved && Math.hypot(p.x - d.x, p.y - d.y) < 4) return;+ if (!d.moved) { d.moved = true; setDragging(true); setHover(null); }+ const at = { x: p.x / vs, y: p.y / vs };+ if (d.kind === 'move') {+ d.dx = (p.x - d.x) / vs;+ d.dy = (p.y - d.y) / vs;+ } else if (d.kind === 'rotate') {+ /* Shift: in steps of 15°, as a single clip turns */+ const turn = ((Math.atan2(at.y - d.anchor.y, at.x - d.anchor.x) - d.a0) * 180) / Math.PI;+ d.turn = e.shiftKey ? Math.round(turn / 15) * 15 : turn;+ setGroupTurn({ box: d.box0, turn: d.turn });+ } else {+ const ux = d.from.x - d.anchor.x, uy = d.from.y - d.anchor.y;+ const along = (v: number, u: number, a: number) => Math.max(0.02, (v - a) / (Math.abs(u) > 1e-6 ? u : 1e-6));+ if (d.handle && d.handle.length === 2) {+ /* a corner: along the frame's diagonal, both ways alike (a page is never stretched) */+ const k = Math.max(0.02, ((at.x - d.anchor.x) * ux + (at.y - d.anchor.y) * uy) / Math.max(1e-6, ux * ux + uy * uy));+ d.kx = d.ky = k;+ } else if (d.handle === 'e' || d.handle === 'w') d.kx = along(at.x, ux, d.anchor.x);+ else d.ky = along(at.y, uy, d.anchor.y);+ }+ const moved = d.items.map((it) => ({ loc: it.loc, box: it.box, t: groupDragged(d, it.t0, it.box) }));+ setClipsMoved(moved);+ clipsPlace.push(d.items.map((it, i) => ({ clip: it.id, box: compactBox(moved[i]!.t, it.box) })));+ return;+ }if (multiDrag.current) {const d = multiDrag.current;const p = local(e);@@ -2392,7 +2729,6 @@ function FilmStageSelectImpl({}return;}- if (!gestureRef.current && !draftRef.current && !hoverEnabled) return;moveAt.current = { cx: e.clientX, cy: e.clientY, shift: e.shiftKey, alt: e.altKey };if (!moveRaf.current) moveRaf.current = requestAnimationFrame(flushMove);}}@@ -2425,6 +2761,21 @@ function FilmStageSelectImpl({>{/* the clips selected elsewhere, under the selection: what is being moved is always on top */}{linkedShown.map((mark) => <MgOutline key={mark.loc} t={mark.t} box={mark.box} viewScale={vsNow} />)}+ {clipsMoved?.map((mark) => <MgOutline key={mark.loc} t={mark.t} box={mark.box} viewScale={vsNow} />)}+ {groupBox ? (() => {+ const g = groupTurn?.box ?? groupBox;+ return (+ <StageTransformFrame+ frame={{ cx: (g.left + g.width / 2) * vsNow, cy: (g.top + g.height / 2) * vsNow, w: g.width * vsNow, h: g.height * vsNow, r: groupTurn?.turn ?? 0 }}+ scope="group"+ /* sides stretch videos only: a page is never stretched, a still keeps its shape (as one in hand) */+ edges={groupStretch}+ moving={dragging}+ label={groupTurn ? `${Math.round(groupTurn.turn)}°` : `${Math.round(g.width)} × ${Math.round(g.height)}`}+ bounds={stageBounds}+ />+ );+ })() : null}{/* the menu is drawn on body, but React events bubble through the component tree: a press on an item must notreach the stage as a press on the picture */}{menu ? (@@ -2441,9 +2792,13 @@ function FilmStageSelectImpl({</div>) : null}{/* not on the layer in hand (it has its frame), not while drawing a marquee or dragging */}- {hover && hoverEnabled && !draftRect && !dragging && editingText == null && !(picked && hover.handle === picked.layer?.handle) ? (+ {hover && !draftRect && !dragging && editingText == null+ && !(picked && (hover.clip ? picked.element?.isMgOuter && hover.clip === picked.element.clipId : hover.handle === picked.layer?.handle)) ? (<Box rect={scaleBox(hover.rect, vsNow)} frame={hover.frame && scaleFrame(hover.frame, vsNow)} tone="hover" />) : null}+ {draftRect ? marqueeHits.map((h, i) => (+ <Box key={h.clip ?? `${h.handle}:${i}`} rect={scaleBox(h.rect, vsNow)} frame={h.frame && scaleFrame(h.frame, vsNow)} tone="hover" />+ )) : null}{draftRect ? <Box rect={draftRect} tone="draft" /> : null}{regionDraft ? <Box rect={boxOfDrag(regionDraft)} tone="region" /> : null}{flash ? <Box rect={scaleBox({ left: flash.box.x, top: flash.box.y, width: flash.box.w, height: flash.box.h }, vsNow)} tone="region" fading={flash.fading} /> : null}diff --git a/packages/openfilm/studio/ui/src/components/FramePicker.tsx b/packages/openfilm/studio/ui/src/components/FramePicker.tsxindex ffd8c13..7765f97 100644--- a/packages/openfilm/studio/ui/src/components/FramePicker.tsx+++ b/packages/openfilm/studio/ui/src/components/FramePicker.tsx@@ -30,8 +30,8 @@ export function canvasRatioLabel(t: (key: string) => string, item: { id: FilmFrareturn item.phone ? t('viewer.ratioPhone') : 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;+/** Whether the stage has this ratio: its width within 2 px of it (a size made from a ratio is rounded to even px). */+export const shaped = (stage: { w: number; h: number }, ratio: number) => Math.abs(stage.w - stage.h * ratio) <= 2;export function FramePicker({stage, original, busy, onCanvas,@@ -109,11 +109,14 @@ export function FramePicker({* 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 = '' }: {+export function CustomFrame({ value, disabled, onPick, className = '', chip = false }: {value: FilmFrameId;disabled?: boolean;onPick: (id: FilmFrameId) => void;className?: string;+ /** as one of a row of frame chips (the export dialog): the same height, border and corners, its fields capsules+ inside it with an even gap; else a menu's row */+ chip?: boolean;}) {const t = useT();const [w0, h0] = value === 'native' ? ['16', '9'] : value.split(':');@@ -121,10 +124,14 @@ export function CustomFrame({ value, disabled, onPick, className = '' }: {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)]';+ const field = chip+ ? 'h-6 w-9 rounded-full bg-[var(--fill-tsp)] text-center text-[12px] font-medium tabular-nums text-[var(--text)] outline-none ring-[var(--text-faint)] focus:ring-1'+ : '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>+ <div className={chip+ ? `flex items-center gap-1 rounded-lg border border-[var(--border)] py-[4px] pl-2.5 pr-[4px] ${className}`+ : `flex items-center gap-1.5 px-2 py-1 ${className}`}>+ <span className={chip ? 'mr-1 text-[12px] font-medium text-[var(--text-muted)]' : '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>@@ -132,7 +139,7 @@ export function CustomFrame({ value, disabled, onPick, className = '' }: {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">+ className={`flex h-6 w-6 items-center justify-center ${chip ? 'rounded-full' : 'rounded-[5px]'} text-[var(--text-muted)] transition hover:bg-[var(--bg-hover)] hover:text-[var(--text)] disabled:opacity-30`}><Check size={13} /></button></div>diff --git a/packages/openfilm/studio/ui/src/components/MediaPool.tsx b/packages/openfilm/studio/ui/src/components/MediaPool.tsxindex 0c1d04f..d219aa3 100644--- a/packages/openfilm/studio/ui/src/components/MediaPool.tsx+++ b/packages/openfilm/studio/ui/src/components/MediaPool.tsx@@ -6,7 +6,9 @@* drag files into them. Paths are not shown: Reveal in Finder and Copy path are on the right-click menu.** Click a file to see it: the viewer plays it and the inspector shows its facts (onSelectFile). Drag it to the- * timeline to use it. Moving or renaming a file also repoints the timeline's clips (the server does it in the same+ * timeline to use it. Several are picked as in Finder (⌘-click, ⇧-click, a box dragged over empty space, ⌘A), to move+ * them (dragged onto a folder, or Move to) or delete them together. Any kind of file can be imported; Studio previews+ * and plays only pictures, videos, sounds and pages. Moving or renaming a file also repoints the timeline's clips (the server does it in the same* step), so nothing goes missing.** The host owns the data and the changes: it passes the listing (`listing`), where pictures and sounds come from@@ -19,6 +21,12 @@ import {Clapperboard,Copy,Folder,+ ExternalLink,+ FolderInput,+ FolderSymlink,+ HardDriveDownload,+ Link2,+ Unlink,FolderOpen,FolderPlus,LayoutGrid,@@ -38,27 +46,34 @@ import { clearResourceDrag, setResourceDragData } from '@/lib/resource-drag';import { STUDIO_REF_TYPE, type StudioRef } from '@/lib/host';import {formatClipDuration,+ formatFileSize,mediaNameMatches,renameChangesKind,renamedPath,+ resourceKindOf,safeName,srcHitsAsset,type MediaListing,type MediaResult,type MediaSources,type WorkspaceResource,+ type WorkspaceResourceKind,+ type MediaLink,+ type MediaProxy,} from '@/lib/workspace-resources';import { ConfirmDialog } from './ConfirmDialog';import { ContextMenu, type ContextMenuEntry } from './ContextMenu';-import { MediaPreview } from './MediaPreview';+import { KIND_ICON, MediaPreview } from './MediaPreview';import { Tooltip } from './Tooltip';import { retryImage } from '@/lib/retry-image';+import { boxBetween, boxHits, boxPick, moveTargets, pickItem, type Box } from '@/lib/media-selection';+import { barLayout, type BarWords } from '@/lib/media-bar';-type Filter = 'all' | 'video' | 'image' | 'audio' | 'page';+type Filter = 'all' | 'video' | 'image' | 'audio' | 'page' | 'other';type SortKey = 'name' | 'time' | 'duration' | 'type';-const FILTERS: readonly Filter[] = ['all', 'video', 'image', 'audio', 'page'];+const FILTERS: readonly Filter[] = ['all', 'video', 'image', 'audio', 'page', 'other'];const SORTS: readonly SortKey[] = ['name', 'time', 'duration', 'type'];-/** A tile dragged inside the pane, to be moved into a folder. */+/** Tiles dragged inside the pane, to be moved into a folder: their paths, a line each (a name has no line break). */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);@@ -69,7 +84,6 @@ const OPEN_FOLDER = new Map<string, string>();const HIDDEN_DIRS = [/(^|\/)fonts?(\/|$)/i];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);/** `layout`: tiles in a grid, or rows of a list (name, length, kind). */@@ -88,6 +102,12 @@ function loadView(projectId: string): ViewState {type Item = { type: 'folder'; rel: string; name: string; count: number; covers: WorkspaceResource[] } | { type: 'file'; file: WorkspaceResource };+/** An import's progress, per file (its index in the import): 0..1, and where it landed once it is in. */+export type ImportProgress = (file: number, ratio: number, landed?: string) => void;+/** A file on its way in: a card of its own in the folder it goes to, its progress inside, until the listing has it. */+type Upload = { id: string; name: string; into: string; kind: WorkspaceResourceKind; ratio: number; preview?: string; landed?: string };+let uploadSeq = 0;+export interface MediaPoolProps {projectId: string;/** The project's media and pages; null while the first listing loads (the pane stays blank). */@@ -99,10 +119,11 @@ export interface MediaPoolProps {selectedPath?: string | null;onSelectFile: (file: WorkspaceResource | null) => void;/**- * Import files from the computer into `folder` (project-relative: `assets` or `assets/<sub>`), reporting progress- * 0..1 over all of them. Reject with an Error whose message the pane shows (else "Upload failed, please retry").+ * Import files from the computer into `folder` (project-relative: `assets` or `assets/<sub>`), reporting each file's+ * progress 0..1 and, once it is in, where it landed. Reject with an Error whose message the pane shows (else "Upload+ * failed, please retry").*/- onImport: (files: File[], folder: string, onProgress: (ratio: number) => void) => Promise<unknown>;+ onImport: (files: File[], folder: string, onProgress: ImportProgress) => Promise<unknown>;/** Rename or move a file or folder (project-relative `from` → `to`); its clips follow. */onMove: (from: string, to: string) => Promise<MediaResult>;/**@@ -118,8 +139,21 @@ export interface MediaPoolProps {onNewFolder: (path: string) => Promise<MediaResult>;/** Before deleting files, take their clips off the timeline. A string is the reason it could not. */onDropClips?: (paths: readonly string[]) => Promise<string | null>;- /** Show a file or folder in Finder (project-relative). Missing: the menu has no Reveal in Finder. */- onReveal?: (path: string) => void;+ /**+ * Show a file or folder in Finder (project-relative; `original`: where a linked one is kept). Missing: the menu has+ * no Reveal in Finder.+ */+ onReveal?: (path: string, original?: boolean) => void;+ /**+ * Media kept on this computer, picked in the system's dialog: files, or a folder (`'no-dialog'` where there is+ * none), then copied into `folder` (cloned where the disk can) or linked where it is kept, a NAS or another disk+ * (`onBring`, resolving where each landed). Without them, Upload sends files picked in the browser.+ */+ onPick?: (title: string, folder: boolean) => Promise<string[] | 'no-dialog'>;+ onBring?: (paths: string[], folder: string, mode: 'copy' | 'link') => Promise<string[]>;+ /** A link pointed at where its media is now (the person picks it), or copied into the project in its place. */+ onRelink?: (path: string, folder: boolean) => Promise<MediaResult>;+ onCollect?: (path: string) => Promise<MediaResult>;/** Where the pool is a drawer the person opened (a host app's panel, see lib/host.ts): its close button, last in the bar. */onClose?: () => void;/**@@ -133,8 +167,8 @@ export interface MediaPoolProps {/** The file a pill hovered in the app's chat points at: its tile lit while it is. */litPath?: string | null;/**- * Put a file on the timeline, at the playhead on the targeted track or at the end of the main one (the tile's "+",- * Enter on the file picked). Without it there is no "+".+ * Put a file on the timeline, at the playhead on the targeted track or at the end of the main one (Enter on the file+ * picked; dragging it there is the usual way).*/onAdd?: (file: WorkspaceResource) => void;}@@ -154,6 +188,10 @@ export function MediaPool({onNewFolder,onDropClips,onReveal,+ onPick,+ onBring,+ onRelink,+ onCollect,onClose,fileRef,onRefer,@@ -167,45 +205,54 @@ export function MediaPool({const [at, setAtState] = React.useState(() => OPEN_FOLDER.get(projectId) ?? '');const setAt = React.useCallback((rel: string) => { OPEN_FOLDER.set(projectId, rel); setAtState(rel); }, [projectId]);const [query, setQuery] = React.useState('');- const [selectedFolder, setSelectedFolder] = React.useState<string | null>(null);+ /** What is picked: files and folders by their project-relative path (lib/media-selection). */+ const [picked, setPicked] = React.useState<string[]>(() => (selectedPath ? [selectedPath] : []));+ /** The one clicked last: where a ⇧-click's run starts. */+ const anchor = React.useRef<string | null>(selectedPath ?? null);const [renaming, setRenaming] = React.useState<string | null>(null);const [creating, setCreating] = React.useState(false);const [menu, setMenu] = React.useState<{ x: number; y: number; flipTo?: number; items: ContextMenuEntry[]; dense?: boolean } | null>(null);- const [confirm, setConfirm] = React.useState<{ path: string; name: string; folder: boolean } | null>(null);- const [importing, setImporting] = React.useState<{ count: number; ratio: number } | null>(null);+ const [confirm, setConfirm] = React.useState<{ targets: { path: string; folder: boolean }[]; name: string } | null>(null);+ const [uploads, setUploads] = React.useState<Upload[]>([]);const [notice, setNotice] = React.useState<string | null>(null);const [dropTarget, setDropTarget] = React.useState<string | null>(null);const [osDrag, setOsDrag] = React.useState(false);const inputRef = React.useRef<HTMLInputElement>(null);- React.useEffect(() => { setView(loadView(projectId)); setAtState(OPEN_FOLDER.get(projectId) ?? ''); }, [projectId]);+ React.useEffect(() => { setView(loadView(projectId)); setAtState(OPEN_FOLDER.get(projectId) ?? ''); setPicked([]); }, [projectId]);+ /* the file the viewer shows is the host's: the one clicked last, when it is a file. One shown from elsewhere (a click+ on the timeline let it go, the chat pointed at one) is then all that is picked */+ const sentPath = React.useRef(selectedPath ?? null);+ const showFile = React.useCallback((file: WorkspaceResource | null) => {+ sentPath.current = file?.path ?? null;+ onSelectFile(file);+ }, [onSelectFile]);+ React.useEffect(() => {+ if ((selectedPath ?? null) === sentPath.current) return;+ sentPath.current = selectedPath ?? null;+ setPicked(selectedPath ? [selectedPath] : []);+ anchor.current = selectedPath ?? null;+ }, [selectedPath]);React.useEffect(() => {try { window.localStorage.setItem(viewKey(projectId), JSON.stringify(view)); } catch { /* per-viewer only */ }}, [projectId, view]);const root = media?.dir ?? 'assets';const assetRel = React.useCallback((path: string) => (path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path), [root]);+ /** Under assets/ (not one of the project's own pages, which are shown at the top). */+ const inMedia = React.useCallback((path: string) => path.startsWith(`${root}/`), [root]);const relDir = (rel: string) => (rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '');const allFiles = React.useMemo(() => {if (!media) return null;- const files = media.files.filter((f) => isMedia(f) && !hiddenDir(relDir(assetRel(f.path))));+ /* every file, of any kind: a document or a model is material too (the agent can make a film of it); Studio+ plays and previews only pictures, videos, sounds and pages */+ const files = media.files.filter((f) => !hiddenDir(relDir(assetRel(f.path))));return [...media.pages, ...files];}, [media, assetRel]);- /* a folder shows when it holds media, when the person made it, or when it is empty (made in Finder, or by an agent,- to be filled): only one holding nothing but other files (a tool's data) stays out of the way */- const folders = React.useMemo(() => {- if (!media) return [];- const made = media.made ? new Set(media.made) : null;- const under = (dir: string) => media.files.filter((f) => assetRel(f.path).startsWith(`${dir}/`));- return media.dirs.filter((dir) => {- if (hiddenDir(dir)) return false;- if (!made || [...made].some((m) => m === dir || m.startsWith(`${dir}/`))) return true;- const files = under(dir);- return !files.length || files.some((f) => isMedia(f) && !hiddenDir(relDir(assetRel(f.path))));- });- }, [media, assetRel]);+ /* every folder under assets/ but a tool's (fonts) */+ const folders = React.useMemo(() => (media ? media.dirs.filter((dir) => !hiddenDir(dir)) : []), [media]);const items = React.useMemo((): Item[] | null => {if (!allFiles) return null;@@ -222,21 +269,22 @@ export function MediaPool({.filter((f) => (view.filter === 'all' || filterOf(f) === view.filter) && mediaNameMatches(f.name, q)).sort(order).map((file) => ({ type: 'file', file }));}- const here = allFiles.filter((f) => (f.kind === 'mg' ? at === '' : relDir(assetRel(f.path)) === at)).sort(order);+ /* the project's pages are at the top; a page put in a folder is in its folder */+ const here = allFiles.filter((f) => (inMedia(f.path) ? relDir(assetRel(f.path)) === at : at === '')).sort(order);const sub = folders.filter((dir) => relDir(dir) === at).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).map((rel) => ({type: 'folder' as const, rel, name: rel.split('/').pop()!,- count: allFiles.filter((f) => f.kind !== 'mg' && assetRel(f.path).startsWith(`${rel}/`)).length,+ count: allFiles.filter((f) => inMedia(f.path) && assetRel(f.path).startsWith(`${rel}/`)).length,/* what the folder holds, on its cover: pictures first (they say the most), sounds after */covers: allFiles- .filter((f) => f.kind !== 'mg' && assetRel(f.path).startsWith(`${rel}/`))+ .filter((f) => inMedia(f.path) && assetRel(f.path).startsWith(`${rel}/`)).sort((a, b) => Number(a.kind === 'audio') - Number(b.kind === 'audio') || a.name.localeCompare(b.name, undefined, { numeric: true })).slice(0, 4),}));return [...sub, ...here.map((file) => ({ type: 'file' as const, file }))];- }, [allFiles, folders, at, query, view, assetRel]);+ }, [allFiles, folders, at, query, view, assetRel, inMedia]);/* a file asked to be shown: its folder opened (pages are at the top), a search or a filter that hides it let go */const gridRef = React.useRef<HTMLDivElement>(null);@@ -246,7 +294,7 @@ export function MediaPool({if (!file) return undefined;setQuery('');setView((v) => (v.filter === 'all' || v.filter === filterOf(file) ? v : { ...v, filter: 'all' }));- setAt(file.kind === 'mg' ? '' : relDir(assetRel(file.path)));+ setAt(inMedia(file.path) ? relDir(assetRel(file.path)) : '');const frame = requestAnimationFrame(() => {gridRef.current?.querySelector(`[data-media-path="${CSS.escape(file.path)}"]`)?.scrollIntoView({ block: 'nearest' });});@@ -260,49 +308,143 @@ export function MediaPool({}, [at, media, setAt]);const folderPath = (rel: string) => (rel ? `${root}/${rel}` : root);+ const keyOf = React.useCallback((item: Item) => (item.type === 'folder' ? `${root}/${item.rel}` : item.file.path), [root]);+ /* the items as shown, by key: a ⇧-click's run goes along them */+ const order = React.useMemo(() => (items ?? []).map(keyOf), [items, keyOf]);+ const itemByKey = React.useMemo(() => new Map((items ?? []).map((item) => [keyOf(item), item])), [items, keyOf]);+ /* what is picked and shown: a search or another folder hides the rest, and what is hidden is not acted on */+ const chosen = React.useMemo(() => picked.filter((key) => itemByKey.has(key)), [picked, itemByKey]);+ /** The folder an item is in ('' the top, where the pages are shown). */+ const hereOf = (key: string) => (key.startsWith(`${root}/`) ? relDir(assetRel(key)) : '');const importFiles = async (list: File[], intoRel = at) => {if (!list.length) return;setNotice(null);- setImporting({ count: list.length, ratio: 0 });+ /* a card each, at once, where it goes: a picture shows itself while it is sent */+ const batch: Upload[] = list.map((file) => {+ const kind = resourceKindOf(file.name);+ return { id: `upload-${++uploadSeq}`, name: file.name, into: intoRel, kind, ratio: 0, ...(kind === 'image' ? { preview: URL.createObjectURL(file) } : {}) };+ });+ setUploads((all) => [...all, ...batch]);try {/* 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 }));+ await onImport(list, folderPath(intoRel), (i, ratio, landed) => {+ const id = batch[i]?.id;+ setUploads((all) => all.map((u) => (u.id === id ? { ...u, ratio, ...(landed ? { landed } : {}) } : u)));+ });} catch (e) {setNotice(e instanceof Error && e.message ? e.message : t('assets.uploadFailed'));- } finally {- setImporting(null);+ /* what did not get in goes; what did stays until the listing has it */+ dropUploads((u) => batch.some((b) => b.id === u.id) && !u.landed);}};+ /**+ * Media on this computer, picked in the system's dialog, copied in or linked where it is kept (a NAS): a card each+ * while it comes. Where there is no dialog, an import is the browser's pick.+ */+ const bringFrom = async (mode: 'copy' | 'link', folder: boolean, intoRel = at) => {+ if (!onPick || !onBring) { inputRef.current?.click(); return; }+ setNotice(null);+ const paths = await onPick(t(mode === 'copy' ? 'media.pickImport' : folder ? 'media.pickLinkFolder' : 'media.pickLink'), folder);+ if (paths === 'no-dialog') { if (mode === 'copy' && !folder) inputRef.current?.click(); else setNotice(t('media.noDialog')); return; }+ const batch: Upload[] = paths.map((path) => {+ const name = path.split(/[\\/]/).filter(Boolean).pop() ?? path;+ return { id: `upload-${++uploadSeq}`, name, into: intoRel, kind: folder ? 'other' : resourceKindOf(name), ratio: -1 };+ });+ setUploads((all) => [...all, ...batch]);+ for (const [i, path] of paths.entries()) {+ const id = batch[i]!.id;+ try {+ // eslint-disable-next-line no-await-in-loop+ const [landed] = await onBring([path], folderPath(intoRel), mode);+ setUploads((all) => all.map((u) => (u.id === id ? { ...u, ratio: 1, ...(landed ? { landed } : {}) } : u)));+ } catch (e) {+ setNotice(e instanceof Error && e.message ? e.message : t('assets.uploadFailed'));+ dropUploads((u) => u.id === id);+ }+ }+ };+ /** Take cards away (a picture's preview let go with them). */+ const dropUploads = React.useCallback((gone: (u: Upload) => boolean) => {+ setUploads((all) => {+ if (!all.some(gone)) return all;+ for (const u of all) if (gone(u) && u.preview) URL.revokeObjectURL(u.preview);+ return all.filter((u) => !gone(u));+ });+ }, []);+ /* a card gives way to the file once the listing has it (or a while after it landed, if it never shows here) */+ React.useEffect(() => {+ if (!media) return;+ const have = new Set([...media.files.map((f) => f.path), ...media.dirs.map((d) => `${media.dir}/${d}`)]);+ dropUploads((u) => Boolean(u.landed && have.has(u.landed)));+ }, [media, dropUploads]);+ const landedCount = uploads.filter((u) => u.landed).length;+ React.useEffect(() => {+ if (!landedCount) return undefined;+ const timer = window.setTimeout(() => dropUploads((u) => Boolean(u.landed)), 5000);+ return () => window.clearTimeout(timer);+ }, [landedCount, dropUploads]);+ const uploadsRef = React.useRef(uploads);+ uploadsRef.current = uploads;+ React.useEffect(() => () => { for (const u of uploadsRef.current) if (u.preview) URL.revokeObjectURL(u.preview); }, []);+ /** Files on their way into a folder or one inside it: their progress together, for its cover. */+ const progressInto = (rel: string) => {+ const going = uploads.filter((u) => u.into === rel || u.into.startsWith(`${rel}/`));+ return going.length ? going.reduce((sum, u) => sum + Math.max(0, u.ratio), 0) / going.length : undefined;+ };/* 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 [moveAsk, setMoveAsk] = React.useState<{ paths: string[]; intoRel: string; unseen: { file: string; unseen: string[] }[] } | null>(null);+ /** Move files and folders into a folder (`intoRel` under assets/, '' its top), one after another. */+ const moveAll = async (paths: readonly string[], intoRel: string, asked = false) => {const into = folderPath(intoRel);- if (relDir(path) === into) return;- const name = path.slice(path.lastIndexOf('/') + 1);+ const nameOf = (path: string) => path.slice(path.lastIndexOf('/') + 1);+ /* what is there already stays, and a folder never goes into itself */+ const going = paths.filter((path) => hereOf(path) !== intoRel && into !== path && !into.startsWith(`${path}/`));+ if (!going.length) return;if (!asked && onMoveCheck) {- const unseen = await onMoveCheck(path, `${into}/${name}`).catch(() => []);- if (unseen.length) { setMoveAsk({ path, intoRel, unseen }); return; }+ const unseen = (await Promise.all(going.map((path) => onMoveCheck(path, `${into}/${nameOf(path)}`).catch(() => [])))).flat();+ if (unseen.length) { setMoveAsk({ paths: going, 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 (selectedRef.current === path) onSelectFile(null);+ const moved: string[] = [];+ let taken: string | null = null;+ let failed = false;+ for (const path of going) {+ // eslint-disable-next-line no-await-in-loop+ const result = await onMove(path, `${into}/${nameOf(path)}`);+ if (result === 'ok') moved.push(path);+ else if (result === 'taken') taken ??= nameOf(path);+ else failed = true;+ }+ if (taken) setNotice(t('media.moveTaken').replace('{name}', taken).replace('{folder}', intoRel ? intoRel.split('/').pop()! : t('media.filter_all')));+ else if (failed) setNotice(t('media.moveFailed'));+ if (selectedRef.current && moved.includes(selectedRef.current)) showFile(null);+ setPicked((cur) => cur.filter((key) => !moved.includes(key)));};- const remove = async (target: { path: string; folder: boolean }) => {- const gone = target.folder+ const remove = async (targets: readonly { path: string; folder: boolean }[]) => {+ const gone = targets.flatMap((target) => (target.folder? (media?.files ?? []).filter((f) => f.path.startsWith(`${target.path}/`)).map((f) => f.path)- : [target.path];+ : [target.path]));const dropped = await onDropClips?.(gone);if (dropped) { setNotice(dropped); return; }- const result = await onDelete(target.path);- if (result !== 'ok') setNotice(t('assets.deleteFailed'));- if (selectedPath && gone.includes(selectedPath)) onSelectFile(null);+ let failed = false;+ for (const target of targets) {+ // eslint-disable-next-line no-await-in-loop+ if (await onDelete(target.path) !== 'ok') failed = true;+ }+ if (failed) setNotice(t('assets.deleteFailed'));+ if (selectedPath && gone.includes(selectedPath)) showFile(null);+ setPicked((cur) => cur.filter((key) => !targets.some((target) => target.path === key)));+ };+ /** Ask to delete these (picked) items. */+ const askDelete = (keys: readonly string[]) => {+ const targets = keys.flatMap((key) => { const item = itemByKey.get(key); return item ? [{ path: key, folder: item.type === 'folder' }] : []; });+ const first = targets[0] ? itemByKey.get(targets[0].path) : undefined;+ if (first) setConfirm({ targets, name: first.type === 'folder' ? first.name : first.file.name });};const rename = async (path: string, name: string, folder: boolean) => {@@ -316,7 +458,7 @@ export function MediaPool({}const result = await onMove(path, to);if (result !== 'ok') setNotice(t(result === 'taken' ? 'assets.renameTaken' : 'assets.renameFailed'));- else if (selectedPath === path) onSelectFile(null);+ else if (selectedPath === path) showFile(null);};/* a folder just named stays where it was typed until the listing has it: no blink between Enter and the refresh */@@ -345,6 +487,49 @@ export function MediaPool({...(onReveal ? [{ id: 'reveal', label: t('projects.revealFolder'), icon: <FolderOpen size={14} />, onSelect: () => onReveal(path) }] : []),{ id: 'copy', label: t('media.copyPath'), icon: <Copy size={14} />, onSelect: () => { void navigator.clipboard?.writeText(path).catch(() => {}); } },];+ /** What to say of a proxy. */+ const proxyText = (proxy: MediaProxy) => (proxy.state === 'making' ? t('media.proxyMaking').replace('{p}', String(Math.round((proxy.ratio ?? 0) * 100)))+ : proxy.state === 'waiting' ? t('media.proxyWaiting') : proxy.state === 'failed' ? t('media.proxyFailed') : t('media.proxyReady'));+ /** Where a file or folder is linked from (a NAS), if it is a link. */+ const linkOf = (key: string): MediaLink | undefined => {+ const item = itemByKey.get(key);+ return item?.type === 'file' ? item.file.link : item ? media?.linkedDirs?.[item.rel] : undefined;+ };+ /** Copy what links lead to into the project in their place, one after another. */+ const collectAll = async (keys: readonly string[]) => {+ if (!onCollect) return;+ for (const key of keys) {+ // eslint-disable-next-line no-await-in-loop+ if (await onCollect(key) !== 'ok') { setNotice(t('media.collectFailed')); return; }+ }+ };+ /* a link's own: where it is kept, pointed at where that is now, or copied into the project */+ const linkEntries = (key: string, folder: boolean): ContextMenuEntry[] => {+ const link = linkOf(key);+ if (!link) return [];+ return [+ ...(onReveal && !link.missing ? [{ id: 'reveal-original', label: t('media.revealOriginal'), icon: <ExternalLink size={14} />, onSelect: () => onReveal(key, true) }] : []),+ ...(onRelink ? [{ id: 'relink', label: t('media.relink'), icon: <Link2 size={14} />, onSelect: () => { void onRelink(key, folder).then((r) => { if (r !== 'ok') setNotice(t('media.relinkFailed')); }); } }] : []),+ ...(onCollect && !link.missing ? [{ id: 'collect', label: t('media.collect'), note: t('media.collectNote'), icon: <HardDriveDownload size={14} />, onSelect: () => { void collectAll([key]); } }] : []),+ { id: 'link-sep', separator: true } as const,+ ];+ };+ /** Move to: the top or any folder, the one they are all in checked (they are there already). */+ const moveEntry = (keys: readonly string[]): ContextMenuEntry => {+ const heres = new Set(keys.map(hereOf));+ const moving = keys.filter((key) => itemByKey.get(key)?.type === 'folder').map(assetRel);+ return {+ id: 'move-to', label: t('media.moveTo'), icon: <FolderInput size={14} />,+ submenu: moveTargets(folders, moving).map((rel) => {+ const here = heres.size === 1 && heres.has(rel);+ return {+ id: `move:${rel}`, label: rel ? rel.split('/').join(' / ') : t('media.filter_all'), checked: here, disabled: here,+ ...(here ? { hint: t('media.moveHere') } : {}),+ onSelect: () => { void moveAll(keys, rel); },+ };+ }),+ };+ };const fileMenu = (file: WorkspaceResource): ContextMenuEntry[] => [...(fileRef && onRefer ? [{ id: 'refer', label: t('host.refer'), icon: <MessageSquarePlus size={14} />, onSelect: () => onRefer(fileRef(file)) },@@ -352,6 +537,7 @@ export function MediaPool({] : []),...commonEntries(file.path),{ id: 'sep', separator: true } as const,+ ...linkEntries(file.path, false),/* web pages are the film's code, written by the person's agent (and named in each other's code): not renamedhere; any file can be deleted, to the Trash, its clips with it */...(file.kind === 'video' && onExtractAudio ? [{@@ -359,24 +545,170 @@ export function MediaPool({onSelect: () => { void onExtractAudio(file.path).then((r) => { if (r !== 'ok') setNotice(t('assets.extractAudioFailed')); }); },}] : []),...(file.kind === 'mg' ? [] : [{ id: 'rename', label: t('assets.rename'), icon: <Pencil size={14} />, onSelect: () => setRenaming(file.path) }]),- { id: 'delete', label: t('assets.delete'), icon: <Trash2 size={14} />, danger: true, onSelect: () => setConfirm({ path: file.path, name: file.name, folder: false }) },+ moveEntry([file.path]),+ { id: 'delete', label: t('assets.delete'), icon: <Trash2 size={14} />, danger: true, onSelect: () => setConfirm({ targets: [{ path: file.path, folder: false }], name: file.name }) },];const folderMenu = (rel: string, name: string): ContextMenuEntry[] => [...commonEntries(`${root}/${rel}`),{ id: 'sep', separator: true },+ ...linkEntries(`${root}/${rel}`, true),{ id: 'rename', label: t('assets.rename'), icon: <Pencil size={14} />, onSelect: () => setRenaming(`${root}/${rel}`) },- { id: 'delete', label: t('assets.delete'), icon: <Trash2 size={14} />, danger: true, onSelect: () => setConfirm({ path: `${root}/${rel}`, name, folder: true }) },+ moveEntry([`${root}/${rel}`]),+ { id: 'delete', label: t('assets.delete'), icon: <Trash2 size={14} />, danger: true, onSelect: () => setConfirm({ targets: [{ path: `${root}/${rel}`, folder: true }], name }) },+ ];+ /** Several picked: what can be done to all of them at once. */+ const manyMenu = (keys: readonly string[]): ContextMenuEntry[] => [+ ...(onCollect && keys.some((key) => linkOf(key) && !linkOf(key)!.missing) ? [{+ id: 'collect', label: t('media.collect'), note: t('media.collectNote'), icon: <HardDriveDownload size={14} />,+ onSelect: () => { void collectAll(keys.filter((key) => linkOf(key) && !linkOf(key)!.missing)); },+ }] : []),+ moveEntry(keys),+ { id: 'sep', separator: true },+ { id: 'delete', label: t('media.deleteMany').replace('{n}', String(keys.length)), icon: <Trash2 size={14} />, danger: true, onSelect: () => askDelete(keys) },+ ];+ /* what Upload offers: a copy in the project, or a link to where the media is kept (a NAS, another disk) */+ const importMenu: ContextMenuEntry[] = [+ { id: 'import', label: t('media.importFiles'), note: t('media.importFilesNote'), icon: <Upload size={14} />, onSelect: () => { void bringFrom('copy', false); } },+ { id: 'link', label: t('media.linkFiles'), note: t('media.linkFilesNote'), icon: <Link2 size={14} />, onSelect: () => { void bringFrom('link', false); } },+ { id: 'link-folder', label: t('media.linkFolder'), icon: <FolderSymlink size={14} />, onSelect: () => { void bringFrom('link', true); } },];const blankMenu: ContextMenuEntry[] = [{ id: 'new-folder', label: t('assets.newFolder'), icon: <FolderPlus size={14} />, onSelect: () => setCreating(true) },- { id: 'import', label: t('media.import'), icon: <Plus size={14} />, onSelect: () => inputRef.current?.click() },+ { id: 'import', label: t('media.import'), icon: <Plus size={14} />, onSelect: () => (onPick && onBring ? void bringFrom('copy', false) : inputRef.current?.click()) },+ ...(onPick && onBring ? [+ { id: 'link', label: t('media.linkFiles'), icon: <Link2 size={14} />, onSelect: () => { void bringFrom('link', false); } },+ { id: 'link-folder', label: t('media.linkFolder'), icon: <FolderSymlink size={14} />, onSelect: () => { void bringFrom('link', true); } },+ ] : []),];- const openMenuAt = (e: { clientX: number; clientY: number }, items: ContextMenuEntry[], dense?: boolean) => setMenu({ x: e.clientX, y: e.clientY, items, dense });- const barMenu = (e: React.MouseEvent, items: ContextMenuEntry[]) => {- const r = e.currentTarget.getBoundingClientRect();+ /** The bar button a menu hangs from: a press on it is not outside the menu, and a click on it closes the menu. */+ const menuFrom = React.useRef<HTMLElement | null>(null);+ const openMenuAt = (e: { clientX: number; clientY: number }, items: ContextMenuEntry[], dense?: boolean) => {+ menuFrom.current = null;+ setMenu({ x: e.clientX, y: e.clientY, items, dense });+ };++ /* a click picks (lib/media-selection pickItem); the viewer shows the file clicked while it is picked, else the film */+ const press = (item: Item, e?: { metaKey: boolean; ctrlKey: boolean; shiftKey: boolean }) => {+ const key = keyOf(item);+ const mods = { toggle: Boolean(e && (e.metaKey || e.ctrlKey)), range: Boolean(e?.shiftKey) };+ const next = pickItem(chosen, key, order, anchor.current, mods);+ if (!mods.range) anchor.current = key;+ setPicked(next);+ showFile(item.type === 'file' && next.includes(key) ? item.file : null);+ /* the keys are the pane's now (Delete, ⌘A), whatever was clicked */+ if (!gridRef.current?.contains(document.activeElement)) gridRef.current?.focus({ preventScroll: true });+ };+ /* a right-click on one of several picked is about all of them; on anything else, about it alone */+ const menuFor = (item: Item, e: React.MouseEvent) => {+ const key = keyOf(item);+ if (chosen.length > 1 && chosen.includes(key)) { openMenuAt(e, manyMenu(chosen)); return; }+ press(item);+ openMenuAt(e, item.type === 'folder' ? folderMenu(item.rel, item.name) : fileMenu(item.file));+ };+ /** What a drag of this item moves: every one picked when it is one of them. */+ const dragKeys = (key: string) => (chosen.length > 1 && chosen.includes(key) ? chosen : [key]);++ /* a box dragged over empty space picks what it touches (lib/media-selection); held near the top or bottom, the pane+ scrolls on under it */+ const [marquee, setMarquee] = React.useState<Box | null>(null);+ /** The click that ends a box is not a click on empty space (which lets go of what is picked). */+ const boxed = React.useRef(false);+ const startBox = (e: React.PointerEvent<HTMLDivElement>) => {+ boxed.current = false;+ const grid = e.currentTarget;+ const r0 = grid.getBoundingClientRect();+ if (e.button !== 0 || e.clientX - r0.left >= grid.clientWidth) return;+ if ((e.target as Element).closest('[data-media-path], [data-media-folder], [data-media-new-folder], [data-media-upload], button, input')) return;+ /* no text selected as it goes; the keys are the pane's */+ e.preventDefault();+ grid.focus({ preventScroll: true });+ const at = (x: number, y: number) => { const r = grid.getBoundingClientRect(); return { x: x - r.left + grid.scrollLeft, y: y - r.top + grid.scrollTop }; };+ const start = at(e.clientX, e.clientY);+ const add = e.metaKey || e.ctrlKey || e.shiftKey;+ const before = add ? chosen : [];+ const byKey = itemByKey;+ let pointer = { x: e.clientX, y: e.clientY };+ let live = false;+ let hits: string[] = before;+ const tiles = () => [...grid.querySelectorAll<HTMLElement>('[data-media-key]')].map((el) => {+ const r = el.getBoundingClientRect();+ const o = at(r.left, r.top);+ return { key: el.dataset.mediaKey!, box: { left: o.x, top: o.y, right: o.x + r.width, bottom: o.y + r.height } };+ });+ const update = () => {+ const now = at(pointer.x, pointer.y);+ if (!live && Math.hypot(now.x - start.x, now.y - start.y) < 4) return;+ live = true;+ const box = boxBetween(start, now);+ setMarquee(box);+ hits = boxPick(before, boxHits(tiles(), box), add);+ setPicked(hits);+ };+ let frame = 0;+ const tick = () => {+ const r = grid.getBoundingClientRect();+ const dy = pointer.y < r.top + 24 ? -Math.min(20, Math.ceil((r.top + 24 - pointer.y) / 3))+ : pointer.y > r.bottom - 24 ? Math.min(20, Math.ceil((pointer.y - r.bottom + 24) / 3)) : 0;+ if (live && dy) { grid.scrollTop += dy; update(); }+ frame = requestAnimationFrame(tick);+ };+ frame = requestAnimationFrame(tick);+ const move = (ev: PointerEvent) => { pointer = { x: ev.clientX, y: ev.clientY }; update(); };+ const end = () => {+ cancelAnimationFrame(frame);+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', end);+ window.removeEventListener('pointercancel', end);+ setMarquee(null);+ if (!live) return;+ boxed.current = true;+ anchor.current = hits.at(-1) ?? null;+ const only = hits.length === 1 ? byKey.get(hits[0]!) : undefined;+ showFile(only?.type === 'file' ? only.file : null);+ };+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', end);+ window.addEventListener('pointercancel', end);+ };+ const barMenu = (e: React.MouseEvent<HTMLElement>, items: ContextMenuEntry[]) => {+ const from = e.currentTarget;+ if (menu && menuFrom.current === from) { setMenu(null); menuFrom.current = null; return; }+ menuFrom.current = from;+ const r = from.getBoundingClientRect();setMenu({ x: r.left, y: r.bottom + 4, flipTo: r.top - 4, items, dense: true });};+ /* the bar at the pane's width (the whole pane is measured: the bar's own padding changes with it) */+ /* a callback ref: watched from when the element is there, however late it comes */+ const [rootEl, setRootEl] = React.useState<HTMLDivElement | null>(null);+ const [paneWidth, setPaneWidth] = React.useState(0);+ React.useEffect(() => {+ if (!rootEl || typeof ResizeObserver === 'undefined') return undefined;+ const ro = new ResizeObserver(([entry]) => setPaneWidth(Math.round(entry?.contentRect.width ?? 0)));+ ro.observe(rootEl);+ return () => ro.disconnect();+ }, [rootEl]);+ /* what the bar's words measure in this language and font (again once the fonts have loaded) */+ const [fontsTick, setFontsTick] = React.useState(0);+ React.useEffect(() => { void document.fonts?.ready.then(() => setFontsTick((n) => n + 1)); }, []);+ const hint = t('media.searchShort');+ const uploadWord = t('media.upload');+ const words = React.useMemo((): BarWords | null => {+ const ctx = typeof document === 'undefined' ? null : document.createElement('canvas').getContext('2d');+ if (!rootEl || !ctx) return null;+ const family = getComputedStyle(rootEl).fontFamily;+ const measure = (text: string, weight: number) => { ctx.font = `${weight} 12.5px ${family}`; return ctx.measureText(text).width; };+ return { hint: measure(hint, 400), upload: measure(uploadWord, 500) };+ }, [hint, uploadWord, fontsTick, rootEl]);+ /* the fullest bar that fits (lib/media-bar); before the pane is measured, the full one */+ const bar = paneWidth > 0 && words+ ? barLayout(paneWidth, words, 4 + (onClose ? 1 : 0), Boolean(query))+ : { field: true, uploadWord: true, tight: false, cramped: false };+ const tight = bar.tight;+ const [searchOpen, setSearchOpen] = React.useState(false);+ /* a search opened (from the button, or a field too short to type in) is over the bar; one typed stays open */+ const searching = bar.cramped && (searchOpen || Boolean(query));+const crumbs = at ? at.split('/') : [];const flat = Boolean(query.trim()) || view.filter !== 'all';const rows = view.layout === 'list';@@ -404,10 +736,10 @@ export function MediaPool({setDropTarget((cur) => (cur === intoRel ? null : cur));},onDrop: (e: React.DragEvent) => {- const path = e.dataTransfer.getData(FOLDER_DRAG);- if (path) {+ const paths = e.dataTransfer.getData(FOLDER_DRAG);+ if (paths) {e.preventDefault(); e.stopPropagation(); setDropTarget(null);- void moveInto(path, intoRel);+ void moveAll(paths.split('\n').filter(Boolean), intoRel);return;}if (!fromComputer(e.dataTransfer) || !e.dataTransfer.files.length) return;@@ -417,32 +749,41 @@ export function MediaPool({});const counts = React.useMemo(() => {- const out: Record<Filter, number> = { all: 0, video: 0, image: 0, audio: 0, page: 0 };+ const out: Record<Filter, number> = { all: 0, video: 0, image: 0, audio: 0, page: 0, other: 0 };for (const f of allFiles ?? []) { out.all += 1; out[filterOf(f)] += 1; }return out;}, [allFiles]);return (<div+ ref={setRootEl}className="relative flex h-full min-h-0 flex-col"- /* Delete (or Backspace) on the file picked here asks to delete it, as an editor's project panel does; only while- the keys are the pane's (the timeline's Delete is the timeline's) */+ /* the pane's keys, while they are its own (the timeline's Delete is the timeline's): Delete (or Backspace) asks to+ delete what is picked, as an editor's project panel does; Enter puts the one file picked on the timeline, as+ its "+" does; ⌘A picks everything shown; Esc lets go */onKeyDown={(e) => {- if (!selectedPath || renaming || confirm) return;+ if (renaming || confirm) return;if ((e.target as HTMLElement).closest('input, textarea, [contenteditable="true"], button')) return;- const file = allFiles?.find((f) => f.path === selectedPath);- if (!file) return;- /* Enter puts the file picked on the timeline, as its "+" does */- if (e.key === 'Enter' && onAdd && !e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey && canAdd(file)) {+ const plain = !e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey;+ if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'a' && order.length) {e.preventDefault();e.stopPropagation();- onAdd(file);+ setPicked(order);+ return;+ }+ if (!chosen.length) return;+ if (e.key === 'Escape' && plain) { setPicked([]); return; }+ const only = chosen.length === 1 ? itemByKey.get(chosen[0]!) : undefined;+ if (e.key === 'Enter' && onAdd && plain && only?.type === 'file' && canAdd(only.file)) {+ e.preventDefault();+ e.stopPropagation();+ onAdd(only.file);return;}if (e.key !== 'Delete' && e.key !== 'Backspace') return;e.preventDefault();e.stopPropagation();- setConfirm({ path: file.path, name: file.name, folder: false });+ askDelete(chosen);}}/* files from the computer: a drag of this pane's own tiles is not one, whatever the browser adds to it (a picturedragged carries itself as a file) */@@ -455,19 +796,41 @@ export function MediaPool({void importFiles([...e.dataTransfer.files]);}}>- <div className="flex shrink-0 items-center gap-1 px-2.5 pb-1.5 pt-2.5">- <label className="flex h-7 min-w-0 flex-1 items-center gap-1.5 rounded-md bg-[var(--bg-hover)] px-2 text-[12.5px] text-[var(--text-muted)]">- <Search size={13} className="shrink-0" />- <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t('media.search')}- className="min-w-0 flex-1 bg-transparent text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]" />- {query ? <button type="button" aria-label={t('media.clearSearch')} onClick={() => setQuery('')} className="shrink-0 hover:text-[var(--text)]"><X size={12} /></button> : null}- </label>+ {/* the bar at the pane's width (lib/media-bar): the search field fills the room left; narrowing, Upload is its+ icon first, then the field shortens, then the search is a button that opens over the bar */}+ <div className={`relative flex shrink-0 items-center pb-1.5 pt-2.5 ${tight ? 'gap-0.5 px-2' : 'gap-1 px-2.5'}`}>+ {/* one field throughout: opened over the bar it is restyled, not made again, so it keeps the focus; there, its+ see-through fill is laid on the pane's own, so the buttons under it do not show */}+ {bar.field || searching ? (+ <label className={`flex h-7 min-w-0 items-center gap-1.5 rounded-md bg-[var(--bg-hover)] px-2 text-[12.5px] text-[var(--text-muted)] ${searching ? `absolute top-2.5 z-10 ${tight ? 'inset-x-2' : 'inset-x-2.5'} [background:linear-gradient(var(--bg-hover),var(--bg-hover)),var(--dock-pane)]` : 'flex-1'}`}>+ <Search size={13} className="shrink-0" />+ <input autoFocus={!bar.field} value={query} onChange={(e) => setQuery(e.target.value)} placeholder={hint}+ onFocus={() => { if (bar.cramped) setSearchOpen(true); }}+ onBlur={() => { if (!query) setSearchOpen(false); }}+ onKeyDown={(e) => { if (e.key === 'Escape' && searching) { setQuery(''); setSearchOpen(false); e.currentTarget.blur(); } }}+ className="min-w-0 flex-1 bg-transparent text-[var(--text)] outline-none placeholder:text-[var(--text-faint)]" />+ {query || searching ? (+ <button type="button" aria-label={t('media.clearSearch')} onMouseDown={(e) => e.preventDefault()}+ onClick={() => { setQuery(''); setSearchOpen(false); }} className="shrink-0 hover:text-[var(--text)]"><X size={12} /></button>+ ) : null}+ </label>+ ) : null}+ {bar.field ? null : (+ /* the field down to its icon, still filling the room: clicked, it opens over the bar */+ <Tooltip label={t('media.search')} side="bottom">+ <button type="button" aria-label={t('media.search')} onClick={() => setSearchOpen(true)}+ className="flex h-7 min-w-7 flex-1 items-center justify-center rounded-md bg-[var(--bg-hover)] text-[var(--text-muted)] transition hover:text-[var(--text)]">+ <Search size={13} />+ </button>+ </Tooltip>+ )}{/* bringing media in is what this pane is for: the one labeled button, right after the search */}<Tooltip label={t('media.import')} side="bottom">- <button type="button" onClick={() => inputRef.current?.click()}- className="flex h-7 shrink-0 items-center gap-1.5 rounded-md bg-[var(--bg-active)] px-2.5 text-[12.5px] font-medium text-[var(--text)] transition hover:bg-[var(--border-strong)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--border-strong)]">+ <button type="button" aria-label={t('media.import')} aria-haspopup={onPick && onBring ? 'menu' : undefined}+ onClick={(e) => (onPick && onBring ? barMenu(e, importMenu) : inputRef.current?.click())}+ className={`flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-md bg-[var(--bg-active)] text-[12.5px] font-medium text-[var(--text)] transition hover:bg-[var(--border-strong)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--border-strong)] ${bar.uploadWord ? 'px-2.5' : 'w-7'}`}><Upload size={13} strokeWidth={2.2} />- {t('media.upload')}+ {bar.uploadWord ? uploadWord : null}</button></Tooltip><BarButton label={t(rows ? 'media.viewGrid' : 'media.viewList')} onClick={() => setView((v) => ({ ...v, layout: rows ? 'grid' : 'list' }))}>@@ -480,9 +843,10 @@ export function MediaPool({id: key, label: t(`media.sort_${key}`), checked: view.sort === key, onSelect: () => setView((v) => ({ ...v, sort: key })),})))}><ArrowUpDown size={14} /></BarButton><BarButton label={t('assets.newFolder')} onClick={() => { setQuery(''); setView((v) => ({ ...v, filter: 'all' })); setCreating(true); }}><FolderPlus size={14} /></BarButton>- <input ref={inputRef} type="file" multiple accept="video/*,image/*,audio/*" className="hidden"- onChange={(e) => { const list = [...(e.target.files ?? [])]; e.target.value = ''; void importFiles(list); }} />{onClose ? <BarButton label={t('media.close')} onClick={onClose}><X size={14} /></BarButton> : null}+ {/* any kind of file: what Studio cannot play is still the project's material */}+ <input ref={inputRef} type="file" multiple className="hidden"+ onChange={(e) => { const list = [...(e.target.files ?? [])]; e.target.value = ''; void importFiles(list); }} /></div>{/* where you are: All, then the folders you went into (drop a file on one to move it there) */}@@ -514,14 +878,6 @@ export function MediaPool({)}</div>- {importing ? (- <div className="mx-2.5 mb-2 shrink-0">- <div className="mb-1 text-[11.5px] text-[var(--text-muted)]">- {t('media.importing').replace('{n}', String(importing.count)).replace('{p}', String(Math.round(importing.ratio * 100)))}- </div>- <div className="h-1 overflow-hidden rounded bg-[var(--bg-hover)]"><div className="h-full bg-[var(--accent)] transition-[width]" style={{ width: `${Math.round(importing.ratio * 100)}%` }} /></div>- </div>- ) : null}{notice ? (<div className="mx-2.5 mb-2 flex shrink-0 items-start gap-2 rounded-md bg-[var(--bg-hover)] px-2 py-1.5 text-[12px] text-[var(--text-muted)]"><span className="min-w-0 flex-1">{notice}</span>@@ -531,26 +887,45 @@ export function MediaPool({<divref={gridRef}- className="min-h-0 flex-1 overflow-y-auto px-2.5 pb-3 pt-1"- /* 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); } }}+ tabIndex={-1}+ className="relative min-h-0 flex-1 overflow-y-auto px-2.5 pb-3 pt-1 outline-none"+ onPointerDown={startBox}+ /* a click on empty space (around the tiles, or in the gaps between them) lets go of what is picked */+ onClick={(e) => {+ if (boxed.current) { boxed.current = false; return; }+ if (!(e.target as Element).closest('[data-media-path], [data-media-folder], [data-media-new-folder], button')) { setPicked([]); showFile(null); }+ }}onContextMenu={(e) => { if (e.target === e.currentTarget) { e.preventDefault(); openMenuAt(e, blankMenu); } }}>- {items && !items.length && !creating ? (+ {marquee ? (+ <div className="pointer-events-none absolute z-20 rounded-[2px] border border-[var(--accent)] bg-[color-mix(in_srgb,var(--accent)_14%,transparent)]"+ style={{ left: marquee.left, top: marquee.top, width: marquee.right - marquee.left, height: marquee.bottom - marquee.top }} />+ ) : null}+ {items && !items.length && !creating && !(flat ? [] : uploads.filter((u) => u.into === at)).length ? (flat ? <p className="px-1 pt-6 text-center text-[12px] text-[var(--text-muted)]">{t('media.noMatch')}</p> : (<div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center"><Clapperboard size={22} className="text-[var(--text-faint)]" /><div className="text-[13px] font-medium text-[var(--text)]">{t(at ? 'media.emptyFolder' : 'media.emptyTitle')}</div>{at ? null : <p className="max-w-[30ch] text-[12px] leading-relaxed text-[var(--text-muted)]">{t('media.emptyBody')}</p>}- <button type="button" onClick={() => inputRef.current?.click()}+ <button type="button" onClick={() => (onPick && onBring ? void bringFrom('copy', false) : inputRef.current?.click())}className="mt-1 inline-flex h-7 items-center gap-1.5 rounded-md border border-[var(--border)] px-2.5 text-[12.5px] text-[var(--text-dim)] transition hover:bg-[var(--bg-hover)]"><Plus size={13} />{t('media.import')}</button></div>)) : (- <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))' }}+ <div className={rows ? '@container 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); } }}>+ {rows ? (+ <div className="flex h-6 shrink-0 select-none items-center gap-2 px-1.5 text-[11px] text-[var(--text-faint)]">+ <span className="w-[46px] shrink-0" />+ <span className="min-w-0 flex-1 truncate">{t('media.sort_name')}</span>+ <span className={COL_TYPE}>{t('assets.propType')}</span>+ <span className={COL_DIMS}>{t('assets.propDimensions')}</span>+ <span className={COL_SIZE}>{t('assets.propSize')}</span>+ <span className={COL_DUR}>{t('assets.propDuration')}</span>+ </div>+ ) : 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' ? (@@ -560,15 +935,18 @@ export function MediaPool({name={item.name}count={item.count}covers={item.covers}+ linked={Boolean(media?.linkedDirs?.[item.rel])}+ progress={progressInto(item.rel)}sources={sources}- selected={selectedFolder === item.rel}+ pickKey={`${root}/${item.rel}`}+ selected={chosen.includes(`${root}/${item.rel}`)}target={dropTarget === item.rel}renaming={renaming === `${root}/${item.rel}`}drop={dropProps(item.rel)}- onDragStart={(e) => { e.dataTransfer.setData(FOLDER_DRAG, `${root}/${item.rel}`); e.dataTransfer.effectAllowed = 'move'; }}- onPress={() => { setSelectedFolder(item.rel); onSelectFile(null); }}- onOpen={() => { setSelectedFolder(null); setAt(item.rel); }}- onMenu={(e) => { setSelectedFolder(item.rel); openMenuAt(e, folderMenu(item.rel, item.name)); }}+ onDragStart={(e) => { e.dataTransfer.setData(FOLDER_DRAG, dragKeys(`${root}/${item.rel}`).join('\n')); e.dataTransfer.effectAllowed = 'move'; }}+ onPress={(e) => press(item, e)}+ onOpen={() => { setPicked([]); setAt(item.rel); }}+ onMenu={(e) => menuFor(item, e)}onRename={(name) => void rename(`${root}/${item.rel}`, name, true)}onCancelRename={() => setRenaming(null)}/>@@ -580,17 +958,21 @@ export function MediaPool({sources={sources}duration={formatClipDuration(item.file.durationMs ?? 0)}where={repeated.has(item.file.name) ? item.file.path.slice(0, Math.max(0, item.file.path.lastIndexOf('/'))) || item.file.path : undefined}- selected={selectedPath === item.file.path}+ selected={chosen.includes(item.file.path)}lit={litPath === item.file.path}+ {...(item.file.link ? { linkLabel: item.file.link.missing ? t('media.linkMissing') : t('media.linkedFrom').replace('{path}', item.file.link.to) } : {})}+ {...(item.file.proxy ? { proxyLabel: proxyText(item.file.proxy), proxyMark: t('media.proxy') } : {})}renaming={renaming === item.file.path}{...(fileRef ? { studioRef: () => fileRef(item.file) } : {})}- onPress={() => { setSelectedFolder(null); onSelectFile(item.file); }}- {...(onAdd && canAdd(item.file) ? { onAdd: () => onAdd(item.file), addLabel: t('media.addToTimeline') } : {})}- onMenu={(e) => { onSelectFile(item.file); openMenuAt(e, fileMenu(item.file)); }}+ moving={() => dragKeys(item.file.path)}+ onPress={(e) => press(item, e)}+ typeText={item.file.kind === 'mg' ? t('assets.kindPage') : extOf(item.file.name).toUpperCase()}+ onMenu={(e) => menuFor(item, e)}onRename={(name) => void rename(item.file.path, name, false)}onCancelRename={() => setRenaming(null)}/>))}+ {flat ? null : uploads.filter((u) => u.into === at).map((u) => <UploadTile key={u.id} upload={u} row={rows} />)}</div>)}</div>@@ -601,7 +983,7 @@ export function MediaPool({{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}+ {menu ? <ContextMenu x={menu.x} y={menu.y} flipTo={menu.flipTo} items={menu.items} onClose={() => { setMenu(null); menuFrom.current = null; }} dense={menu.dense} trigger={menuFrom} /> : null}<ConfirmDialogopen={moveAsk != null}title={t('media.moveAskTitle')}@@ -609,22 +991,25 @@ export function MediaPool({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); }}+ onConfirm={() => { const ask = moveAsk; setMoveAsk(null); if (ask) void moveAll(ask.paths, ask.intoRel, true); }}/><ConfirmDialogopen={confirm != null}- title={confirm?.folder ? t('media.deleteFolderTitle').replace('{name}', confirm.name) : t('assets.deleteConfirmTitle')}+ title={!confirm ? '' : confirm.targets.length > 1 ? t('media.deleteManyTitle').replace('{n}', String(confirm.targets.length))+ : confirm.targets[0]?.folder ? t('media.deleteFolderTitle').replace('{name}', confirm.name) : t('assets.deleteConfirmTitle')}description={(() => {if (!confirm) return '';- const hits = usedSrcs.filter((src) => srcHitsAsset(src, confirm.path) || src.startsWith(`${confirm.path}/`)).length;- if (!hits) return t('assets.deleteConfirm');+ const many = confirm.targets.length > 1;+ const hits = usedSrcs.filter((src) => confirm.targets.some((x) => srcHitsAsset(src, x.path) || src.startsWith(`${x.path}/`))).length;+ if (!hits) return t(many ? 'media.deleteManyConfirm' : 'assets.deleteConfirm');+ if (many) return t(hits === 1 ? 'media.deleteManyAlsoClip' : 'media.deleteManyAlsoClips').replace('{n}', String(hits));return t(hits === 1 ? 'assets.deleteAlsoClip' : 'assets.deleteAlsoClips').replace('{n}', String(hits));})()}confirmLabel={t('assets.delete')}cancelLabel={t('confirm.cancel')}dangeronCancel={() => setConfirm(null)}- onConfirm={() => { const target = confirm; setConfirm(null); if (target) void remove(target); }}+ onConfirm={() => { const asked = confirm; setConfirm(null); if (asked) void remove(asked.targets); }}/></div>);@@ -660,6 +1045,15 @@ const TILE_BOX = 'relative aspect-video overflow-hidden rounded-md ring-2 transi/** 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)]';+/* the list's columns of facts, right of the name, as many as the pane is wide for (a container query on the list):+ the length always (a folder's count there), the size, the kind and the picture's size as it widens */+const COL = 'shrink-0 truncate text-right text-[11px] tabular-nums text-[var(--text-faint)]';+const COL_TYPE = `${COL} hidden w-11 @min-[340px]:block`;+const COL_DIMS = `${COL} hidden w-[76px] @min-[240px]:block`;+const COL_SIZE = `${COL} hidden w-14 @min-[410px]:block`;+const COL_DUR = `${COL} w-12`;+/** A file name's ending, without the dot (`png`), or '' when it has none. */+const extOf = (name: string) => /\.([^./\s]{1,8})$/.exec(name)?.[1] ?? '';/** 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';@@ -685,10 +1079,16 @@ function FolderGlyph({ open }: { open?: boolean }) {*/function FolderTile(p: {name: string; count: number; covers: readonly WorkspaceResource[]; sources: MediaSources;+ /** Files on their way into it: their progress together, a bar along its cover. */+ progress?: number | undefined;+ /** A link to a folder kept elsewhere (a NAS). */+ linked?: boolean;+ /** Its key in what is picked (its path). */+ pickKey: string;selected: boolean; target: boolean; renaming: boolean;drop: { onDragOver: (e: React.DragEvent) => void; onDragLeave: (e: React.DragEvent) => void; onDrop: (e: React.DragEvent) => void };onDragStart: (e: React.DragEvent) => void;- onPress: () => void; onOpen: () => void; onMenu: (e: React.MouseEvent) => void;+ onPress: (e: React.MouseEvent) => 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;@@ -698,24 +1098,28 @@ function FolderTile(p: {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}+ data-media-folder="" data-media-key={p.pickKey} 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)]" />}+ {p.target ? <FolderOpen size={15} className="text-[var(--accent)]" /> : p.linked ? <FolderSymlink size={15} className="text-[var(--text-muted)]" /> : <Folder size={15} className="text-[var(--text-muted)]" />}</span>+ {p.progress != null ? <UploadBar ratio={p.progress} /> : null}</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>+ <span className={COL_TYPE} />+ <span className={COL_DIMS} />+ <span className={COL_SIZE} />+ <span className={COL_DUR}>{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" data-media-folder="" draggable={!p.renaming} onDragStart={p.onDragStart}+ <div className="group min-w-0 cursor-default select-none" data-media-folder="" data-media-key={p.pickKey} 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 */}@@ -726,14 +1130,15 @@ function FolderTile(p: {<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} />+ {file.kind === 'mg' ? <PagePoster file={file} sources={p.sources} /> : <MediaPreview file={file} sources={p.sources} />}</span>))}</div>) : <FolderGlyph open={p.target} />}<span className="pointer-events-none absolute inset-x-0 bottom-0 h-1/2 bg-gradient-to-t from-black/55 to-transparent" />+ {p.progress != null ? <UploadBar ratio={p.progress} /> : null}<span className="pointer-events-none absolute bottom-1 left-1.5 flex items-center gap-1 text-[10.5px] font-medium text-white/90">- {p.target ? <FolderOpen size={11} /> : <Folder size={11} />}+ {p.target ? <FolderOpen size={11} /> : p.linked ? <FolderSymlink size={11} /> : <Folder size={11} />}<span className="tabular-nums">{p.count ? String(p.count) : ''}</span></span></div>@@ -785,35 +1190,26 @@ function FileTile(p: {lit?: boolean;/** The file as a reference in the app's chat, carried by a drag beside the file itself. */studioRef?: () => StudioRef;- onPress: () => void; onMenu: (e: React.MouseEvent) => void; onRename: (name: string) => void; onCancelRename: () => void;- /** The "+": the file put on the timeline. */- onAdd?: () => void;- addLabel?: string;+ /** What a drag of it moves into a folder: it, or every one picked with it. */+ moving: () => readonly string[];+ onPress: (e?: React.MouseEvent) => void; onMenu: (e: React.MouseEvent) => void; onRename: (name: string) => void; onCancelRename: () => void;+ /** A link to media kept elsewhere: what to say of it (where it is kept, or that it cannot be reached). */+ linkLabel?: string;+ /** Heavy footage's proxy: what to say of it (being made, ready…), and its mark once ready. */+ proxyLabel?: string;+ proxyMark?: string;+ /** What kind of file it is, short (`PNG`, `Page`): the list view's Type. */+ typeText: 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 (<divclassName={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-media-key={p.file.path}data-chat-lit={p.lit ? '' : undefined}title={p.where ? p.file.path : p.file.name}draggable={!p.renaming}@@ -823,35 +1219,55 @@ function FileTile(p: {setResourceDragData(e.dataTransfer, p.file);if (p.studioRef) e.dataTransfer.setData(STUDIO_REF_TYPE, JSON.stringify([p.studioRef()]));/* 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.setData(FOLDER_DRAG, p.moving().join('\n'));e.dataTransfer.effectAllowed = 'copyMove';}}onDragEnd={() => clearResourceDrag()}/* focusable, so the keys pressed after picking it are the pane's (Delete asks to delete it) */tabIndex={-1}- onClick={(e) => { e.currentTarget.focus({ preventScroll: true }); p.onPress(); }}+ onClick={(e) => { e.currentTarget.focus({ preventScroll: true }); p.onPress(e); }}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} />}+ {p.file.proxy && p.file.proxy.state !== 'ready' && p.file.proxy.state !== 'failed' ? <UploadBar ratio={p.file.proxy.state === 'making' ? p.file.proxy.ratio ?? 0 : -1} /> : null}</span>- <span className="min-w-0 flex-1">+ <span className="flex min-w-0 flex-1 flex-col">{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>}+ : (+ <span className="flex min-w-0 items-center gap-1" title={p.linkLabel}>+ {p.file.link ? (p.file.link.missing ? <Unlink size={12} className="shrink-0 text-[var(--danger,#e5484d)]" /> : <Link2 size={12} className="shrink-0 text-[var(--text-faint)]" />) : null}+ <span className={`block truncate text-[12.5px] ${p.file.link?.missing ? 'text-[var(--text-faint)]' : p.selected ? 'text-[var(--text)]' : 'text-[var(--text-dim)]'}`} style={KEEP_SPACES}>{p.file.name}</span>+ </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}+ <span className={COL_TYPE}>{p.typeText}</span>+ <span className={COL_DIMS}>{p.file.w && p.file.h ? `${p.file.w} × ${p.file.h}` : ''}</span>+ <span className={COL_SIZE}>{p.file.size ? formatFileSize(p.file.size) : ''}</span>+ <span className={COL_DUR}>{p.duration}</span></>) : <>{/* 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 */}- {add}+ {/* a link to media kept elsewhere: marked; one that cannot be reached (a NAS that is off) says so over it */}+ {p.file.link?.missing ? (+ <span className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-1 bg-black/65 text-[10.5px] text-white/85" title={p.linkLabel}>+ <Unlink size={16} />{p.linkLabel}+ </span>+ ) : p.file.link ? (+ <span className="absolute bottom-1 left-1 z-10 flex h-4 w-4 items-center justify-center rounded bg-black/65 text-white" title={p.linkLabel}><Link2 size={10} /></span>+ ) : null}+ {/* heavy footage's proxy: its making along the bottom, then a mark */}+ {p.file.proxy?.state === 'ready' ? (+ <span className="absolute right-1 top-1 z-10 rounded bg-black/65 px-1 text-[9.5px] font-semibold uppercase leading-[15px] tracking-wide text-white/90" title={p.proxyLabel}>{p.proxyMark}</span>+ ) : p.file.proxy && p.file.proxy.state !== 'failed' ? (+ <span className="absolute inset-x-0 bottom-0 z-10 h-1" title={p.proxyLabel}><UploadBar ratio={p.file.proxy.state === 'making' ? p.file.proxy.ratio ?? 0 : -1} /></span>+ ) : null}{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>@@ -865,6 +1281,48 @@ function FileTile(p: {);}+/** How much of a file is in: a bar along the bottom of its card. */+function UploadBar({ ratio }: { ratio: number }) {+ /* below 0: how much is in is not known (a copy made on this computer): the bar pulses */+ return (+ <span className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-1 bg-black/35">+ <span className={`block h-full bg-[var(--accent)] transition-[width] duration-200 ${ratio < 0 ? 'animate-pulse' : ''}`} style={{ width: `${ratio < 0 ? 100 : Math.round(ratio * 100)}%` }} />+ </span>+ );+}++/** A file on its way in, where it will be: a picture shows itself, anything else its icon; its progress inside. */+function UploadTile({ upload, row }: { upload: Upload; row: boolean }) {+ const pct = upload.ratio < 0 ? '' : `${Math.round(upload.ratio * 100)}%`;+ const Icon = KIND_ICON[upload.kind];+ const picture = upload.preview+ ? <img src={upload.preview} alt="" className="absolute inset-0 h-full w-full object-contain opacity-45" />+ : <span className="absolute inset-0 flex items-center justify-center"><Icon size={row ? 14 : 24} className="text-[var(--text-faint)]" /></span>;+ if (row) {+ return (+ <div className={ROW} data-media-upload="">+ <span className={ROW_THUMB}>{picture}<UploadBar ratio={upload.ratio} /></span>+ <span className="block min-w-0 flex-1 truncate text-[12.5px] text-[var(--text-muted)]" style={KEEP_SPACES}>{upload.name}</span>+ <span className={COL_DUR}>{pct}</span>+ </div>+ );+ }+ return (+ <div className="min-w-0 cursor-default select-none" data-media-upload="">+ <div className="pt-[7px]">+ <div className={`${TILE_BOX} bg-[var(--bg-hover)] ring-transparent`}>+ {picture}+ <span className="absolute inset-0 flex items-center justify-center text-[12px] font-medium tabular-nums text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.7)]">{pct}</span>+ <UploadBar ratio={upload.ratio} />+ </div>+ </div>+ <div className="mt-1 min-w-0 px-0.5">+ <div className="truncate text-[12px] text-[var(--text-muted)]" style={KEEP_SPACES}>{upload.name}</div>+ </div>+ </div>+ );+}+/*** A web page's cover: its poster (the middle frame: a title that fades in is black on its first), else the scene* mark. The mark shows until the poster has loaded, so a page whose poster can't be drawn (it throws) never shows thediff --git a/packages/openfilm/studio/ui/src/components/MediaPreview.tsx b/packages/openfilm/studio/ui/src/components/MediaPreview.tsxindex 8804251..d0d49f9 100644--- a/packages/openfilm/studio/ui/src/components/MediaPreview.tsx+++ b/packages/openfilm/studio/ui/src/components/MediaPreview.tsx@@ -23,6 +23,9 @@ export const KIND_ICON: Record<WorkspaceResourceKind, LucideIcon> = {other: FileIcon,};+/** A file name's ending, without the dot (`pdf`), or '' when it has none. */+const extOf = (name: string) => /\.([^./\s]{1,8})$/.exec(name)?.[1] ?? '';+/*** Has this element come near the viewport yet. A tile asks for its poster only then: a pane of eighty files would* otherwise send eighty requests at once, and the visible row would come in last. Latched: once near, it stays.@@ -86,6 +89,12 @@ export function MediaPreview({/>) : thumbable && near && poster ? (<img src={poster} alt="" onError={() => setBroken(true)} className={IMG} />+ ) : file.kind === 'other' ? (+ /* a file Studio does not play (a document, a model, data): its icon and its ending, which say what it is */+ <span className="flex flex-col items-center gap-1">+ <Icon size={24} className="text-[var(--text-muted)]" />+ {extOf(file.name) ? <span className="text-[10px] font-semibold uppercase tracking-wide text-[var(--text-faint)]">{extOf(file.name)}</span> : null}+ </span>) : (<Icon size={26} className="text-[var(--text-muted)]" />)}diff --git a/packages/openfilm/studio/ui/src/components/MenuSelect.tsx b/packages/openfilm/studio/ui/src/components/MenuSelect.tsxindex 6da980a..433d93b 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 = '', size = 'sm',+ label, value, groups, onPick, disabled = false, className = '', size = 'sm', prefix,}: {/** what it chooses, for screen readers (the field shows the choice) */label: string;@@ -23,6 +23,8 @@ export function MenuSelect({className?: string;/** `sm`: the inspector's fields; `md`: a dialog's (the export's) */size?: 'sm' | 'md';+ /** A word before the choice (Blend), as the inspector's other fields have their mark. */+ prefix?: string;}) {const [open, setOpen] = React.useState(false);const [width, setWidth] = React.useState(0);@@ -84,6 +86,7 @@ export function MenuSelect({onKeyDown={onKeyDown}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}`}>+ {prefix ? <span className="shrink-0 whitespace-nowrap text-[10.5px] text-[var(--text-faint)]">{prefix}</span> : null}<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' : ''}`} /></button>diff --git a/packages/openfilm/studio/ui/src/components/ProjectLayoutMenu.tsx b/packages/openfilm/studio/ui/src/components/ProjectLayoutMenu.tsxindex 147e0ac..3b3b803 100644--- a/packages/openfilm/studio/ui/src/components/ProjectLayoutMenu.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectLayoutMenu.tsx@@ -69,7 +69,7 @@ export function ProjectLayoutMenu({ className, assets, layers, timeline, inspect['inspector', t('layout.inspector'), inspector, onInspector, PanelRight] as const,].map(([key, label, checked, change, Icon]) => <button key={key} type="button" role="switch"aria-checked={checked} onClick={() => change(!checked)}- className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-[13px] text-[var(--text)] hover:bg-[var(--bg-hover)] focus-visible:outline focus-visible:outline-[var(--border-strong)]">+ className="flex w-full items-center gap-2.5 rounded-[7px] px-2 py-1.5 text-[13px] text-[var(--text)] hover:bg-[var(--bg-hover)] focus-visible:outline focus-visible:outline-[var(--border-strong)]"><span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-[var(--surface-2)] text-[var(--text-muted)]"><Icon size={13} aria-hidden /></span><span className="flex-1 text-left">{label}</span>{/* a switch, not a tick: each pane is open or closed, not one picked from a set. Ink-colored, not blue. */}diff --git a/packages/openfilm/studio/ui/src/components/ProjectSources.tsx b/packages/openfilm/studio/ui/src/components/ProjectSources.tsxindex 7655b6b..f66ac60 100644--- a/packages/openfilm/studio/ui/src/components/ProjectSources.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectSources.tsx@@ -8,7 +8,8 @@ import { createPortal } from 'react-dom';import { ArrowUp, ChevronDown, ChevronRight, Clapperboard, Clock3, Folder, FolderOpen, Github, Loader2, X } from 'lucide-react';import { useT } from '@/i18n';import {- SourceError, fetchErrorKey, fetchPhaseKey, followFetch, formatBytes, formatSeconds, looksLikeRepoUrl, pathCrumbs, sourcesApi,+ SourceError, createSpeedMeter, fetchErrorKey, fetchPhaseKey, followFetch, formatBytes, formatSeconds, looksLikeRepoUrl, pathCrumbs,+ secondsLeft, sourcesApi,type BrowseListing, type Example, type FetchJob,} from '@/lib/project-sources';import { CardButton } from './Card';@@ -18,11 +19,14 @@ function SourceDialog({label,width,onClose,+ closeOnOutside = true,children,}: {label: string;width: number;onClose: () => void;+ /** false: a click outside does nothing (a download running is not stopped by a stray click) */+ closeOnOutside?: boolean;children: React.ReactNode;}) {React.useEffect(() => {@@ -41,7 +45,7 @@ function SourceDialog({aria-modalaria-label={label}className="fixed inset-0 z-[10100] flex items-center justify-center bg-black/35 p-4 backdrop-blur-[2px]"- onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}+ onMouseDown={(event) => { if (closeOnOutside && event.target === event.currentTarget) onClose(); }}><divclassName="flex max-h-[calc(100vh-48px)] w-full flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--surface)] shadow-[var(--shadow-lg)]"@@ -259,10 +263,54 @@ export function FolderBrowserDialog({);}+/**+ * How a fetch is going, as a download looks: what it is doing, a bar, how much of how much has come, how fast, and+ * how long is left. Before the first answer (`job` null): getting the list of files, the bar sweeping.+ */+function FetchProgress({ job }: { job: FetchJob | null }) {+ const t = useT();+ const meter = React.useRef(createSpeedMeter());+ const [speed, setSpeed] = React.useState<number | null>(null);+ const bytes = job?.bytes ?? 0;+ React.useEffect(() => {+ if (job?.phase === 'download') setSpeed(meter.current(bytes, Date.now()));+ }, [job?.phase, bytes]);+ const phase = job?.phase ?? 'lookup';+ const total = job?.total ?? null;+ const percent = phase === 'copy' ? 100 : phase === 'lookup' ? null : job?.percent ?? null;+ const left = phase === 'download' ? secondsLeft(bytes, total, speed) : null;+ return (+ <div aria-live="polite">+ <div className="flex items-baseline gap-3 text-[12.5px] text-[var(--text)]">+ <span className="min-w-0 flex-1 truncate">{t(fetchPhaseKey(phase))}</span>+ {percent != null && phase !== 'copy' ? <span className="shrink-0 tabular-nums text-[var(--text-muted)]">{percent}%</span> : null}+ </div>+ <div className="relative mt-2 h-1.5 overflow-hidden rounded-full bg-[var(--border)]">+ {percent == null ? (+ <div className="openfilm-loading-bar absolute inset-y-0 left-0 w-1/3 rounded-full bg-[var(--text)]/60" />+ ) : (+ <div className="h-full rounded-full bg-[var(--text)] transition-[width] duration-300 ease-out" style={{ width: `${percent}%` }} />+ )}+ </div>+ <div className="mt-2 flex min-h-[16px] items-baseline gap-3 text-[11.5px] tabular-nums text-[var(--text-muted)]">+ <span className="min-w-0 flex-1 truncate">+ {phase === 'lookup' ? '' : total ? `${formatBytes(bytes)} / ${formatBytes(total)}` : formatBytes(bytes)}+ </span>+ {phase === 'download' && speed != null ? (+ <span className="shrink-0">+ {`${formatBytes(speed)}/s`}+ {left != null ? ` · ${t('projects.fetch.left').replace('{time}', formatSeconds(left))}` : ''}+ </span>+ ) : null}+ </div>+ </div>+ );+}+/*** "Get from GitHub": an address pasted (a repository, or a folder in one), fetched into the library by Studio, then- * opened. While it runs: where it is and how much has come; a failure in plain words, with Try again. `url` and- * `start`: an example's address, fetched at once.+ * opened. An example (`url` and `start`) skips the address: it is a download, with its progress and Cancel only.+ * Cancel stops it and leaves nothing (an example's dialog closes); a failure is said in plain words, with Try again.*/export function GitHubDialog({url: initialUrl = '',@@ -279,11 +327,16 @@ export function GitHubDialog({onClose: () => void;}) {const t = useT();+ const example = start && !!initialUrl;const [url, setUrl] = React.useState(initialUrl);const [job, setJob] = React.useState<FetchJob | null>(null);+ /* asked to start, no answer yet */+ const [starting, setStarting] = React.useState(false);const [error, setError] = React.useState<string | null>(null);const follow = React.useRef<ReturnType<typeof followFetch> | null>(null);- const running = job?.state === 'running';+ /* which fetch is the current one: a cancelled one's late answers are let go */+ const run = React.useRef(0);+ const running = starting || job?.state === 'running';const say = React.useCallback((code: string | null | undefined, message: string) => {const key = fetchErrorKey(code);@@ -291,89 +344,115 @@ export function GitHubDialog({}, [t]);const get = React.useCallback(async (address: string) => {+ const mine = ++run.current;+ const current = () => run.current === mine;setError(null);setJob(null);+ setStarting(true);try {const first = await sourcesApi.startFetch(address);- follow.current = followFetch(first, setJob);+ /* cancelled before Studio answered: stopped now */+ if (!current()) { void sourcesApi.cancelFetch(first.id).catch(() => {}); return; }+ follow.current = followFetch(first, (next) => { if (current()) setJob(next); });+ setStarting(false);const last = await follow.current.done;- if (!last) return;+ if (!last || !current()) return;if (last.state === 'done' && last.project) onDone(last.project.id);- else if (last.state === 'failed' && last.code !== 'cancelled') say(last.code, last.error ?? '');- if (last.state === 'failed') setJob(null);+ else if (last.state === 'failed') {+ if (last.code !== 'cancelled') say(last.code, last.error ?? '');+ setJob(null);+ }} catch (e) {- say(e instanceof SourceError ? e.code : null, e instanceof Error ? e.message : String(e));+ if (current()) say(e instanceof SourceError ? e.code : null, e instanceof Error ? e.message : String(e));+ } finally {+ if (current()) setStarting(false);}}, [onDone, say]);- const started = React.useRef(false);- React.useEffect(() => {- if (start && initialUrl && !started.current) { started.current = true; void get(initialUrl); }- }, [start, initialUrl, get]);-/* closed or gone while it runs: it is stopped (a half-fetched copy is never left) */const latest = React.useRef<FetchJob | null>(null);latest.current = job;- React.useEffect(() => () => {+ const stop = React.useCallback(() => {+ run.current += 1;follow.current?.stop();const current = latest.current;if (current?.state === 'running') void sourcesApi.cancelFetch(current.id).catch(() => {});+ latest.current = null;}, []);+ React.useEffect(() => stop, [stop]);+ /* an example starts at once (`get` read from a ref: a new onDone each render does not start it again) */+ const getLatest = React.useRef(get);+ getLatest.current = get;+ React.useEffect(() => {+ if (!example) return undefined;+ void getLatest.current(initialUrl);+ return stop;+ }, [example, initialUrl, stop]);const cancel = () => {- if (job?.state === 'running') void sourcesApi.cancelFetch(job.id).catch(() => {});- follow.current?.stop();+ stop();setJob(null);+ setStarting(false);+ if (example) onClose();};+ const close = () => { stop(); onClose(); };const ready = looksLikeRepoUrl(url) && !running;+ const failed = error ? <p role="alert" className="text-[12.5px] leading-snug text-[var(--err)]">{error}</p> : null;return (- <SourceDialog label={t('projects.fetch.title')} width={520} onClose={onClose}>- <DialogHead title={title ?? t('projects.fetch.title')} onClose={onClose} />- <form- className="px-5 pb-5"- onSubmit={(event) => { event.preventDefault(); if (ready) void get(url.trim()); }}- >- <label className="block text-[12px] font-medium text-[var(--text-muted)]" htmlFor="openfilm-fetch-url">{t('projects.fetch.urlLabel')}</label>- <div className="mt-1.5 flex items-center gap-2">- <div className="relative min-w-0 flex-1">- <Github size={14} className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-[var(--text-faint)]" />- <input- id="openfilm-fetch-url"- autoFocus={!start}- value={url}- disabled={running}- onChange={(event) => { setUrl(event.target.value); setError(null); }}- placeholder={t('projects.fetch.placeholder')}- spellCheck={false}- autoComplete="off"- className="h-8 w-full rounded-lg bg-[var(--surface-2)] pl-8 pr-3 text-[12.5px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)] focus:ring-1 focus:ring-[var(--border-strong)] disabled:opacity-60"- />+ <SourceDialog label={title ?? t('projects.fetch.title')} width={520} onClose={close} closeOnOutside={!running}>+ <DialogHead title={title ?? t('projects.fetch.title')} onClose={close} />+ {example ? (+ <div className="px-5 pb-5">+ {error ? failed : <FetchProgress job={job} />}+ <div className="mt-4 flex justify-end gap-2">+ {error ? (+ <>+ <CardButton key="close" weight="quiet" onClick={close}>{t('projects.fetch.close')}</CardButton>+ <CardButton key="retry" weight="primary" onClick={() => void get(initialUrl)}>{t('projects.fetch.retry')}</CardButton>+ </>+ ) : (+ <CardButton key="cancel" weight="secondary" onClick={cancel}>{t('projects.fetch.cancel')}</CardButton>+ )}</div>- {running ? (- <CardButton weight="secondary" onClick={cancel}>{t('projects.fetch.cancel')}</CardButton>- ) : (- <CardButton type="submit" weight="primary" disabled={!ready}>{error ? t('projects.fetch.retry') : t('projects.fetch.get')}</CardButton>- )}</div>- <p className="mt-2 text-[12px] leading-relaxed text-[var(--text-faint)]">{t('projects.fetch.hint')}</p>- {running && job ? (- <div className="mt-4 rounded-xl border border-[var(--border-soft)] bg-[var(--surface-2)] px-3.5 py-3" aria-live="polite">- <div className="flex items-center gap-2 text-[12.5px] text-[var(--text)]">- <Loader2 size={13} className="shrink-0 animate-spin" />- <span className="min-w-0 flex-1 truncate">{t(fetchPhaseKey(job.phase))}</span>- <span className="shrink-0 tabular-nums text-[var(--text-muted)]">{t('projects.fetch.size').replace('{size}', formatBytes(job.bytes))}</span>- </div>- <div className="mt-2 h-1 overflow-hidden rounded-full bg-[var(--border)]">- <div- className={`h-full rounded-full bg-[var(--text)] transition-[width] duration-300 ${job.percent == null ? 'w-1/3 animate-pulse' : ''}`}- style={job.percent == null ? undefined : { width: `${Math.max(4, job.percent)}%` }}+ ) : (+ <form+ className="px-5 pb-5"+ onSubmit={(event) => { event.preventDefault(); if (ready) void get(url.trim()); }}+ >+ <label className="block text-[12px] font-medium text-[var(--text-muted)]" htmlFor="openfilm-fetch-url">{t('projects.fetch.urlLabel')}</label>+ <div className="mt-1.5 flex items-center gap-2">+ <div className="relative min-w-0 flex-1">+ <Github size={14} className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-[var(--text-faint)]" />+ <input+ id="openfilm-fetch-url"+ autoFocus+ value={url}+ disabled={running}+ onChange={(event) => { setUrl(event.target.value); setError(null); }}+ placeholder={t('projects.fetch.placeholder')}+ spellCheck={false}+ autoComplete="off"+ className="h-8 w-full rounded-lg bg-[var(--surface-2)] pl-8 pr-3 text-[12.5px] text-[var(--text)] outline-none placeholder:text-[var(--text-faint)] focus:ring-1 focus:ring-[var(--border-strong)] disabled:opacity-60"/></div>- <p className="mt-1.5 truncate text-[11.5px] text-[var(--text-faint)]">{job.label}</p>+ <CardButton key="get" type="submit" weight="primary" disabled={!ready}>+ {running ? <Loader2 size={13} className="animate-spin" /> : null}+ {error ? t('projects.fetch.retry') : t('projects.fetch.get')}+ </CardButton></div>- ) : null}- {error ? <p role="alert" className="mt-3 text-[12.5px] leading-snug text-[var(--err)]">{error}</p> : null}- </form>+ <p className="mt-2 text-[12px] leading-relaxed text-[var(--text-faint)]">{t('projects.fetch.hint')}</p>+ {running ? (+ <div className="mt-4 rounded-xl border border-[var(--border-soft)] bg-[var(--surface-2)] px-3.5 py-3">+ <FetchProgress job={job} />+ <div className="mt-3 flex justify-end">+ <CardButton key="cancel" weight="secondary" onClick={cancel}>{t('projects.fetch.cancel')}</CardButton>+ </div>+ </div>+ ) : null}+ {failed ? <div className="mt-3">{failed}</div> : null}+ </form>+ )}</SourceDialog>);}diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsxindex 7c1be58..729cb54 100644--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx@@ -8,7 +8,8 @@*/import * as React from 'react';import { GalleryVerticalEnd, Layers, LibraryBig, MessageSquarePlus, MonitorDown, Settings2, TriangleAlert } from 'lucide-react';-import { api, ApiError, projectEvents, type Clip, type Film, type Listing, type Op, type ProjectFilm, type ProjectSettings } from '@/api';+import { applyOps } from '../../../server/ops.mjs';+import { api, ApiError, PREFS_EVENT, projectEvents, type Clip, type Film, type Listing, type Op, type ProjectFilm, type ProjectSettings } from '@/api';import { useT } from '@/i18n';import { useFilm, type Step } from '@/editor/use-film';import { Player } from '@/editor/player';@@ -24,11 +25,11 @@ import { placeMedia, type SourceRange } from '@/lib/media-place';import { apartOnTracks, type ClipEdit } from '@/lib/film-clip-edits';import { mediaFetch } from '@/lib/media-queue';import { clipboardItemsOf, clipboardNow, pasteEdit, type TimelineClipboardItem } from '@/lib/timeline-clipboard';-import { editModelOf, freshLink, linkedIds, planMove, planRippleTrim, planRoom, planSpeed, soundTrackFor, type EditMode } from '@/lib/timeline-edit';-import { readTimelinePrefs } from '@/lib/timeline-prefs';+import { editModelOf, freshLink, linkedIds, magnetOn, mainTrackOf, planMove, planRippleTrim, planRoom, planSpeed, soundTrackFor, type EditMode } from '@/lib/timeline-edit';+import { followOf, readTimelinePrefs } from '@/lib/timeline-prefs';import { fadeMsOf, type FadeMs } from '@/lib/clip-fade';import {- findTransitions, planRemoveTransition, planResizeTransition, planTransition, TRANSITION_MS, WHITE_PAGE,+ findTransitions, planRemoveTransition, planResizeTransition, planTransition, TRANSITION_MS,type ClipFacts, type TransitionAsk, type TransitionPlan,} from '@/lib/transitions';import { frameMs } from '@/lib/timecode';@@ -41,7 +42,7 @@ import { useLoadedThumbs } from '@/lib/use-loaded-thumbs';import { droppedOverrides, overrideTarget, undoneFields, type DroppedEdits, type PersonEdit } from '@/lib/dropped-overrides';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 { factsOfProbe, mediaListingOf, resourceKindOf, srcHitsAsset, warmProjectMedia, type MediaListing, type MediaProxy, type MediaResult, type MediaSources, type WorkspaceResource } from '@/lib/workspace-resources';import { BrandLoadingScreen } from './BrandLoadingScreen';import { BrandLogo } from './BrandLogo';import { SettingsModal, type SettingsSection } from './settings/SettingsModal';@@ -61,7 +62,7 @@ import { DEFAULT_INSPECTOR, DOCK_GAP, DockPaneDivider, MIN_DOCK_H, MIN_INSPECTORimport { PANE_BAR, PANE_BTN_ON, PANE_TOGGLE, PANE_TOGGLE_ICON } from './dock-pane-bar';import { Tooltip } from './Tooltip';import { UpdateButton } from './UpdateButton';-import { MediaPool } from './MediaPool';+import { MediaPool, type ImportProgress } from './MediaPool';import type { SubtitleRowSpec } from './SubtitleRow';import { LayersPanel } from './LayersPanel';import type { LayerRow } from '@/lib/layers-tree';@@ -92,6 +93,7 @@ import { stageMenu, stageRecoveryMenu, type StageArrangeResult, type StageMenuCoimport type { StageEditFailure, StageTextEdit } from './FilmInspector';import { layerTarget, pageClipOf, recoverLayer } from '@/lib/stage-layers';import type { MaskSession } from '@/lib/stage-mask';+import type { MaskShape } from '@/lib/clip-mask';import { nextOverrides, overrideOf, type OverrideGeometry } from '@/lib/film-overrides';import { compactScale, type MgTransform, type NodeOverride, type OverridePivot, type StageElement, type StageElementStyle, type StageGeometry } from '@/lib/stage-types';import { isTypingTarget } from './typing-target';@@ -247,14 +249,16 @@ export function ProjectView({ projectId, onProject, onLeave }: {filmRef.current = film.film;React.useEffect(() => { if (film.error) toast.showError(film.error); }, [film.error, toast]);- /* media facts (length, size, sound) of the project's video and sound files and its web pages, probed once each: a- page without a duration has no end, and is dropped on the timeline with a length of its own */+ /* media facts (length, size, sound) of the project's videos, stills and sounds and its web pages, probed once each: a+ page without a duration has no end, and is dropped on the timeline with a length of its own; a picture's size+ gives its clip a box in its own shape */const probed = React.useRef(new Set<string>());React.useEffect(() => {if (!rawListing) return;const wanted = [- ...rawListing.files.filter((f) => f.kind === 'video' || f.kind === 'audio').map((f) => ({ f, page: false })),- ...rawListing.pages.map((f) => ({ f, page: true })),+ ...rawListing.files.filter((f) => f.kind === 'video' || f.kind === 'image' || f.kind === 'audio').map((f) => ({ f, page: false })),+ /* pages: the project's, and any put in a folder of the media pane */+ ...[...rawListing.pages, ...rawListing.files.filter((f) => f.kind === 'page')].map((f) => ({ f, page: true })),];for (const { f, page } of wanted) {const key = `${f.path}@${f.mtime}`;@@ -264,7 +268,11 @@ export function ProjectView({ projectId, onProject, onLeave }: {.then((r) => (r.ok ? r.json() : null)).then((probe) => {if (!probe) return;- const facts = { ...factsOfProbe(probe), audio: Boolean(probe.audio), ...(page && !(probe.duration > 0) ? { endless: true } : {}) };+ const facts = {+ ...factsOfProbe(probe), audio: Boolean(probe.audio),+ ...(page && !(probe.duration > 0) ? { endless: true } : {}),+ ...(page && probe.reflows ? { reflows: true } : {}),+ };setFacts((m) => new Map(m).set(f.path, facts));}, () => {});}@@ -281,9 +289,41 @@ export function ProjectView({ projectId, onProject, onLeave }: {pageSurface: (f) => `${folder}${f.path.split('/').map(encodeURIComponent).join('/')}`,};}, [projectId, folder, filesTick]);+ /*+ * proxies (studio/server/proxies.mjs): asked for the project's heavy footage whenever its files change or the+ * preferences do, followed while they are made. One ready for footage on the film, or other preferences, load the+ * preview again behind the picture, so it plays what it should.+ */+ const [proxies, setProxies] = React.useState<Record<string, MediaProxy>>({});+ const [prefsTick, setPrefsTick] = React.useState(0);+ React.useEffect(() => {+ const changed = () => setPrefsTick((n) => n + 1);+ window.addEventListener(PREFS_EVENT, changed);+ return () => window.removeEventListener(PREFS_EVENT, changed);+ }, []);+ React.useEffect(() => { if (prefsTick) preview.current?.reload?.(); }, [prefsTick]);+ React.useEffect(() => {+ if (!rawListing) return undefined;+ let alive = true;+ let timer = 0;+ let before: Record<string, MediaProxy> = {};+ const ask = async () => {+ const answer = await fetch(`/api/projects/${encodeURIComponent(projectId)}/proxies`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })+ .then((r) => (r.ok ? r.json() : null), () => null) as { states?: Record<string, MediaProxy> } | null;+ if (!alive || !answer) return;+ const states = answer.states ?? {};+ setProxies(states);+ const now = Object.keys(states).filter((path) => states[path]!.state === 'ready' && before[path] && before[path]!.state !== 'ready');+ if (now.some((path) => blocksRef.current.some((b) => b.src && srcHitsAsset(b.src, path)))) preview.current?.reload?.();+ before = states;+ if (Object.values(states).some((s) => s.state === 'waiting' || s.state === 'making')) timer = window.setTimeout(() => { void ask(); }, 1500);+ };+ void ask();+ return () => { alive = false; window.clearTimeout(timer); };+ }, [rawListing, projectId, prefsTick]);const listing = React.useMemo<MediaListing | null>(- () => (rawListing ? mediaListingOf(rawListing, (path) => facts.get(path), (rawListing as { made?: string[] }).made) : null),- [rawListing, facts],+ () => (rawListing ? mediaListingOf(rawListing, (path) => ({ ...facts.get(path), ...(proxies[path] ? { proxy: proxies[path] } : {}) }), (rawListing as { made?: string[] }).made) : null),+ [rawListing, facts, proxies],);React.useEffect(() => { if (listing) warmProjectMedia(projectId, listing, mediaSources); }, [projectId, listing, mediaSources]);/* a file of the media pane as a reference: shown by its poster (a video, a page) or itself (a still, on Studio's@@ -483,6 +523,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {clipLinksRef.current = clipLinks;/** The timeline as an edit sees it now (lib/timeline-edit). */const editModel = React.useCallback(() => editModelOf(tracksRef.current, clipLinksRef.current), []);+ /** The main track (the lowest picture track), where the magnet acts: the inspector asks. */+ const mainTrack = React.useMemo(() => mainTrackOf(editModelOf(timelineTracks)), [timelineTracks]);const blocksRef = React.useRef<readonly TimelineBlock[]>([]);blocksRef.current = React.useMemo(() => timelineTracks.flatMap((tr) => tr.blocks), [timelineTracks]);/* the film's length: the preview's, unless it could not draw the film; that length is then of the film before@@ -518,6 +560,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {/* selection, by clip id: a block's own id is its place, and that changes when it moves */const [selectedKeys, setSelectedKeys] = React.useState<readonly string[]>([]);+ const selectedKeysRef = React.useRef(selectedKeys);+ selectedKeysRef.current = selectedKeys;const selectedBlocks = React.useMemo(() => {const keys = new Set(selectedKeys);return blocksRef.current.filter((b) => keys.has(b.clipId ?? b.id));@@ -555,9 +599,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {const [layersWidth, setLayersWidth] = React.useState(240);const layersPaneRef = React.useRef<HTMLDivElement | null>(null);const [timelineOpen, setTimelineOpen] = useKeptFlag('openfilm.project.timeline');- /* closed until it has something to show (a selection opens it), or the person opens it */- const [inspectorOpen, persistInspector, setInspectorOpen] = useKeptFlag('openfilm.project.inspector', true);- const closeInspector = React.useCallback(() => persistInspector(false), [persistInspector]);+ /* open whenever the project opens (a reload too); closed, it stays closed until then or until a selection opens it */+ const [inspectorOpen, setInspectorOpen] = React.useState(true);+ const closeInspector = React.useCallback(() => setInspectorOpen(false), [setInspectorOpen]);const [rowWidth, setRowWidth] = React.useState(0);const [colHeight, setColHeight] = React.useState(0);React.useEffect(() => {@@ -680,23 +724,19 @@ export function ProjectView({ projectId, onProject, onLeave }: {const pickedTr = filmTransitions.find((x) => x.key === pickedTransition) ?? null;/*** A transition put on a cut, made longer or shorter, or taken away (lib/transitions): planned on the timeline as it- * is, in the timeline's mode (the magnet, sync lock, linked clips), one write and one undo step. A dip to white first- * keeps its white page in the project (transitions/white.html).+ * is, in the timeline's mode (the magnet, sync lock, linked clips), one write and one undo step. The menus put on+ * fades only; other transitions are an agent's to write.*/const askTransition = React.useCallback(async (ask: TransitionAsk): Promise<string | null> => {const prefs = readTimelinePrefs();- const opts = { ripple: prefs.magnet, sync: prefs.sync, linked: prefs.linked, whiteSrc: WHITE_SRC };const model = editModel();+ /* the magnet acts on the main track: there a transition's overlap closes up what follows */+ const cutClip = ask.kind === 'add' ? ask.cut.a : filmTransitions.find((x) => x.key === ask.key)?.a;+ const cutTrack = model.find((tr) => tr.clips.some((c) => c.id === cutClip))?.index;+ const opts = { ripple: magnetOn(model, cutTrack, prefs.magnet), ...followOf(prefs), linked: prefs.linked, whiteSrc: WHITE_SRC };let plan: TransitionPlan;let label: string;if (ask.kind === 'add') {- if (ask.type === 'dip-white') {- const made = await fetch(`/api/projects/${encodeURIComponent(projectId)}/transition-pages`, {- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'white', html: WHITE_PAGE }),- }).catch(() => null);- if (!made?.ok) return t('transitions.failed').replace('{error}', made ? String(made.status) : 'offline');- await api.files(projectId).then(setRawListing, () => {});- }/* the default length, on the frame grid */const frame = frameMs(1);plan = planTransition(model, clipFacts, ask.type, ask.cut, Math.round(TRANSITION_MS / frame) * frame, opts);@@ -709,7 +749,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {}if ('error' in plan) return t(plan.error === 'locked' ? 'transitions.locked' : plan.error === 'short' ? 'transitions.short' : 'transitions.none');return plan.ops.length ? edit(plan.ops, label) : null;- }, [editModel, clipFacts, filmTransitions, edit, projectId, t]);+ }, [editModel, clipFacts, filmTransitions, edit, t]);/*** The inspector's edits (its refusals it says beside its field). A new speed goes to the clips linked to the clip too; with the magnet on (the timeline's* switch) a speed or a length that makes the clip longer or shorter pushes or pulls what follows, as a ripple trim@@ -720,8 +760,10 @@ export function ProjectView({ projectId, onProject, onLeave }: {const block = one && edits.length === 1 ? blocksRef.current.find((b) => b.loc === one.loc) : undefined;const prefs = readTimelinePrefs();if (block?.loc && lockedEdits(edits, filmRef.current).length) return Promise.resolve(t('timeline.trackLocked'));- if (!block?.clipId || (one!.prop !== 'speed' && one!.prop !== 'at' && !(one!.prop === 'end' && prefs.magnet))) return editBlocks(edits, true);const model = editModel();+ /* the magnet acts on the main track alone */+ const magnet = magnetOn(model, model.find((tr) => tr.clips.some((c) => c.id === block?.clipId))?.index, prefs.magnet);+ if (!block?.clipId || (one!.prop !== 'speed' && one!.prop !== 'at' && !(one!.prop === 'end' && magnet))) return editBlocks(edits, true);const ids = prefs.linked ? [block.clipId, ...linkedIds(model, [block.clipId]).filter((id) => id !== block.clipId)] : [block.clipId];if (one!.prop === 'at') {/* a start typed in: the clip (and those linked to it) moves as a drag would, in the timeline's mode: with the@@ -729,20 +771,20 @@ export function ProjectView({ projectId, onProject, onLeave }: {what is under it. Never onto a new track */const startMs = Number(one!.value) * 1000 + (block.anchor?.parentStartMs ?? 0);if (!Number.isFinite(startMs)) return Promise.resolve(t('timeline.editFail'));- const plan = planMove(model, { ids, deltaMs: startMs - block.startMs, pointerMs: startMs, mode: prefs.magnet ? 'insert' : 'overwrite', sync: prefs.sync });+ const plan = planMove(model, { ids, deltaMs: startMs - block.startMs, pointerMs: startMs, mode: magnet ? 'insert' : 'overwrite', magnet: prefs.magnet, ...followOf(prefs) });if (!plan) return Promise.resolve(t('timeline.trackLocked'));return plan.ops.length ? edit(plan.ops, clipStep('history.stepMoved', [block.clipId]), true) : Promise.resolve(null);}if (one!.prop === 'speed') {const speed = typeof one!.value === 'number' ? one!.value : 1;- const plan = planSpeed(model, ids, speed, { ripple: prefs.magnet, sync: prefs.sync });+ const plan = planSpeed(model, ids, speed, { ripple: magnet, ...followOf(prefs) });if (plan.slowest != null) return Promise.resolve(t('inspector.speedTooSlow').replace('{n}', String(plan.slowest)));return plan.ops.length ? edit(plan.ops, `history.stepSpeed|${block.clipId}`, true) : Promise.resolve(null);}/* a new length, with the magnet: a ripple trim of the tail by the difference (source seconds over the speed) */const k = block.anchor?.trimFrom != null && block.speed ? block.speed : 1;const deltaMs = ((Number(one!.value) - Number(one!.from ?? one!.value)) * 1000) / k;- const plan = planRippleTrim(model, ids, 'end', deltaMs, { sync: prefs.sync });+ const plan = planRippleTrim(model, ids, 'end', deltaMs, followOf(prefs));return plan.ops.length ? edit(plan.ops, `history.stepRippleTrimmed|${block.clipId}`, true) : Promise.resolve(null);}, [editBlocks, editModel, edit, t]);const removeBlock = React.useCallback((block: TimelineBlock): Promise<string | null> => {@@ -778,14 +820,29 @@ export function ProjectView({ projectId, onProject, onLeave }: {taken.add(made);rightLinks.set(link, made);}+ /* a selected clip's selection goes to its right half, as CapCut's: named here so it can be selected once written */+ const selected = new Set(selectedKeysRef.current);+ const used = new Set(clips.map((c) => c.id));+ const rightIds = new Map<string, string>();+ for (const { block } of halves) {+ if (!selected.has(block.clipId!)) continue;+ let id = `${block.clipId}-b`;+ for (let n = 2; used.has(id); n++) id = `${block.clipId}-b-${n}`;+ used.add(id);+ rightIds.set(block.clipId!, id);+ }const ops: Op[] = halves.map(({ block, split, link }) => ({op: 'split',clip: block.clipId!,left: split.left,/* a half left alone with a link (its linked clip not under the cut) keeps none: it would pull the other along */right: { ...split.right, link: link ? rightLinks.get(link) ?? null : null },+ ...(rightIds.has(block.clipId!) ? { rightId: rightIds.get(block.clipId!)! } : {}),}));- return edit(ops, clipStep('history.stepSplit', halves.slice(0, 2).map((h) => h.block.clipId!)));+ return edit(ops, clipStep('history.stepSplit', halves.slice(0, 2).map((h) => h.block.clipId!))).then((err) => {+ if (!err && rightIds.size) setSelectedKeys((keys) => keys.map((k) => rightIds.get(k) ?? k));+ return err;+ });}, [edit, editModel, t]);/*** A video's sound taken apart from its picture, as an editor unlinks them: the same file's sound alone, at the same@@ -838,7 +895,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {const all = [...items, ...cut].sort((a, b) => a.startMs - b.startMs);if (!all.length) return Promise.resolve(null);const prefs = readTimelinePrefs();- const ops = pasteEdit(all, timelineTracks, editModel(), atMs, lane, { mode: prefs.magnet ? 'insert' : 'overwrite', sync: prefs.sync });+ const ops = pasteEdit(all, timelineTracks, editModel(), atMs, lane, { magnet: prefs.magnet, ...followOf(prefs) });if (!ops) return Promise.resolve(t('timeline.trackLocked'));const gone = new Set(cut.map((item) => item.clipId));const written = ops.map((op): Op => {@@ -854,10 +911,10 @@ export function ProjectView({ projectId, onProject, onLeave }: {const roomFor = React.useCallback((spans: { track: number | { insert: number } | undefined; atSec: number; durMs: number }[], mode?: EditMode): Op[] => {const onTracks = spans.flatMap((s) => (typeof s.track === 'number' ? [{ track: s.track, startMs: Math.round(s.atSec * 1000), endMs: Math.round(s.atSec * 1000) + s.durMs }] : []));if (!mode || !onTracks.length) return [];- return planRoom(editModel(), onTracks, { mode, sync: readTimelinePrefs().sync }).ops;+ return planRoom(editModel(), onTracks, { mode, ...followOf(readTimelinePrefs()) }).ops;}, [editModel]);const dropAsset = React.useCallback(async (file: ResourceDragItem, target: AssetDropTarget, atMs: number): Promise<string | null> => {- const plan = assetDropInsert(file, timelineTracks, target, atMs);+ const plan = assetDropInsert(file, timelineTracks, target, atMs, stageRef.current);if ('error' in plan) return plan.error === 'locked' ? t('timeline.trackLocked') : t('timeline.dropNotClip');const pending = pendingDropOf(file, target, atMs);if (pending) setPendingDrops((all) => [...all, pending]);@@ -879,7 +936,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {const prefs = readTimelinePrefs();const target = timelineCommands.current?.target() ?? null;const at = how.atPlayhead || target != null ? snapToFrame(timeRef.current) : 'end';- const plan = placeMedia(editModel(), { file, range: how.range ?? null, target, at, mode: how.mode ?? (prefs.magnet ? 'insert' : 'overwrite'), sync: prefs.sync });+ const plan = placeMedia(editModel(), { file, range: how.range ?? null, target, at, ...(how.mode ? { mode: how.mode } : {}), magnet: prefs.magnet, ...followOf(prefs), stage: stageRef.current });if ('error' in plan) { toast.show(plan.error === 'locked' ? t('timeline.trackLocked') : t('timeline.dropNotClip')); return; }const failed = await edit(plan.ops, 'history.stepDrop');if (failed) { toast.show(failed); return; }@@ -987,6 +1044,10 @@ export function ProjectView({ projectId, onProject, onLeave }: {onNewFolder={onNewFolder}onDropClips={dropClipsForAssets}onReveal={reveal}+ onPick={onPick}+ onBring={onBring}+ onRelink={onRelink}+ onCollect={onCollect}onClose={onClose}{...(studioHost?.refer ? { fileRef: refOfFile, onRefer: studioHost.refer } : {})}reveal={revealMedia}@@ -1268,6 +1329,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {setStageSelectRequest((cur) => ({ loc, ...(clipLoc ? { clipLoc } : {}), seq: (cur?.seq ?? 0) + 1 }));}, []);const selectStageClip = React.useCallback((clipLoc: string) => { setStageElement(null); setSelectedLocs([clipLoc]); }, [setSelectedLocs]);+ /* a marquee on the picture around several clips: the timeline selects them */+ const selectStageClips = React.useCallback((locs: readonly string[]) => { setStageElement(null); setSelectedLocs([...locs]); }, [setSelectedLocs]);/* ── the Layers panel: its rows select on the picture, outline there, hide, lock and restack (overrides) ── */const [pointedLayer, setPointedLayer] = React.useState<{ clipId: string; loc: string } | null>(null);const askStage = React.useCallback(<T,>(op: string, args: object = {}): Promise<T | null> => (@@ -1402,7 +1465,11 @@ export function ProjectView({ projectId, onProject, onLeave }: {for (const p of picks) { const ref = refOfStagePick(p); if (ref) refer(ref); }}, []); // eslint-disable-line react-hooks/exhaustive-deps/* the bar's Mask: the inspector open on its Mask section (the shapes are picked there) */- const openMaskSection = React.useCallback(() => {+ /* the picture's Mask menu: the shape goes to the clip's Mask section (put on, its handles shown), opened */+ const [maskAsk, setMaskAsk] = React.useState<{ shape: MaskShape | 'none'; clipLoc: string; n: number } | null>(null);+ const maskAsked = React.useCallback(() => setMaskAsk(null), []);+ const openMaskSection = React.useCallback((shape: MaskShape | 'none', clipLoc: string) => {+ setMaskAsk({ shape, clipLoc, n: Date.now() });openSection('mask');setInspectorContent('selection');setInspectorOpen(true);@@ -1419,7 +1486,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {if (!picked.length) return null;const prefs = readTimelinePrefs();const tracks = tracksRef.current;- const ops = pasteEdit(clipboardItemsOf(picked, tracks), tracks, editModel(), Math.max(...picked.map((b) => b.endMs)), null, { mode: prefs.magnet ? 'insert' : 'overwrite', sync: prefs.sync });+ const ops = pasteEdit(clipboardItemsOf(picked, tracks), tracks, editModel(), Math.max(...picked.map((b) => b.endMs)), null, { magnet: prefs.magnet, ...followOf(prefs) });const failed = !ops ? t('timeline.trackLocked') : ops.length ? await edit(ops, picked.length <= 2 ? clipStep('history.stepDuplicated', picked.map((b) => b.clipId!)) : 'history.stepDuplicate') : null;if (failed) toast.show(failed);return failed;@@ -1539,29 +1606,82 @@ export function ProjectView({ projectId, onProject, onLeave }: {/* ── media pane actions ── */const projectApi = `/api/projects/${encodeURIComponent(projectId)}`;const mediaResult = async (res: Response): Promise<MediaResult> => (res.ok ? 'ok' : res.status === 409 ? 'taken' : 'failed');- /* resolves with where each file landed (a taken name gets a number); one that is no readable media is said at once */- const onImport = React.useCallback(async (files: File[], into: string, onProgress: (ratio: number) => void): Promise<string[]> => {- let done = 0;+ /* media kept on this computer (files.mjs bringIn): picked in the system's dialog (the app's own for a folder, when+ it has one; 'no-dialog' where there is none), copied in (cloned where the disk can) or linked where it is kept (a+ NAS). A link pointed elsewhere, or copied into the project in its place */+ const postJson = React.useCallback(async (path: string, body: unknown) => {+ const res = await fetch(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });+ const answer = await res.json().catch(() => ({})) as Record<string, unknown>;+ return { ok: res.ok, status: res.status, answer };+ }, []);+ const onPick = React.useCallback(async (title: string, folder: boolean): Promise<string[] | 'no-dialog'> => {+ if (folder && studioHost?.folders?.pick) { const path = await studioHost.folders.pick({ title }); return path ? [path] : []; }+ const { ok, status, answer } = await postJson(folder ? '/api/pick-folder' : '/api/pick-files', { title });+ if (status === 501) return 'no-dialog';+ if (!ok) return [];+ return folder ? (typeof answer.path === 'string' ? [answer.path] : []) : Array.isArray(answer.paths) ? answer.paths.map(String) : [];+ }, [postJson]);+ const onBring = React.useCallback(async (paths: string[], into: string, mode: 'copy' | 'link'): Promise<string[]> => {+ const { ok, answer } = await postJson(`${projectApi}/files/bring`, { paths, into, mode });+ if (!ok) throw new Error(String(answer.error ?? t('assets.uploadFailed')));+ return Array.isArray(answer.landed) ? answer.landed.map(String) : [];+ }, [projectApi, postJson, t]);+ const onRelink = React.useCallback(async (path: string, folder: boolean): Promise<MediaResult> => {+ const to = (await onPick(t('media.pickRelink'), folder));+ if (to === 'no-dialog' || !to.length) return 'ok';+ return (await postJson(`${projectApi}/files/relink`, { path, to: to[0] })).ok ? 'ok' : 'failed';+ }, [projectApi, postJson, onPick, t]);+ const onCollect = React.useCallback(async (path: string): Promise<MediaResult> => (+ (await postJson(`${projectApi}/files/collect`, { path })).ok ? 'ok' : 'failed'+ ), [projectApi, postJson]);+ /*+ * resolves with where each file landed (a taken name gets a number); one that is no readable media is said at once.+ * Each file's progress is its bytes sent (XMLHttpRequest: fetch cannot tell how much of a body has gone), then 1 and+ * where it landed+ */+ const onImport = React.useCallback(async (files: File[], into: string, onProgress: ImportProgress): Promise<string[]> => {const landed: string[] = [];- for (const file of files) {- // eslint-disable-next-line no-await-in-loop- const res = await fetch(`${projectApi}/files?path=${encodeURIComponent(`${into}/${file.name}`)}`, { method: 'PUT', body: file });+ /* in the app a dropped file's path is known: copied on this computer (cloned where the disk can: at once, and no+ more room taken), not sent through the page */+ const paths = files.map((file) => studioHost?.folders?.pathOf(file) ?? '');+ if (paths.length && paths.every(Boolean)) {+ for (const [i, path] of paths.entries()) {+ onProgress(i, -1);+ // eslint-disable-next-line no-await-in-loop+ const [at] = await onBring([path], into, 'copy');+ if (at) landed.push(at);+ onProgress(i, 1, at);+ }+ return landed;+ }+ for (const [i, file] of files.entries()) {// eslint-disable-next-line no-await-in-loop- const body = await res.json().catch(() => ({})) as { path?: string; error?: string; unreadable?: string };- if (!res.ok) throw new Error(String(body.error ?? t('assets.uploadFailed')));+ const { ok, body } = await new Promise<{ ok: boolean; body: { path?: string; error?: string; unreadable?: string } }>((done) => {+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', `${projectApi}/files?path=${encodeURIComponent(`${into}/${file.name}`)}`);+ xhr.upload.onprogress = (e) => { if (e.lengthComputable && e.total > 0) onProgress(i, Math.min(0.99, e.loaded / e.total)); };+ xhr.onload = () => {+ let body = {};+ try { body = JSON.parse(xhr.responseText); } catch { /* no answer to read */ }+ done({ ok: xhr.status >= 200 && xhr.status < 300, body });+ };+ xhr.onerror = () => done({ ok: false, body: {} });+ xhr.send(file);+ });+ if (!ok) throw new Error(String(body.error ?? t('assets.uploadFailed')));if (body.path) landed.push(body.path);if (body.unreadable) toast.show(t('assets.unreadable').replace('{name}', file.name).replace('{why}', body.unreadable));- onProgress(++done / files.length);+ onProgress(i, 1, body.path);}return landed;- }, [projectApi, t, toast]);+ }, [projectApi, t, toast, onBring]);/* ── files dropped from the computer: imported into assets/ (the media pane's own import), then put on the film ── */- /** A file just imported, as the media pane would hand it to a drop: its kind from its name, its length probed. */+ /** A file just imported, as the media pane would hand it to a drop: its kind from its name, its length and size probed. */const resourceOf = React.useCallback(async (path: string): Promise<ResourceDragItem> => {const kind = resourceKindOf(path);const base: ResourceDragItem = { path, name: path.slice(path.lastIndexOf('/') + 1), kind, dir: '', size: 0, mtimeMs: 0 };- if (kind !== 'video' && kind !== 'audio') return base;+ if (kind !== 'video' && kind !== 'image' && kind !== 'audio') return base;const probe = await fetch(`${projectApi}/media?what=probe&path=${encodeURIComponent(path)}`).then((r) => (r.ok ? r.json() : null), () => null);return { ...base, ...factsOfProbe(probe) };}, [projectApi]);@@ -1593,7 +1713,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {}, [onImport, resourceOf, edit, roomFor, t]);/* on the timeline: where they were dropped, as a drag from the media pane lands */const dropFiles = React.useCallback((files: File[], hit: AssetLaneHit | null, atMs: number, mode?: EditMode) => (- importAndPlace(files, (items) => assetRunInsert(items, tracksRef.current, hit, atMs, mode), mode)+ importAndPlace(files, (items) => assetRunInsert(items, tracksRef.current, hit, atMs, mode, stageRef.current), mode)), [importAndPlace]);/* on the picture: at the playhead, pictures on a new track on top, sounds on a sound track */const dropFilesOnPicture = React.useCallback((files: File[]) => {@@ -1603,7 +1723,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {const pictures = items.filter((f) => f.kind !== 'audio');const tracks = tracksRef.current;const heard = sounds.length ? assetRunInsert(sounds, tracks, soundLaneHit(tracks, atMs, assetRunMs(sounds)), atMs) : { inserts: [] };- const seen = pictures.length ? assetRunInsert(pictures, tracks, { lane: -1, band: 'body' }, atMs) : { inserts: [] };+ const seen = pictures.length ? assetRunInsert(pictures, tracks, { lane: -1, band: 'body' }, atMs, undefined, stageRef.current) : { inserts: [] };/* the sounds first: the pictures' new track goes in at the top and moves every track under it down one */const inserts = [...('inserts' in heard ? heard.inserts : []), ...('inserts' in seen ? seen.inserts : [])];if (inserts.length) return { inserts };@@ -1684,16 +1804,14 @@ export function ProjectView({ projectId, onProject, onLeave }: {const onNewFolder = React.useCallback(async (path: string) => mediaResult(await fetch(`${projectApi}/folders`, {method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path }),})), [projectApi]);- const reveal = React.useCallback((path: string) => {- void fetch(`${projectApi}/reveal`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path }) });+ const reveal = React.useCallback((path: string, original?: boolean) => {+ void fetch(`${projectApi}/reveal`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path, ...(original ? { original } : {}) }) });}, [projectApi]);/* ── picture: the delivery frame, fullscreen ── */const stage = film.film?.stage ?? { w: 1920, h: 1080 };stageRef.current = stage;const empty = !film.film?.tracks.some((tr) => tr.clips.length);- /* 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 shapekeeps the canvas's short side (canvasFor; a typed size is that size), and every picture on it is scaled by onefactor into the new canvas, centered, in the same edit (one undo). Laying the film out again for the new canvas@@ -1706,9 +1824,8 @@ export function ProjectView({ projectId, onProject, onLeave }: {.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;+ /** The edit that makes the canvas `size`, the film fitted into it (see canvas-fit). */+ const canvasOps = React.useCallback((size: { w: number; h: number }): Op[] => {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) => ({@@ -1719,14 +1836,37 @@ export function ProjectView({ projectId, onProject, onLeave }: {reflows: reflows.has(clip.id),size: clip.size ?? null,})));- void edit([+ return [{ 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]);+ ];+ }, [stage, spans, film.film]);+ /* a canvas size shown on the picture while its width or height is dragged, not kept yet */+ const [canvasDraft, setCanvasDraft] = React.useState<{ w: number; h: number } | null>(null);+ const shownStage = canvasDraft ?? stage;+ /* 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(shownStage, 'native'), [shownStage]);+ const previewCanvas = React.useCallback((size: { w: number; h: number } | null) => {+ const value = film.film;+ if (!value) return;+ if (!size || (size.w === stage.w && size.h === stage.h)) {+ setCanvasDraft((cur) => { if (cur) preview.current?.update(value); return null; });+ return;+ }+ let shown: Film;+ try { shown = applyOps(structuredClone(value), canvasOps(size)) as Film; } catch { return; }+ setCanvasDraft(size);+ preview.current?.update(shown);+ }, [film.film, stage, canvasOps]);+ const changeCanvas = React.useCallback((next: FilmFrameId, given?: { w: number; h: number }) => {+ const size = given ?? canvasFor(stage, next);+ setCanvasDraft(null);+ if (size.w === stage.w && size.h === stage.h) { if (canvasDraft && film.film) preview.current?.update(film.film); return; }+ void edit(canvasOps(size), 'history.stepEdit');+ }, [edit, stage, canvasOps, canvasDraft, film.film]);const stageFullRef = React.useRef<HTMLDivElement>(null);const [fullscreen, setFullscreen] = React.useState(false);React.useEffect(() => {@@ -2090,7 +2230,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {assets={hostAssets ? null : assetsPaneOpen} onAssets={setAssetsPaneOpen}layers={layersPaneOpen} onLayers={setLayersPaneOpen}timeline={timelineOpen} inspector={inspectorOpen}- onTimeline={setTimelineOpen} onInspector={persistInspector}+ onTimeline={setTimelineOpen} onInspector={setInspectorOpen}hostPanel={hostPanel ? { label: hostPanel.label, open: hostPanel.open, onChange: hostPanel.setOpen } : null} /><ProjectHistoryButton open={historyOpen} onClick={openHistory} className={TOP_BTN} /><ProjectMenu className={TOP_BTN}@@ -2177,7 +2317,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {</Tooltip><span className="min-w-0 flex-1" /><Tooltip label={t(inspectorOpen ? 'inspector.hide' : 'inspector.show')} side="bottom">- <button type="button" onClick={() => persistInspector(!inspectorOpen)}+ <button type="button" onClick={() => setInspectorOpen(!inspectorOpen)}aria-label={t(inspectorOpen ? 'inspector.hide' : 'inspector.show')}className={`${PANE_TOGGLE} ${inspectorOpen ? PANE_BTN_ON : ''}`}><Settings2 size={PANE_TOGGLE_ICON} />@@ -2228,12 +2368,12 @@ export function ProjectView({ projectId, onProject, onLeave }: {width: `${(frameBox.inner.w / frameBox.w) * 100}%`,height: `${(frameBox.inner.h / frameBox.h) * 100}%`,}}>- <Preview ref={preview} folder={folder} stage={stage} time={() => player.current.time()}+ <Preview ref={preview} folder={folder} stage={shownStage} time={() => player.current.time()}onInfo={onInfo} onKey={previewKey} onError={setPreviewError}>{!fullscreen ? (<FilmStageSelectpreviewRef={preview}- stage={stage}+ stage={shownStage}doc={value as unknown as FilmDoc}spans={spans}timeMs={timeMs}@@ -2242,6 +2382,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {onSelectElement={selectStageElement}onEditClip={editClipsFromStage}linkedLocs={selectedLocs}+ onSelectClips={selectStageClips}selectRequest={stageSelectRequest}clipPreviewRef={clipPreviewRef}lookPreviewRef={lookPreviewRef}@@ -2344,6 +2485,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {store={geometryStore}element={stageElement}clips={selectedBlocks}+ mainTrack={mainTrack}onEditClips={editClips}width={inspectorShownWidth}onClose={closeInspector}@@ -2362,10 +2504,15 @@ export function ProjectView({ projectId, onProject, onLeave }: {onPreviewLook={previewLook}onStartCrop={startStageCrop}onEditMask={editStageMask}+ maskAsk={maskAsk}+ onMaskAsked={maskAsked}stage={stage}film={filmSummary}onCanvas={changeCanvas}+ onCanvasPreview={previewCanvas}+ canvasDraft={canvasDraft}onEditLayers={editStageOverrides}+ onPlaceLayers={(to) => stageControl.current?.placeLayers(to)}locked={inspectorLocked}rate={frameRate}fades={clipFades}diff --git a/packages/openfilm/studio/ui/src/components/ResourceInspector.tsx b/packages/openfilm/studio/ui/src/components/ResourceInspector.tsxindex 28ec368..eea5605 100644--- a/packages/openfilm/studio/ui/src/components/ResourceInspector.tsx+++ b/packages/openfilm/studio/ui/src/components/ResourceInspector.tsx@@ -1,6 +1,6 @@import { Download, File as FileIcon } from 'lucide-react';import { useT } from '@/i18n';-import { formatClipDuration, type WorkspaceResource, type WorkspaceResourceKind } from '@/lib/workspace-resources';+import { formatClipDuration, formatFileSize, type WorkspaceResource, type WorkspaceResourceKind } from '@/lib/workspace-resources';import { InspectorPanel } from './InspectorPanel';import { KIND_ICON } from './MediaPreview';@@ -44,25 +44,6 @@ function assetKindLabel(kind: WorkspaceResourceKind, t: (path: string) => stringreturn t('assets.catOther');}-const SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];--/** "12.3 MB": the order of magnitude is what a person reads, not the exact byte count. */-function formatFileSize(bytes: number): string {- if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';- let value = bytes;- let unit = 0;- while (value >= 1024 && unit < SIZE_UNITS.length - 1) {- value /= 1024;- unit += 1;- }- /* no decimals for bytes or past three digits ("248 MB" reads better than "248.3 MB") */- const text = value.toFixed(unit === 0 || value >= 100 ? 0 : 1);- /* 1023.97 KB rounds to 1024.0, which is 1 MB */- return Number(text) >= 1024 && unit < SIZE_UNITS.length - 1- ? `1.0 ${SIZE_UNITS[unit + 1]}`- : `${text} ${SIZE_UNITS[unit]}`;-}-/** Frame rate as people say it: 29.97 keeps two decimals, 30 is 30. */function formatFps(fps: number): string {return Number.isInteger(fps) ? String(fps) : fps.toFixed(2).replace(/\.?0+$/, '');@@ -92,6 +73,19 @@ function AssetFields({ file }: { file: WorkspaceResource }) {if (file.mtimeMs) {rows.push({ label: t('assets.propModified'), value: new Date(file.mtimeMs).toLocaleString() });}+ /* heavy footage's proxy for the preview: being made, ready, or not to be */+ if (file.proxy) {+ const { state, ratio } = file.proxy;+ rows.push({+ label: t('assets.propProxy'),+ value: state === 'making' ? t('media.proxyMaking').replace('{p}', String(Math.round((ratio ?? 0) * 100)))+ : state === 'waiting' ? t('media.proxyWaiting') : state === 'failed' ? t('media.proxyFailed') : t('media.proxyReady'),+ });+ }+ /* a link to media kept elsewhere (a NAS): where it is, or that it cannot be reached now */+ if (file.link) {+ rows.push({ label: t('assets.propLinked'), value: file.link.missing ? `${file.link.to} (${t('media.linkMissing')})` : file.link.to });+ }return (<dl className="py-2">diff --git a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx b/packages/openfilm/studio/ui/src/components/SourcePreview.tsxindex 4f7a394..b044324 100644--- a/packages/openfilm/studio/ui/src/components/SourcePreview.tsx+++ b/packages/openfilm/studio/ui/src/components/SourcePreview.tsx@@ -14,7 +14,7 @@ import type { SourceRange } from '@/lib/media-place';import { formatTimecode, snapToFrame } from '@/lib/timecode';import { type MediaSources, type WorkspaceResource } from '@/lib/workspace-resources';import { isTypingTarget } from './typing-target';-import { MediaPreview } from './MediaPreview';+import { KIND_ICON, MediaPreview } from './MediaPreview';import { PANE_BTN, PANE_ICON } from './dock-pane-bar';import { Tooltip } from './Tooltip';import { ViewerBar } from './ViewerBar';@@ -246,7 +246,12 @@ function MediaPreviewPane({ file, sources, onClose, onPlace }: SourcePreviewProp<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>+ /* a file Studio does not play: what it is, by its icon and name */+ <div className="flex min-w-0 flex-col items-center gap-2 text-center">+ {React.createElement(KIND_ICON[file.kind], { size: 40, strokeWidth: 1.4, className: 'text-[var(--text-muted)]' })}+ <span className="max-w-full truncate text-[13px] font-medium text-[var(--text)]">{file.name}</span>+ <p className="text-[12.5px] text-[var(--text-muted)]">{t('media.cannotPreview')}</p>+ </div>)}</div>{timed ? (diff --git a/packages/openfilm/studio/ui/src/components/StageTransformFrame.tsx b/packages/openfilm/studio/ui/src/components/StageTransformFrame.tsxindex aa11387..bc3637c 100644--- a/packages/openfilm/studio/ui/src/components/StageTransformFrame.tsx+++ b/packages/openfilm/studio/ui/src/components/StageTransformFrame.tsx@@ -9,9 +9,9 @@** Geometry is the frame's own center, size and angle, not its bounding box: a turned thing has a turned frame.*- * Three sets of data attributes: a whole clip's (`data-mg-kind` / `data-mg-handle`), a layer's (`data-layer-kind` /- * `data-layer-handle`) and a crop's in crop mode (`data-crop-kind` / `data-crop-handle`); one pointer press is routed- * by the set it lands on.+ * Four sets of data attributes: a whole clip's (`data-mg-kind` / `data-mg-handle`), a layer's (`data-layer-kind` /+ * `data-layer-handle`), a crop's in crop mode (`data-crop-kind` / `data-crop-handle`) and several clips' together+ * (`data-group-kind` / `data-group-handle`); one pointer press is routed by the set it lands on.*//** The stage's "this one" blue: the frame, picked layers and linked outlines are drawn in it. */export const FRAME_BLUE = '#0d99ff';@@ -84,8 +84,11 @@ export function StageTransformFrame({bounds,}: {frame: FrameGeometry;- /** Which set of handle attributes (see the file head): `mg` for a whole clip, `layer` for a layer, `crop` for a crop. */- scope: 'mg' | 'layer' | 'crop';+ /**+ * Which set of handle attributes (see the file head): `mg` for a whole clip, `layer` for a layer, `crop` for a crop,+ * `group` for several clips selected together.+ */+ scope: 'mg' | 'layer' | 'crop' | 'group';corners?: 'scale' | 'none';edges?: boolean;rotate?: boolean;diff --git a/packages/openfilm/studio/ui/src/components/Timeline.tsx b/packages/openfilm/studio/ui/src/components/Timeline.tsxindex 804c7e1..e546914 100644--- a/packages/openfilm/studio/ui/src/components/Timeline.tsx+++ b/packages/openfilm/studio/ui/src/components/Timeline.tsx@@ -22,6 +22,7 @@ import {Lock,LockOpen,Magnet,+ Paperclip,MessageSquarePlus,MoreHorizontal,ChevronDown,@@ -51,7 +52,6 @@ import {ArrowRightToLine,Pencil,TriangleAlert,- AudioLines,Blend,} from 'lucide-react';import { useT } from '@/i18n';@@ -91,7 +91,10 @@ import {gapAt,insertPointOn,linkedIds,+ magnetOn,+ mainTrackOf,planCloseGap,+ planCloseMainGaps,planLink,planRemove,planRippleTrimTo,@@ -103,7 +106,7 @@ import {} from '@/lib/timeline-edit';import { clipThumbId, indexClipThumbs, thumbIntoOrigin } from '@/lib/thumb-frame';import { THUMB_CELL_PX } from '@/lib/thumb-cache';-import { useTimelinePrefs, writeTimelinePref } from '@/lib/timeline-prefs';+import { followOf, useTimelinePrefs, writeTimelinePref } from '@/lib/timeline-prefs';import { STUDIO_REF_TYPE, type StudioRef } from '@/lib/host';import { orderedRange, rangeLabel, type FilmRange } from '@/lib/studio-refs';import { draftNumbersOf, sameClip, type ChatPoint, type DraftMarks } from '@/lib/chat-marks';@@ -406,8 +409,9 @@ function LandingMark({ landing, pxPerMs }: { landing: DropLanding; pxPerMs: numbtype AssetHint = AssetDropPreview & {/** Set only when snapped to another clip's edge: draws the snap guide. */snapGuideMs: number | null;- /** Onto a track: insert (pushing what follows on) or overwrite (cutting what is there). */- editMode: EditMode;+ /** Onto a track: insert (pushing what follows on) or overwrite (cutting what is there); none: onto free time, or a+ new track when it is taken. */+ editMode: EditMode | undefined;/** Where the clips the drop pushes or cuts are drawn meanwhile, by block id; null: it goes. */ghosts: ReadonlyMap<string, { startMs: number; endMs: number } | null>;};@@ -962,7 +966,13 @@ export const Timeline = React.memo(function Timeline({const snap = prefs.snap;const prefsRef = React.useRef(prefs);prefsRef.current = prefs;- const togglePref = React.useCallback((pref: keyof typeof prefs) => writeTimelinePref(pref, !prefsRef.current[pref]), []);+ /** What turning the magnet on does to the film: the main track closes up (set once runPlan exists, below). */+ const onMagnetOn = React.useRef<() => void>(() => {});+ const togglePref = React.useCallback((pref: keyof typeof prefs) => {+ const on = !prefsRef.current[pref];+ writeTimelinePref(pref, on);+ if (pref === 'magnet' && on) onMagnetOn.current();+ }, []);const [assetHint, setAssetHint] = React.useState<AssetHint | null>(null);const [dropBusy, setDropBusy] = React.useState(false);/* what went wrong (a drop, an edit), or what an edit could not do: said in the toolbar until dismissed */@@ -971,6 +981,8 @@ export const Timeline = React.memo(function Timeline({const [notice, setNotice] = React.useState<string | null>(null);/* the tracks as an edit sees them (lib/timeline-edit): every gesture plans on it */const model = React.useMemo(() => editModelOf(tracks, links), [tracks, links]);+ /** The main track's film.html index: the magnet acts there. */+ const mainDoc = React.useMemo(() => mainTrackOf(model), [model]);const modelRef = React.useRef(model);modelRef.current = model;/** Block ids → the same clips with every clip linked to them, unless the Linked switch is off (or `alone`). */@@ -1330,12 +1342,17 @@ export const Timeline = React.memo(function Timeline({}, [playable, hasLanes, playheadGapPx, totalMs]);/* A scrub follows the pointer from pointerdown to pointerup even outside the timeline (listeners on window). Each- frame previews, release commits: hundreds of seeks would make the sound tear. A click without dragging takes the- same path. */+ frame previews, release commits: hundreds of seeks would make the sound tear. With snapping on, the line snaps to+ clip edges and markers, as CapCut's. A click without dragging takes the same path, and pauses, as CapCut does. */const startScrub = React.useCallback((e: React.PointerEvent, fromRuler = false) => {if (e.button !== 0 || !playable) return;e.preventDefault();- let at = msAtClientX(e.clientX);+ const targets = snap ? snapTargetsFor(allBlocks, '', 0, undefined, snapPointsMs).filter((t) => t.kind !== 'playhead') : [];+ const timeAt = (clientX: number): number => {+ const raw = msAtClientX(clientX);+ return targets.length ? snapMs(raw, targets, pxPerMs).ms : raw;+ };+ let at = timeAt(e.clientX);setScrubMs(at);onScrubPreview(at);lastTold.current = performance.now();@@ -1347,7 +1364,7 @@ export const Timeline = React.memo(function Timeline({let atX = e.clientX;const flush = (): void => {raf = 0;- at = msAtClientX(atX);+ at = timeAt(atX);/* the line every frame (cheap: the rows are memoized without the time) */setScrubMs(at);/* the editor and the picture every SCRUB_TELL_MS (the expensive part) */@@ -1372,7 +1389,7 @@ export const Timeline = React.memo(function Timeline({if (raf) {cancelAnimationFrame(raf);raf = 0;- at = msAtClientX(atX);+ at = timeAt(atX);}document.body.classList.remove('tl-scrubbing');setScrubbing(false);@@ -1384,7 +1401,7 @@ export const Timeline = React.memo(function Timeline({};window.addEventListener('pointermove', move, { passive: true });window.addEventListener('pointerup', up);- }, [msAtClientX, onScrubCommit, onScrubPreview, playable, warmPlayheadAt]);+ }, [msAtClientX, onScrubCommit, onScrubPreview, playable, warmPlayheadAt, snap, allBlocks, snapPointsMs, pxPerMs]);/** The range being pulled on the ruler, before it is the editor's (drawn from here, not re-rendering the editor). */const [rangeDraft, setRangeDraft] = React.useState<FilmRange | null>(null);@@ -1433,14 +1450,17 @@ export const Timeline = React.memo(function Timeline({/*** Send a plan (lib/timeline-edit) as one edit. A ripple that could not close all of its time (a clip on a track it- * reaches is in the way) says so: the clips stay in sync, and the person learns why a gap is left.+ * reaches is in the way) says so: the clips stay in sync, and the person learns why a gap is left. `note`: what+ * else the edit has to say once it is made.*/- const runPlan = React.useCallback(async (plan: EditPlan | null, label: string): Promise<void> => {- if (!onEditOps || !plan?.ops.length) return;+ const runPlan = React.useCallback(async (plan: EditPlan | null, label: string, note?: string): Promise<boolean> => {+ if (!onEditOps || !plan?.ops.length) return false;const err = await onEditOps(plan.ops, label);if (err) setDropError(err);/* not an error: the edit was made, and this says why a gap was left (a warning's look, not an error's) */else if (plan.shortMs > 0) setNotice(t('timeline.rippleShort').replace('{s}', (plan.shortMs / 1000).toFixed(2)));+ else if (note) setNotice(note);+ return !err;}, [onEditOps, t]);/** A gap picked on a track (a click between two clips, or before the first): drawn, and ⌫ closes it. */@@ -1469,13 +1489,25 @@ export const Timeline = React.memo(function Timeline({return now && Math.abs(now.startMs - g.startMs) < TOUCH_MS && Math.abs(now.endMs - g.endMs) < TOUCH_MS ? g : null;});}, [model]);- /** Close the gap picked: what is after it moves back (with sync lock, on every unlocked track). */+ /* the magnet turned on closes up the main track, as CapCut's: its gaps go, in one step */+ onMagnetOn.current = () => {+ void runPlan(planCloseMainGaps(modelRef.current, followOf(prefsRef.current)), 'history.stepMainClosed');+ };+ /**+ * Close a gap: what is after it moves back (with sync lock, on every unlocked track; on its own track alone when a+ * synced track has no room, and a notice says so).+ */+ const closeGapOn = React.useCallback((g: { track: number; startMs: number; endMs: number }) => {+ const plan = planCloseGap(modelRef.current, g.track, g, followOf(prefsRef.current));+ void runPlan(plan, 'history.stepGapClosed', plan.alone ? t('timeline.gapClosedAlone') : undefined);+ }, [runPlan, t]);+ /** Close the gap picked. */const closeGap = React.useCallback(() => {const g = gap;if (!g) return;setGap(null);- void runPlan(planCloseGap(modelRef.current, g.track, g, { sync: prefsRef.current.sync }), 'history.stepGapClosed');- }, [gap, runPlan]);+ closeGapOn(g);+ }, [gap, closeGapOn]);/** Clips inside the marquee are framed while it is drawn — "what does this box catch" is the whole question. */const framed = React.useMemo(@@ -1652,7 +1684,7 @@ export const Timeline = React.memo(function Timeline({* Delete clips: locked rows untouched. Planned (lib/timeline-edit) as one edit; with `ripple` the time they took* closes (with sync lock on every unlocked track). Without onEditOps, one by one through onRemove(Many).*/- const removeMany = React.useCallback(async (blocks: readonly TimelineBlock[], ripple = false) => {+ const removeMany = React.useCallback(async (blocks: readonly TimelineBlock[], ripple: boolean | 'main' = false) => {const locked = new Set(tracks.filter((tr) => tr.locked).flatMap((tr) => tr.blocks.map((b) => b.id)),);@@ -1663,7 +1695,7 @@ export const Timeline = React.memo(function Timeline({if (onEditOps) {const ids = targets.flatMap((b) => (b.clipId ? [b.clipId] : []));const label = ids.length <= 2 ? `history.stepRemoved|${ids.join(', ')}` : 'history.stepRemove';- await runPlan(planRemove(modelRef.current, ids, { ripple, sync: prefsRef.current.sync }), label);+ await runPlan(planRemove(modelRef.current, ids, { ripple, ...followOf(prefsRef.current) }), label);return;}if (onRemoveMany) {@@ -1680,34 +1712,40 @@ export const Timeline = React.memo(function Timeline({}, [onEditOps, onRemove, onRemoveMany, tracks, setSelected, runPlan]);/**- * Ripple delete (⇧Delete, the menu, or Delete with the magnet on): what comes after closes the gap, on the clips'- * tracks and with sync lock every unlocked track. One edit, one ⌘Z.+ * Ripple delete (⇧Delete, the menu): what comes after closes the gap, on the clips' tracks and with sync lock every+ * unlocked track, or with linkage the main track's, carrying the others. `'main'` (Delete with the magnet on): only+ * the main track closes up, the others keep their gaps. One edit, one ⌘Z.*/- const rippleRemove = React.useCallback(async (blocks: readonly TimelineBlock[], waited = false) => {+ const rippleRemove = React.useCallback(async (blocks: readonly TimelineBlock[], waited = false, how: true | 'main' = true) => {/* a track with clips not drawn yet (an undo just put them back): wait for them, or the gap closes onto them */const ids = new Set(blocks.map((b) => b.id));if (!waited && tracks.some((tr) => tr.incomplete && tr.blocks.some((b) => ids.has(b.id)))) {- const wait = { keys: blocks.map((b) => b.clipId ?? b.id) };+ const wait = { keys: blocks.map((b) => b.clipId ?? b.id), how };rippleWait.current = wait;/* past the wait it goes with what is drawn: a page that never loads must not block it for good */window.setTimeout(() => { if (rippleWait.current === wait) rippleRetry.current(true); }, RIPPLE_WAIT_MS);return;}rippleWait.current = null;- await removeMany(blocks, true);+ await removeMany(blocks, how);}, [removeMany, tracks]);/* a waiting ripple delete goes once its tracks are whole, its clips found again by id (their places may havechanged meanwhile) */- const rippleWait = React.useRef<{ keys: readonly string[] } | null>(null);+ const rippleWait = React.useRef<{ keys: readonly string[]; how: true | 'main' } | null>(null);const rippleRetry = React.useRef((_late: boolean) => {});rippleRetry.current = (late: boolean) => {const wait = rippleWait.current;if (!wait) return;const mine = (b: TimelineBlock) => wait.keys.includes(b.clipId ?? b.id);if (!late && tracks.some((tr) => tr.incomplete && tr.blocks.some(mine))) return;- void rippleRemove(tracks.flatMap((tr) => tr.blocks).filter(mine), true);+ void rippleRemove(tracks.flatMap((tr) => tr.blocks).filter(mine), true, wait.how);};React.useEffect(() => { rippleRetry.current(false); }, [tracks]);+ /** Delete (⌫, ⌘X, the menu): with the magnet the main track closes up, the other tracks keep their gaps. */+ const magnetRemove = React.useCallback(+ (blocks: readonly TimelineBlock[]) => (prefsRef.current.magnet ? rippleRemove(blocks, false, 'main') : removeMany(blocks)),+ [rippleRemove, removeMany],+ );/* selected clips: Delete / Backspace deletes, ⌘C copies, ⌘V pastes at the playhead; not while typing */React.useEffect(() => {@@ -1746,7 +1784,7 @@ export const Timeline = React.memo(function Timeline({if ((!onRemove && !onRemoveMany && !onEditOps) || !picked.length) return;e.preventDefault();/* with the magnet on a delete closes the gap it leaves, as ⇧Delete always does */- void (e.shiftKey || prefsRef.current.magnet ? rippleRemove(picked) : removeMany(picked));+ void (e.shiftKey ? rippleRemove(picked) : magnetRemove(picked));return;}const mod = e.metaKey || e.ctrlKey;@@ -1777,7 +1815,7 @@ export const Timeline = React.memo(function Timeline({window.addEventListener('keydown', onKey);return () => window.removeEventListener('keydown', onKey);/* the playhead is read from a ref: as a dependency the listener would be swapped twenty times a second */- }, [onRemove, onRemoveMany, onEditOps, onCopy, onPaste, hasClipboard, removeMany, rippleRemove, selected, tracks, setSelected, playable, zoomBy, zoomTo, gap, closeGap, pickedTransition, onTransition, onPickTransition]);+ }, [onRemove, onRemoveMany, onEditOps, onCopy, onPaste, hasClipboard, removeMany, rippleRemove, magnetRemove, selected, tracks, setSelected, playable, zoomBy, zoomTo, gap, closeGap, pickedTransition, onTransition, onPickTransition]);/* whether the last press was on the timeline (for ⌘A); capture phase, since presses here are often stopped */React.useEffect(() => {@@ -1820,13 +1858,25 @@ export const Timeline = React.memo(function Timeline({}, [allBlocks, pxPerMs, snap, snapPointsMs]);/**- * Where a drop from the media pane lands and what it does there, for the preview and the drop alike. Onto a track,- * with the magnet (⌥: the other way): an insert at the insert point of the track (lib/timeline-edit insertPointOn),+ * How a drop from the media pane goes in. On the main track with the magnet: an insert (⌥: an overwrite). Elsewhere+ * with the magnet, as CapCut's: no edit, so it never covers a clip — a taken spot opens a new track (⌥: an+ * overwrite). Without the magnet: an overwrite (⌥: an insert).+ */+ const dropModeAt = React.useCallback((hit: { lane: number; band: DropBand }, alt: boolean): EditMode | undefined => {+ const doc = hit.band === 'body' ? tracks[hit.lane]?.docIndex : undefined;+ const { magnet } = prefsRef.current;+ if (magnet && !magnetOn(modelRef.current, doc, magnet)) return alt ? 'overwrite' : undefined;+ return magnetOn(modelRef.current, doc, magnet) !== alt ? 'insert' : 'overwrite';+ }, [tracks]);++ /**+ * Where a drop from the media pane lands and what it does there, for the preview and the drop alike. Onto the main+ * track with the magnet (⌥: the other way): an insert at the insert point of the track (lib/timeline-edit insertPointOn),* pushing what follows on; without: an overwrite where it was let go. The clips it pushes or cuts are drawn moved.*/const assetLanding = React.useCallback((file: ResourceDragItem, clientX: number, clientY: number, altKey: boolean): AssetHint | null => {- const editMode: EditMode = prefsRef.current.magnet !== altKey ? 'insert' : 'overwrite';const laneHit = laneHitAtY(clientY);+ const editMode = dropModeAt(laneHit, altKey);const pointerMs = dropMsAtClientX(clientX);const snapped = dropAt(pointerMs);const preview = assetDropPreview(file, tracks, laneHit, snapped.ms, onEditOps ? editMode : undefined);@@ -1834,9 +1884,9 @@ export const Timeline = React.memo(function Timeline({const docIndex = preview.lane != null ? tracks[preview.laneIndex]?.docIndex : undefined;const ghosts = new Map<string, { startMs: number; endMs: number } | null>();let startMs = preview.startMs;- if (docIndex != null && !preview.error && onEditOps) {+ if (docIndex != null && !preview.error && onEditOps && editMode) {if (editMode === 'insert') startMs = insertPointOn(modelRef.current, docIndex, pointerMs, startMs);- const plan = planRoom(modelRef.current, [{ track: docIndex, startMs, endMs: startMs + preview.endMs - preview.startMs }], { mode: editMode, sync: prefsRef.current.sync });+ const plan = planRoom(modelRef.current, [{ track: docIndex, startMs, endMs: startMs + preview.endMs - preview.startMs }], { mode: editMode, ...followOf(prefsRef.current) });for (const [clipId, at] of plan.placed) {const b = allBlocks.find((x) => x.clipId === clipId);if (b) ghosts.set(b.id, at ? { startMs: at.startMs, endMs: at.endMs } : null);@@ -1851,7 +1901,7 @@ export const Timeline = React.memo(function Timeline({ghosts,/* the guide only when release lands right there: not for a new track, a refused spot or an insert moved to acut (same rule as moving clips) */- snapGuideMs: snapped.target && snapped.target.kind !== 'playhead' && !preview.newTrack && !preview.error && !moved+ snapGuideMs: snapped.target && !preview.newTrack && !preview.error && !moved? snapped.target.ms: null,};@@ -1888,7 +1938,7 @@ export const Timeline = React.memo(function Timeline({const replacing = replaced ? tracks.flatMap((tr) => tr.blocks).find((b) => b.id === replaced && b.clipId) : undefined;const dragged = replacing ? readResourceDragData(e.dataTransfer) ?? peekResourceDrag() : null;if (replacing && dragged) { onReplaceDrop!(replacing, dragged); return; }- const editMode: EditMode = prefsRef.current.magnet !== e.altKey ? 'insert' : 'overwrite';+ const editMode = dropModeAt(laneHitAtY(e.clientY), e.altKey);if (isComputerFileDrag(e.dataTransfer)) {const files = [...e.dataTransfer.files];if (!onDropFiles || !files.length) return;@@ -1969,8 +2019,6 @@ export const Timeline = React.memo(function Timeline({clicked?: TimelineBlock;/** Right-clicked in a gap on a track: it can be closed. */gap?: { track: number; startMs: number; endMs: number };- /** A cut clicked or right-clicked: transitions go on it. */- cut?: CutRef;/** A transition's mark right-clicked. */transition?: FilmTransition;}@@ -2400,17 +2448,6 @@ export const Timeline = React.memo(function Timeline({window.addEventListener('pointerup', up);window.addEventListener('pointercancel', up);}, [onTransition, onPickTransition, fps, dropMsAtClientX]);- /** A press on a cut that comes up where it went down: the cut's menu (its transitions), at the pointer. */- const openCutIfClick = React.useCallback((e: React.PointerEvent, cut: CutRef) => {- const fromX = e.clientX, fromY = e.clientY;- const lane = tracks.find((tr) => tr.blocks.some((b) => b.clipId === cut.a))?.lane ?? null;- const up = (ev: PointerEvent) => {- window.removeEventListener('pointerup', up);- if (Math.abs(ev.clientX - fromX) >= DRAG_THRESHOLD_PX || Math.abs(ev.clientY - fromY) >= DRAG_THRESHOLD_PX) return;- setMenu({ x: ev.clientX, y: ev.clientY, blocks: [], lane, atMs: 0, cut });- };- window.addEventListener('pointerup', up);- }, [tracks]);/** Where a clip is drawn while a gesture or a drop changes it (null: where it is). */const placedOf = React.useCallback((id: string): { startMs: number; endMs: number; gone?: boolean } | null => {@@ -2779,7 +2816,10 @@ export const Timeline = React.memo(function Timeline({})}{/* the cuts between clips that touch: dragged, a roll (one gets longer, the other shorter); not while a moveis in hand, and not on a locked track */}- {!track.locked && mode === 'select' && !(drag.preview?.mode === 'move' && !drag.preview.landed) ? cutsOf(track.blocks).map(([a, b]) => {+ {/* a cut's roll handle: not on the main track with the magnet, where a cut's edges trim and what follows closes+ up, as CapCut's (it has no roll) */}+ {!track.locked && mode === 'select' && !(drag.preview?.mode === 'move' && !drag.preview.landed)+ && !(prefs.magnet && track.docIndex != null && track.docIndex === mainDoc) ? cutsOf(track.blocks).map(([a, b]) => {const pa = placedOf(a.id);const pb = placedOf(b.id);if (pa?.gone || pb?.gone || !drag.can(a).resize || !drag.can(b).resize) return null;@@ -2796,16 +2836,8 @@ export const Timeline = React.memo(function Timeline({onPointerDown={(e) => {e.stopPropagation();if (e.button !== 0) return;- /* a drag rolls the cut (and selects the clip before it then); a click is the cut's alone: its- transitions (lib/transitions) */+ /* a drag rolls the cut (and selects the clip before it then) */drag.start(e, a, 'roll', undefined, b, () => pickForTrim(e, a));- if (onTransition && a.clipId && b.clipId) openCutIfClick(e, { a: a.clipId, b: b.clipId });- }}- onContextMenu={(e) => {- if (!onTransition || !a.clipId || !b.clipId) return;- e.preventDefault();- e.stopPropagation();- setMenu({ x: e.clientX, y: e.clientY, blocks: [], lane: track.lane, atMs: atMs, cut: { a: a.clipId, b: b.clipId } });}}><span aria-hidden className="pointer-events-none absolute inset-y-[2px] left-1/2 w-[2px] -translate-x-1/2 rounded-full bg-[var(--tl-select)] opacity-0 transition-opacity group-hover/roll:opacity-90" />@@ -2884,7 +2916,8 @@ export const Timeline = React.memo(function Timeline({tracks, trackPx, pxPerMs, ringed, selected, drag, waveUrl, mode, msAtClientX, onSplit, clipThumbs, posters, mediaTrouble, t,openBlockMenu, openLaneMenu, onEditBlocks, collapseIfClick, selectOne, setSelected, clipElements, thumbWindow, view.width,chatClip, chatDraft, placedOf, pickForTrim, gap, withLinked, runSplit, trackOverlay,- fadeOfBlock, fadeDrag, startFade, transitions, transitionDrag, pickedTransition, onPickTransition, onTransition, startTransitionResize, openCutIfClick,+ fadeOfBlock, fadeDrag, startFade, transitions, transitionDrag, pickedTransition, onPickTransition, onTransition, startTransitionResize,+ prefs.magnet, mainDoc,]);const tickMarks = React.useMemo(() => ticks.map(({ ms, label }) => {@@ -2982,11 +3015,9 @@ export const Timeline = React.memo(function Timeline({return out;}, [allBlocks, assetHint, drag.preview, padTop, tracks, onEditOps]);- /* the snap guide only when snapped to an edge (or zero) and landing right there (useBlockDrag landsFlush); not for- the playhead, which is already a line */- const snapGuideMs = drag.preview?.snappedTo && drag.preview.snappedTo.kind !== 'playhead'- ? drag.preview.snappedTo.ms- : (assetHint?.snapGuideMs ?? null);+ /* the snap guide when snapped (to an edge, zero, a marker or the playhead) and landing right there (useBlockDrag+ landsFlush): over the playhead too, so the person sees it caught */+ const snapGuideMs = drag.preview?.snappedTo ? drag.preview.snappedTo.ms : (assetHint?.snapGuideMs ?? null);/** The selected clips, in timeline order. */const selectedBlocks = React.useMemo(@@ -2996,20 +3027,24 @@ export const Timeline = React.memo(function Timeline({/*** Ripple trim to the playhead (Q / W): `start` takes the head of the clip off up to the playhead, `end` its tail- * from it, and what follows closes up (with sync lock on every unlocked track). On the clips given, else the- * selected ones the playhead is inside, else the topmost under it; the clips linked to them go along.+ * from it, and what follows closes up (with sync lock on every unlocked track; with linkage, on the main track, the+ * other tracks along). On the clips given, else the selected ones the playhead is inside, else the main track's+ * under it, else the topmost under it; the clips linked to them go along. After Q the playhead goes to the clip's+ * start, where what was under it now is, as CapCut's.*/const rippleTrimToPlayhead = React.useCallback((edge: 'start' | 'end', given?: readonly TimelineBlock[]) => {const atMs = timeMsRef.current;const lockedRow = (b: TimelineBlock) => tracks.some((tr) => tr.locked && tr.blocks.some((x) => x.id === b.id));const inside = (b: TimelineBlock) => Boolean(b.clipId) && !lockedRow(b) && atMs > b.startMs + TOUCH_MS && atMs < b.endMs - TOUCH_MS;const all = tracks.flatMap((tr) => tr.blocks);- const main = (given ?? all.filter((b) => selectedRef.current.includes(b.id))).find(inside) ?? all.find(inside);+ const mainIndex = mainTrackOf(modelRef.current);+ const onMain = tracks.filter((tr) => tr.docIndex != null && tr.docIndex === mainIndex).flatMap((tr) => tr.blocks);+ const main = (given ?? all.filter((b) => selectedRef.current.includes(b.id))).find(inside) ?? onMain.find(inside) ?? all.find(inside);if (!main?.clipId) return;const ids = prefsRef.current.linked ? [main.clipId, ...linkedIds(modelRef.current, [main.clipId]).filter((id) => id !== main.clipId)] : [main.clipId];- const plan = planRippleTrimTo(modelRef.current, ids, edge, atMs, { sync: prefsRef.current.sync });- void runPlan(plan, `history.stepRippleTrimmed|${main.clipId}`);- }, [tracks, runPlan]);+ const plan = planRippleTrimTo(modelRef.current, ids, edge, atMs, followOf(prefsRef.current));+ void runPlan(plan, `history.stepRippleTrimmed|${main.clipId}`).then((done) => { if (done && edge === 'start') onSeek(main.startMs); });+ }, [tracks, runPlan, onSeek]);/** Link clips (one `data-link`), or unlink them. */const linkBlocks = React.useCallback((blocks: readonly TimelineBlock[]) => {@@ -3048,12 +3083,13 @@ export const Timeline = React.memo(function Timeline({const clips = picked().filter((b) => b.loc);if (!clips.length) return;onCopy?.(clips);- void (prefsRef.current.magnet ? rippleRemove(clips) : removeMany(clips));+ void magnetRemove(clips);},nudge: (frames) => {const ids = picked().flatMap((b) => (b.clipId ? [b.clipId] : []));if (!ids.length) return;- const plan = planNudge(modelRef.current, ids, frames, { mode: prefsRef.current.magnet ? 'insert' : 'overwrite', sync: prefsRef.current.sync });+ /* with the magnet nothing is overwritten (on the main track or off it): into free time only */+ const plan = planNudge(modelRef.current, ids, frames, { mode: prefsRef.current.magnet ? 'insert' : 'overwrite', ...followOf(prefsRef.current) });if (plan) void runPlan(plan, 'history.stepMove');},zoomFit: () => {@@ -3063,13 +3099,13 @@ export const Timeline = React.memo(function Timeline({target: () => tracks.find((tr) => tr.lane === targetLaneRef.current)?.docIndex ?? null,};return () => { commandsRef.current = null; };- }, [commandsRef, tracks, rippleTrimToPlayhead, closeGap, linkBlocks, unlinkBlocks, togglePref, withLinked, runSplit, onCopy, rippleRemove, removeMany, runPlan, zoomTo]);+ }, [commandsRef, tracks, rippleTrimToPlayhead, closeGap, linkBlocks, unlinkBlocks, togglePref, withLinked, runSplit, onCopy, magnetRemove, runPlan, zoomTo]);- /** A transition's entries for a cut (or a clip's edge): each put there at its default length, in one step. */+ /** A fade's entry for a clip's edge: put there at its default length, in one step. */const transitionEntries = React.useCallback((cut: CutRef, kinds: readonly TransitionKind[]): ContextMenuEntry[] => kinds.map((kind) => ({id: `tr-${kind}-${cut.a ?? ''}-${cut.b ?? ''}`,label: t(`transitions.${kind}`),- icon: kind === 'crossfade' ? <AudioLines size={14} /> : <Blend size={14} />,+ icon: <Blend size={14} />,onSelect: () => { void onTransition?.({ kind: 'add', type: kind, cut }).then((err) => { if (err) setDropError(err); }); },})), [t, onTransition]);@@ -3081,18 +3117,13 @@ export const Timeline = React.memo(function Timeline({const menuItems = React.useMemo((): ContextMenuEntry[] => {if (!menu) return [];if (menu.head) return headEntries(menu.head);- /* a cut, or a transition's mark: the transitions that go there, and taking one away */- if (menu.cut || menu.transition) {- const cut = menu.cut ?? { a: menu.transition!.a, b: menu.transition!.b };- const there = menu.transition ?? transitions?.find((x) => x.a === cut.a && x.b === cut.b);- return [- ...(menu.cut ? transitionEntries(cut, ['dissolve', 'dip-black', 'dip-white', 'crossfade']) : []),- ...(there && menu.cut ? [{ id: 'tr-sep', separator: true } as const] : []),- ...(there ? [{- id: 'tr-remove', label: t('transitions.remove'), icon: <Trash2 size={14} />, danger: true, shortcut: '⌫',- onSelect: () => { void onTransition?.({ kind: 'remove', key: there.key }).then((err) => { if (err) setDropError(err); }); onPickTransition?.(null); },- }] : []),- ];+ /* a transition's mark (one the film has; none is put on from a menu: an agent writes transitions): taking it away */+ if (menu.transition) {+ const there = menu.transition;+ return [{+ id: 'tr-remove', label: t('transitions.remove'), icon: <Trash2 size={14} />, danger: true, shortcut: '⌫',+ onSelect: () => { void onTransition?.({ kind: 'remove', key: there.key }).then((err) => { if (err) setDropError(err); }); onPickTransition?.(null); },+ }];}const picked = menu.blocks;/* one clip, or one clip with the clips linked to it: the entries about a single clip are about the one clicked */@@ -3121,7 +3152,7 @@ export const Timeline = React.memo(function Timeline({label: t('timeline.menuCloseGap'),icon: <BetweenHorizontalStart size={14} />,shortcut: '⌫',- onSelect: () => { void runPlan(planCloseGap(modelRef.current, found.track, found, { sync: prefsRef.current.sync }), 'history.stepGapClosed'); },+ onSelect: () => closeGapOn(found),});}return entries;@@ -3200,7 +3231,7 @@ export const Timeline = React.memo(function Timeline({onSelect: () => { void onDetachAudio(one); },});}- /* fades and transitions at the clip's start and end (lib/transitions) */+ /* fades at the clip's start and end (lib/transitions) */if (one && onTransition && one.clipId && !pickedLocked) {const row = tracks.find((tr) => tr.blocks.some((b) => b.id === one.id));const at = (ms: number) => (row?.docIndex != null ? cutNear(modelRef.current, row.docIndex, ms, 1) : null);@@ -3211,8 +3242,6 @@ export const Timeline = React.memo(function Timeline({{ id: 'tr-sep-1', separator: true },...transitionEntries(startCut, ['fade-in']),...transitionEntries(endCut, ['fade-out']),- { id: 'tr-start', label: t('transitions.atStart'), icon: <Blend size={14} />, submenu: transitionEntries(startCut, ['dissolve', 'dip-black', 'dip-white', 'crossfade']) },- { id: 'tr-end', label: t('transitions.atEnd'), icon: <Blend size={14} />, submenu: transitionEntries(endCut, ['dissolve', 'dip-black', 'dip-white', 'crossfade']) },{ id: 'tr-sep-2', separator: true },);}@@ -3276,7 +3305,7 @@ export const Timeline = React.memo(function Timeline({hint: pickedLocked ? t('timeline.trackLocked') : t('timeline.menuCopyNone'),shortcut: '⌫',/* as ⌫: with the magnet on, the gap closes */- onSelect: () => { void (prefsRef.current.magnet ? rippleRemove(picked) : removeMany(picked)); },+ onSelect: () => { void magnetRemove(picked); },});if (onEditOps) {out.push({@@ -3294,8 +3323,8 @@ export const Timeline = React.memo(function Timeline({return out;}, [menu, t, onSplit, onDetachAudio, onRemove, onRemoveMany, onCopy, onPaste, onExportBlock, mediaTrouble, relinkCandidates,- onRelink, hasClipboard, runSplit, removeMany, rippleRemove, onEditOps, tracks, blockMenuExtra, headEntries, withLinked,- runPlan, rippleTrimToPlayhead, linkBlocks, unlinkBlocks, transitions, onTransition, onPickTransition, transitionEntries,+ onRelink, hasClipboard, runSplit, removeMany, rippleRemove, magnetRemove, onEditOps, tracks, blockMenuExtra, headEntries, withLinked,+ runPlan, closeGapOn, rippleTrimToPlayhead, linkBlocks, unlinkBlocks, transitions, onTransition, onPickTransition, transitionEntries,]);/* ── the bar beside the selection (SelectionToolbar): what was picked last, the clips, the range or a point ── */@@ -3370,7 +3399,7 @@ export const Timeline = React.memo(function Timeline({out.push({id: 'delete', label: t('timeline.removeBlock'), icon: <Trash2 size={14} />, shortcut: '⌫', danger: true,disabled: pickedLocked || !picked.some((b) => b.loc), hint: lockedHint,- onSelect: () => { void (prefs.magnet ? rippleRemove(picked) : removeMany(picked)); },+ onSelect: () => { void magnetRemove(picked); },});}out.push({@@ -3523,8 +3552,8 @@ export const Timeline = React.memo(function Timeline({) : null}</div>- {/* the switches (lib/timeline-prefs): the magnet (insert, ripple; off: overwrite), sync lock (ripples move every- unlocked track), linked clips, snapping */}+ {/* the switches (lib/timeline-prefs): the main-track magnet (insert, ripple there; off: overwrite), linkage (the+ main track carries what rides on it), sync lock (ripples move every unlocked track), linked clips, snapping */}{onEditOps ? <><span data-timeline-magnet={prefs.magnet ? '1' : '0'}><ToolButton onClick={() => togglePref('magnet')} active={prefs.magnet} label={t('timeline.magnet')}@@ -3532,6 +3561,12 @@ export const Timeline = React.memo(function Timeline({<Magnet size={15} /></ToolButton></span>+ <span data-timeline-linkage={prefs.linkage ? '1' : '0'}>+ <ToolButton onClick={() => togglePref('linkage')} active={prefs.linkage} label={t('timeline.linkage')}+ hint={prefs.linkage ? t('timeline.linkageOn') : t('timeline.linkageOff')}>+ <Paperclip size={15} />+ </ToolButton>+ </span><span data-timeline-sync={prefs.sync ? '1' : '0'}><ToolButton onClick={() => togglePref('sync')} active={prefs.sync} label={t('timeline.sync')}hint={prefs.sync ? t('timeline.syncOn') : t('timeline.syncOff')}>@@ -3941,6 +3976,8 @@ function GestureLabel({ tip, left, top }: { tip: GestureTip; left: number; top:>{what} {signedSeconds(tip.deltaMs)}{tip.lengthMs != null ? <span className="opacity-75"> · {(tip.lengthMs / 1000).toFixed(2)} s</span> : null}+ {/* the source ends here: why the edge stops */}+ {tip.sourceEnd ? <span> · {t('timeline.tip.sourceEnd')}</span> : null}</div>);}diff --git a/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx b/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsxindex c2e787f..c5b31da 100644--- a/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx+++ b/packages/openfilm/studio/ui/src/components/export/ExportCenter.tsx@@ -17,7 +17,7 @@ import {import React from 'react';import { createPortal } from 'react-dom';-import { useT } from '@/i18n';+import { useLanguage, useT } from '@/i18n';import { studioHost } from '@/lib/host';import { MenuSelect } from '@/components/MenuSelect';import { CustomFrame } from '@/components/FramePicker';@@ -57,10 +57,10 @@ import { FILM_FRAME_IDS, filmFrameBox, filmFrameRatio, type FilmFrameFill, typetype Dest = 'social' | 'video' | 'alpha' | 'nle' | 'gif' | 'audio' | 'subtitles' | 'images' | 'slides' | 'project';const DESTS: readonly { id: Dest; icon: React.ReactNode }[] = [- { id: 'social', icon: <MonitorPlay size={16} /> },{ id: 'video', icon: <Film size={16} /> },- { id: 'alpha', icon: <Layers size={16} /> },{ id: 'nle', icon: <Clapperboard size={16} /> },+ { id: 'social', icon: <MonitorPlay size={16} /> },+ { id: 'alpha', icon: <Layers size={16} /> },{ id: 'gif', icon: <Sparkles size={16} /> },{ id: 'audio', icon: <AudioLines size={16} /> },{ id: 'subtitles', icon: <Captions size={16} /> },@@ -69,6 +69,10 @@ const DESTS: readonly { id: Dest; icon: React.ReactNode }[] = [{ id: 'project', icon: <FolderArchive size={16} /> },];+/** Editors' names, never translated. */+const NLE_APP_NAME = { premiere: 'Premiere Pro', resolve: 'DaVinci Resolve' } as const;+const DRAFT_APP_NAME = { jianying: '剪映', capcut: 'CapCut' } as const;+/** "As now" in a frame choice: the delivery frame picked beside the player. */type FrameChoice = FilmFrameId | 'current';@@ -101,7 +105,9 @@ interface Settings {alpha: { codec: ExportVideoCodec; source: string; shortEdge: number; scale: number; fps: number; audio: boolean };audio: { format: 'wav' | 'm4a' | 'mp3'; mix: boolean; stems: boolean };/** For an editing program: the sound as clips or as mixed stems. */- nle: { fps: number | 'source'; audio: 'clips' | 'stems'; subtitles: boolean };+ /** the app it is for: `draft` 剪映 (in Chinese) or CapCut (elsewhere), the same draft; `auto`: the draft when that app+ is on this computer, else Premiere Pro */+ nle: { app: 'auto' | 'draft' | 'premiere' | 'resolve'; fps: number | 'source'; audio: 'clips' | 'stems'; subtitles: boolean };subtitles: { format: 'srt' | 'vtt' | 'txt' };images: { format: 'png' | 'jpg'; shortEdge: number; frame: FrameChoice; fill: FilmFrameFill; burn: boolean };slides: { format: 'pptx' | 'pdf'; shortEdge: number; frame: FrameChoice; fill: FilmFrameFill; burn: boolean };@@ -112,7 +118,7 @@ interface Settings {}const DEFAULTS: Settings = {- dest: 'social',+ dest: 'video',presets: ['youtube'],socialQuality: 'high',socialSubs: 'auto',@@ -122,7 +128,7 @@ const DEFAULTS: Settings = {gif: { width: 640, fps: 15, frame: 'current', fill: 'contain', burn: true },alpha: { codec: 'prores4444', source: WHOLE_FILM, shortEdge: 1080, scale: 1, fps: 30, audio: true },audio: { format: 'wav', mix: true, stems: false },- nle: { fps: 'source', audio: 'clips', subtitles: true },+ nle: { app: 'auto', fps: 'source', audio: 'clips', subtitles: true },subtitles: { format: 'srt' },images: { format: 'png', shortEdge: 1080, frame: 'current', fill: 'contain', burn: false },slides: { format: 'pptx', shortEdge: 1080, frame: 'current', fill: 'contain', burn: false },@@ -219,7 +225,10 @@ export interface ExportCenterProps {export function ExportCenter(props: ExportCenterProps) {const { open, onClose } = props;const t = useT();+ const language = useLanguage();const [can, setCan] = React.useState<ExportCapabilities | null>(null);+ /** 剪映 and CapCut on this computer: an editing project for one goes into its drafts */+ const [draftApps, setDraftApps] = React.useState<{ jianying: boolean; capcut: boolean }>({ jianying: false, capcut: false });const [s, setS] = React.useState<Settings>(DEFAULTS);const [hydrated, setHydrated] = React.useState(false);const [range, setRange] = React.useState<{ on: boolean; from: number; to: number }>({ on: false, from: 0, to: 0 });@@ -246,7 +255,7 @@ export function ExportCenter(props: ExportCenterProps) {setWorking(null);setFolderDraft(null);setRange((r) => ({ ...r, on: false }));- void listExports(props.projectId).then((r) => { setCan(r.can); setDefaultFolder(r.folder); setCaptionCount(r.subtitles ?? 0); setProjectSizes(r.project ?? null); }).catch(() => {});+ void listExports(props.projectId).then((r) => { setCan(r.can); setDraftApps({ jianying: Boolean(r.drafts?.jianying), capcut: Boolean(r.drafts?.capcut) }); setDefaultFolder(r.folder); setCaptionCount(r.subtitles ?? 0); setProjectSizes(r.project ?? null); }).catch(() => {});// eslint-disable-next-line react-hooks/exhaustive-deps}, [open]);@@ -335,6 +344,16 @@ export function ExportCenter(props: ExportCenterProps) {const videoCodec: ExportVideoCodec = codecAvailable(s.video.codec, can) && VIDEO_CODECS.includes(s.video.codec) ? s.video.codec : 'h264';const alphaCodec: ExportVideoCodec = EXPORT_ALPHA_CODECS.includes(s.alpha.codec) && codecAvailable(s.alpha.codec, can) ? s.alpha.codec : 'prores4444';const audioFormat = s.audio.format === 'mp3' && can && !can.mp3 ? 'wav' : s.audio.format;+ /* the same draft is 剪映's or CapCut's: the one on this computer, else (both or neither) 剪映 in Chinese and CapCut in+ any other language; always by its own name */+ const known: 'jianying' | 'capcut' = language === 'zh-CN' ? 'jianying' : 'capcut';+ const draftApp = draftApps[known] || !draftApps[known === 'jianying' ? 'capcut' : 'jianying'] ? known : known === 'jianying' ? 'capcut' : 'jianying';+ const draftHere = draftApps[draftApp];+ /** a translation naming the draft's app */+ const tApp = (path: string) => t(path).replaceAll('{app}', DRAFT_APP_NAME[draftApp]);+ const nleApp = s.nle.app === 'auto' ? (draftHere ? 'draft' : 'premiere') : s.nle.app;+ /* a draft goes into its app's drafts folder, whatever folder is picked */+ const toDrafts = dest === 'nle' && nleApp === 'draft' && draftHere;const codecName = (c: ExportVideoCodec) => CODEC_LABEL[c] + (c === 'png' ? ` ${t('exportCenter.sequence')}` : '');/* the parts of the project asked that it has (a part it has none of is left out) */@@ -377,8 +396,8 @@ export function ExportCenter(props: ExportCenterProps) {}case 'nle':return [{- kind: 'nle', fps: s.nle.fps === 'source' ? (nleSourceFps ?? projectFps) : s.nle.fps, audio: s.nle.audio, media: 'copy',- subtitles: s.nle.subtitles, label: t('exportCenter.nleTitle'),+ kind: 'nle', format: nleApp === 'draft' ? draftApp : 'xml', fps: s.nle.fps === 'source' ? (nleSourceFps ?? projectFps) : s.nle.fps, audio: s.nle.audio, media: 'copy',+ subtitles: s.nle.subtitles, label: nleApp === 'draft' ? tApp('exportCenter.nleDraftTitle') : `${NLE_APP_NAME[nleApp]} XML`,}];case 'subtitles':return [{ kind: 'subtitles', format: s.subtitles.format, label: s.subtitles.format === 'txt' ? t('exportCenter.transcript') : s.subtitles.format.toUpperCase(), ...ranged }];@@ -399,7 +418,7 @@ export function ExportCenter(props: ExportCenterProps) {}];}// eslint-disable-next-line react-hooks/exhaustive-deps- }, [dest, s, can, rangeSec?.[0], rangeSec?.[1], props.frame, blocks, nleSourceFps, captions, projectParts]);+ }, [dest, s, can, nleApp, draftApp, rangeSec?.[0], rangeSec?.[1], props.frame, blocks, nleSourceFps, captions, projectParts]);/* a range, not a size: what is in the picture decides a video's or a GIF's size (export-spec.ts); sound is exact */const estBytes = React.useMemo(() => requests.reduce<[number, number]>(([low, high], r) => {@@ -547,7 +566,7 @@ export function ExportCenter(props: ExportCenterProps) {<span className={`block text-[13px] font-medium ${on ? 'text-[var(--text)]' : 'text-[var(--text-muted)]'}`}>{t(`exportCenter.dest.${d.id}`)}</span>- <span className="block text-[11px] leading-snug text-[var(--text-faint)]">{t(`exportCenter.destHint.${d.id}`)}</span>+ <span className="block text-[11px] leading-snug text-[var(--text-faint)]">{tApp(`exportCenter.destHint.${d.id}`)}</span></span></button>);@@ -563,7 +582,7 @@ export function ExportCenter(props: ExportCenterProps) {<div className="flex shrink-0 items-center gap-2 px-5 pb-1 pt-4"><div className="min-w-0 flex-1"><h3 className="text-[14px] font-semibold text-[var(--text)]">{t(`exportCenter.dest.${dest}`)}</h3>- <p className="mt-0.5 text-[12px] leading-relaxed text-[var(--text-muted)]">{t(`exportCenter.destDesc.${dest}`)}</p>+ <p className="mt-0.5 text-[12px] leading-relaxed text-[var(--text-muted)]">{tApp(`exportCenter.destDesc.${dest}`)}</p></div><buttontype="button"@@ -795,6 +814,17 @@ export function ExportCenter(props: ExportCenterProps) {{dest === 'nle' && (<>+ <Field label={t('exportCenter.nleFor')}>+ <Segmented+ value={nleApp}+ options={[+ { value: 'draft', label: DRAFT_APP_NAME[draftApp] },+ { value: 'premiere', label: NLE_APP_NAME.premiere },+ { value: 'resolve', label: NLE_APP_NAME.resolve },+ ]}+ onChange={(app) => patch('nle', { app })}+ />+ </Field><Field label={t('exportCenter.fps')}><FpsSelectlabel={t('exportCenter.fps')}@@ -815,9 +845,9 @@ export function ExportCenter(props: ExportCenterProps) {/></Field>{captions > 0 && (- <Toggle checked={s.nle.subtitles} onChange={(subtitles) => patch('nle', { subtitles })} label={t('exportCenter.nleSrt')} />+ <Toggle checked={s.nle.subtitles} onChange={(subtitles) => patch('nle', { subtitles })} label={t(nleApp === 'draft' ? 'exportCenter.nleSubs' : 'exportCenter.nleSrt')} />)}- <Hint>{t('exportCenter.nleHint')}</Hint>+ <Hint>{tApp(nleApp === 'premiere' ? 'exportCenter.nleHintPremiere' : nleApp === 'resolve' ? 'exportCenter.nleHintResolve' : draftHere ? 'exportCenter.nleHintDraft' : 'exportCenter.nleHintDraftNone')}</Hint></>)}@@ -1031,28 +1061,28 @@ export function ExportCenter(props: ExportCenterProps) {/>{range.on && (<div className="mt-2 flex flex-wrap items-center gap-2 text-[12px] text-[var(--text-muted)]">- <select- value={range.from}- onChange={(e) => {- const from = Number(e.target.value);- setRange((r) => ({ ...r, from, to: r.to > from ? r.to : (boundaries.ends.find((m) => m.ms > from)?.ms ?? totalMs) }));- }}- className="h-8 max-w-[220px] rounded-lg border border-[var(--border)] bg-[var(--bg)] px-2 text-[12px] text-[var(--text)]"- >- {boundaries.starts.map((m) => (- <option key={`f${m.ms}`} value={m.ms}>{[formatFilmTime(m.ms), m.title].filter(Boolean).join(' · ')}</option>- ))}- </select>+ <div className="flex w-[220px] min-w-0">+ <MenuSelect+ label={t('exportCenter.rangeFrom')}+ size="md"+ value={String(range.from)}+ groups={[{ choices: boundaries.starts.map((m) => ({ value: String(m.ms), label: [formatFilmTime(m.ms), m.title].filter(Boolean).join(' · ') })) }]}+ onPick={(v) => {+ const from = Number(v);+ setRange((r) => ({ ...r, from, to: r.to > from ? r.to : (boundaries.ends.find((m) => m.ms > from)?.ms ?? totalMs) }));+ }}+ />+ </div><span>→</span>- <select- value={range.to}- onChange={(e) => setRange((r) => ({ ...r, to: Number(e.target.value) }))}- className="h-8 max-w-[220px] rounded-lg border border-[var(--border)] bg-[var(--bg)] px-2 text-[12px] text-[var(--text)]"- >- {boundaries.ends.filter((m) => m.ms > range.from).map((m) => (- <option key={`t${m.ms}`} value={m.ms}>{[formatFilmTime(m.ms), m.title].filter(Boolean).join(' · ')}</option>- ))}- </select>+ <div className="flex w-[220px] min-w-0">+ <MenuSelect+ label={t('exportCenter.rangeTo')}+ size="md"+ value={String(range.to)}+ groups={[{ choices: boundaries.ends.filter((m) => m.ms > range.from).map((m) => ({ value: String(m.ms), label: [formatFilmTime(m.ms), m.title].filter(Boolean).join(' · ') })) }]}+ onPick={(v) => setRange((r) => ({ ...r, to: Number(v) }))}+ />+ </div><span className="tabular-nums">{formatFilmTime(rangeMs)}</span></div>)}@@ -1063,7 +1093,17 @@ export function ExportCenter(props: ExportCenterProps) {{/* 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 ? (+ {toDrafts ? (+ <div className="-ml-2 flex min-w-0 max-w-[340px] flex-1 items-center gap-2.5 px-2 py-1.5">+ <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)]">+ <Clapperboard size={15} />+ </span>+ <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)]">{tApp('exportCenter.nleDraftTitle')}</span>+ </span>+ </div>+ ) : folderDraft != null ? (<inputautoFocusvalue={folderDraft}@@ -1241,14 +1281,15 @@ function Segmented<V extends string>({ value, options, onChange }: {onChange: (v: V) => void;}) {return (- <div className="inline-flex max-w-full flex-wrap self-start rounded-lg border border-[var(--border)] bg-[var(--bg)] p-0.5">+ /* a capsule in a capsule: the same even gap all round, so their curves run side by side */+ <div className="inline-flex max-w-full self-start overflow-x-auto rounded-full border border-[var(--border)] bg-[var(--bg)] p-[3px]">{options.map((o) => (<buttonkey={o.value}type="button"aria-pressed={o.value === value}onClick={() => onChange(o.value)}- className={`rounded-md px-2.5 py-1 text-[12px] font-medium transition ${+ className={`shrink-0 whitespace-nowrap rounded-full px-3 py-1 text-[12px] font-medium transition ${o.value === value ? 'bg-[var(--surface-3,var(--bg-hover))] text-[var(--text)] shadow-[var(--shadow-sm)]' : 'text-[var(--text-muted)] hover:text-[var(--text)]'}`}>@@ -1360,9 +1401,8 @@ function FrameField({ value, fill, current, stage, onChange, onFill, t }: {</button>);})}+ <CustomFrame chip value={resolved} onPick={(f) => onChange(f === current ? 'current' : f)} /></div>- <CustomFrame value={resolved} onPick={(f) => onChange(f === current ? 'current' : f)}- className="-mx-2 max-w-[260px] rounded-lg" />{differs && (<Segmentedvalue={fill}diff --git a/packages/openfilm/studio/ui/src/components/inspector-fields.tsx b/packages/openfilm/studio/ui/src/components/inspector-fields.tsxindex c7005cf..81a1b6d 100644--- a/packages/openfilm/studio/ui/src/components/inspector-fields.tsx+++ b/packages/openfilm/studio/ui/src/components/inspector-fields.tsx@@ -20,6 +20,7 @@ import { metricCss, parseMetric, showMetric, stepMetric, type Metric, type Metriimport { Tooltip } from './Tooltip';import { Popover } from './Popover';import { ColorPicker } from './ColorPicker';+import { MenuSelect } from './MenuSelect';/* ───────────────────────────── skin ───────────────────────────── */@@ -651,31 +652,19 @@ export function SelectField({}) {const t = useT();const current = value === MIXED ? '' : value;+ /* several things with different values, or a value the list does not have: shown first, as it is */+ const extra = options.some((opt) => opt.value === current) ? [] : [{ value: current, label: value === MIXED ? t('inspector.mixed') : current === '' ? '—' : current }];return (<Tooltip label={label}>- <div className={FIELD}>- {prefix ? <span className="shrink-0 whitespace-nowrap pl-2 pr-1 text-[10.5px] text-[var(--text-faint)]">{prefix}</span> : null}- <select- aria-label={label}+ <div className="flex min-w-0 flex-1">+ {/* Studio's own menu, not the browser's list: that one is drawn by the system, light in a dark Studio */}+ <MenuSelect+ label={label}+ prefix={prefix}value={current}- onChange={(e) => {- if (e.target.value === '' || e.target.value === current) return;- onCommit(e.target.value);- /* hand focus back once picked: a focused select takes Space, ⌘Z and Delete as typing */- e.currentTarget.blur();- }}- className={`${INPUT} cursor-pointer appearance-none bg-[length:9px] bg-[right_8px_center] bg-no-repeat ${prefix ? 'pl-0' : 'pl-2'} pr-6`}- style={{- backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 10 6\'%3E%3Cpath d=\'M1 1l4 4 4-4\' fill=\'none\' stroke=\'%23999\' stroke-width=\'1.4\' stroke-linecap=\'round\' stroke-linejoin=\'round\'/%3E%3C/svg%3E")',- }}- >- {!options.some((opt) => opt.value === current) ? (- <option value={current}>{value === MIXED ? t('inspector.mixed') : current === '' ? '—' : current}</option>- ) : null}- {options.map((opt) => (- <option key={opt.value} value={opt.value}>{opt.label}</option>- ))}- </select>+ groups={[{ choices: [...extra, ...options] }]}+ onPick={(next) => { if (next !== '' && next !== current) onCommit(next); }}+ /></div></Tooltip>);diff --git a/packages/openfilm/studio/ui/src/components/inspector-look.tsx b/packages/openfilm/studio/ui/src/components/inspector-look.tsxindex f7fc2a3..9e7f5b7 100644--- a/packages/openfilm/studio/ui/src/components/inspector-look.tsx+++ b/packages/openfilm/studio/ui/src/components/inspector-look.tsx@@ -9,15 +9,16 @@*/import * as React from 'react';import {- AlignCenter, AlignJustify, AlignLeft, AlignRight, Ban, ChevronDown, Circle, Crop as CropIcon, Heart, Minus, Plus, RotateCcw, Square,- SquareDashed, Star,+ AlignCenter, AlignJustify, AlignLeft, AlignRight, Ban, ChevronDown, Circle, Crop as CropIcon, Heart, Minus, Plus, RotateCcw, Scan, Square,+ SquareDashed, Star, Strikethrough, Underline,} from 'lucide-react';import type { useT } from '@/i18n';import {- ADJUST_KEYS, BLEND_MODES, FADE_DEFAULT, SHADOW_DEFAULT, STROKE_DEFAULT, adjustOf, cropCss, cropForRatio, cropOf,- cropRatio, filterParts, framingCss, framingOf, ownedDeclaration, pxOf, shadowOf, strokeCss,- strokeOf, withAdjust, withShadow, type AdjustKey, type Crop, type Fade, type FadeSide, type Shadow, type Stroke,+ ADJUST_KEYS, BLEND_MODES, FADE_DEFAULT, INNER_SHADOW_DEFAULT, PLACED_STROKE_DEFAULT, SHADOW_DEFAULT, adjustOf, backdropBlurCss,+ backdropBlurOf, cropCss, cropForRatio, cropOf, cropRatio, filterParts, framingCss, framingOf, innerShadowCss, innerShadowOf,+ ownedDeclaration, placedStrokeCss, placedStrokeOf, pxOf, radiusCorners, shadowOf, strokeOf, withAdjust, withShadow, type AdjustKey, type Crop, type Fade,+ type FadeSide, type InnerShadow, type PlacedStroke, type Shadow, type StrokePosition, type StrokeStyle,} from '@/lib/clip-look';import {MASK_FIELDS, MASK_SHAPES, fadeIn, maskDefault, maskOf, maskOwned, withFade, withMask, type Mask, type MaskBox, type MaskShape,@@ -122,6 +123,8 @@ const previewSettled = () => { previewedBefore = null; };export const NEUTRAL: Record<string, string> = {opacity: '1', filter: 'none', 'clip-path': 'none', 'border-radius': '0', 'mix-blend-mode': 'normal', 'object-fit': 'contain','object-position': '50% 50%', 'mask-image': 'none', border: 'none', 'text-transform': 'none',+ outline: 'none', 'outline-offset': '0px', 'box-shadow': 'none', 'backdrop-filter': 'none', 'text-decoration-line': 'none',+ 'border-top-left-radius': '0', 'border-top-right-radius': '0', 'border-bottom-right-radius': '0', 'border-bottom-left-radius': '0',};/** Whether `v` looks as nothing set (`1`, `none`, `0px`, …). */@@ -130,17 +133,15 @@ export function isNeutral(prop: string, v: string | undefined): boolean {const s = v.trim().toLowerCase();if (s === NEUTRAL[prop]) return true;if (prop === 'opacity') return Number(s) === 1;- if (prop === 'border-radius') return pxOf(s) === 0;+ if (prop.endsWith('-radius') || prop === 'outline-offset') return pxOf(s) === 0;if (prop === 'object-position') { const f = framingOf(s); return f != null && f[0] === 50 && f[1] === 50; }- if (prop === 'border') return strokeOf(s) === undefined;+ if (prop === 'border' || prop === 'outline') return strokeOf(s) === undefined;return s === 'none' || s === 'normal';}export const camelOf = (prop: string) => prop.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());export const kebabOf = (key: string) => key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);-/** Each value of an apply over a value that may be missing. */-const at = (apply: FieldApply, v: number | null | undefined, fallback = 0) => apply(v ?? fallback);const round = (n: number, d = 1) => Math.round(n * 10 ** d) / 10 ** d;/* ───────────────────────────── crop & fill ───────────────────────────── */@@ -173,11 +174,10 @@ export function CropSection({const v = read('object-fit') ?? 'contain';return v === 'cover' || v === 'fill' ? v : 'contain';});- const radius = look.common((read) => pxOf(read('border-radius')) ?? 0);const frame = look.common((read) => framingOf(read('object-position')));const cropUnreadable = look.common((read) => cropOf(read('clip-path')) == null);const touched = look.common((read) => !isNeutral('clip-path', read('clip-path')) || !isNeutral('object-position', read('object-position'))- || !isNeutral('border-radius', read('border-radius')) || (read('object-fit') ?? 'contain') !== 'contain');+ || (read('object-fit') ?? 'contain') !== 'contain');const cropEdit = (side: number, apply: FieldApply): LookEdit => (read): LookSet => {const now = cropOf(read('clip-path'));@@ -187,12 +187,6 @@ export function CropSection({next[side] = Math.max(0, Math.min(99 - now[(side + 2) % 4]!, round(apply(now[side]!), 2)));return { 'clip-path': cropCss(next, pxOf(read('border-radius')) ?? 0) };};- const radiusEdit = (apply: FieldApply): LookEdit => (read) => {- const r = Math.max(0, round(at(apply, pxOf(read('border-radius')))));- const now = cropOf(read('clip-path'));- /* a crop cuts the box's own corners away: it carries the same roundness */- return { 'border-radius': r > 0 ? `${r}px` : null, ...(now && now.some((v) => v > 0) ? { 'clip-path': cropCss(now, r) } : {}) };- };const ratioOf = (id: string) => (id === 'original' ? (own && own.h > 0 ? own.w / own.h : undefined) : RATIOS.find((r) => r.id === id)?.ratio);const shape = (() => {if (!box || crop === MIXED || !crop) return 'free';@@ -252,7 +246,9 @@ export function CropSection({{ value: 'cover', label: t('inspector.fitCover') },{ value: 'fill', label: t('inspector.fitFill') },]}- onChange={(v) => look.commit(() => ({ 'object-fit': v === 'contain' ? null : v }))}+ /* said outright: "none of mine" on a picture in a page brings back the page's own, which for an <img> is+ stretched (CSS's fill) */+ onChange={(v) => look.commit(() => ({ 'object-fit': v }))}/>) : null}{cropUnreadable === false ? (@@ -290,20 +286,6 @@ export function CropSection({) : (<p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t('inspector.cropCustom')}</p>)}- <Row>- <NumField- label={t('inspector.radius')}- prefix={<RadiusGlyph />}- value={radius}- unit="px"- min={0}- max={100_000}- onPreview={(_, apply) => look.preview(radiusEdit(apply))}- onCommit={(_, apply) => look.commit(radiusEdit(apply))}- onRevert={() => look.revert()}- />- <span />- </Row>{framing && frame !== null ? (<><SubLabel>{t('inspector.framing')}</SubLabel>@@ -340,7 +322,7 @@ export function CropSection({/* ───────────────────────────── mask ───────────────────────────── *//** The shape buttons' glyphs: a line, a band, then lucide's. */-function MaskGlyph({ shape }: { shape: MaskShape | 'none' }) {+export function MaskGlyph({ shape }: { shape: MaskShape | 'none' }) {if (shape === 'linear' || shape === 'mirror') {return (<svg width={ICON} height={ICON} viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.3" aria-hidden>@@ -365,7 +347,7 @@ function MaskGlyph({ shape }: { shape: MaskShape | 'none' }) {* the stage previews a drag and writes once, at the release; it is turned on with a new shape.*/export function MaskSection({- look, t, box, target, onEditMask,+ look, t, box, target, onEditMask, ask, onAsked,}: {look: Look;t: T;@@ -374,6 +356,9 @@ export function MaskSection({/** Whose mask, for the stage's handles. */target?: MaskSession['target'] | null;onEditMask?: (session: MaskSession | null) => void;+ /** A shape picked on the picture (the selection bar's Mask): put on, with its handles, once. */+ ask?: { shape: MaskShape | 'none'; n: number } | null;+ onAsked?: () => void;}) {const mbox = box && box.w > 0 && box.h > 0 ? box : null;const mask = look.common((read) => maskOf(read('mask-image'), read('mask-composite'), mbox));@@ -395,6 +380,12 @@ export function MaskSection({if (canEdit) setEditing(true);};+ React.useEffect(() => {+ if (!ask) return;+ pick(ask.shape);+ onAsked?.();+ }, [ask?.n]); // eslint-disable-line react-hooks/exhaustive-deps+/* the stage's handles: the mask as written, written back through this look (one change at the release) */const lookRef = React.useRef(look);lookRef.current = look;@@ -522,7 +513,83 @@ export function MaskSection({/* ───────────────────────────── appearance ───────────────────────────── *//** Opacity (`opacity`) and blending (`mix-blend-mode`), with names people use; `children` adds fills. */-export function AppearanceSection({ look, t, children }: { look: Look; t: T; children?: React.ReactNode }) {+/** A box's four corners (CSS order: top left, top right, bottom right, bottom left). */+const CORNERS = ['top-left', 'top-right', 'bottom-right', 'bottom-left'] as const;+type Corner = (typeof CORNERS)[number];++/**+ * Corner radius, as Figma's: one number for all four, or (the button beside it) each corner its own. A crop cuts the+ * box's own corners away, so it carries the same roundness (one for all: a crop's shape rounds its corners alike).+ */+function RadiusField({ look, t }: { look: Look; t: T }) {+ /* the shorthand, as written or as the page draws it */+ const cornerOf = (read: LookRead, c: Corner) => radiusCorners(read('border-radius'))[CORNERS.indexOf(c)]!;+ const corners = look.common((read) => CORNERS.map((c) => cornerOf(read, c)).join(' '));+ const uneven = corners !== MIXED && new Set(corners.split(' ')).size > 1;+ const [each, setEach] = React.useState(uneven);+ React.useEffect(() => { if (uneven) setEach(true); }, [uneven]);+ const cropped = (read: LookRead) => { const now = cropOf(read('clip-path')); return now && now.some((v) => v > 0) ? now : null; };+ const all = look.common((read) => (CORNERS.every((c) => cornerOf(read, c) === cornerOf(read, 'top-left')) ? cornerOf(read, 'top-left') : MIXED));+ const allEdit = (apply: FieldApply): LookEdit => (read) => {+ const r = Math.max(0, round(apply(cornerOf(read, 'top-left'))));+ const crop = cropped(read);+ return { 'border-radius': r > 0 ? `${r}px` : null, ...(crop ? { 'clip-path': cropCss(crop, r) } : {}) };+ };+ const cornerEdit = (corner: Corner, apply: FieldApply): LookEdit => (read) => {+ const now = CORNERS.map((c) => cornerOf(read, c));+ now[CORNERS.indexOf(corner)] = Math.max(0, round(apply(now[CORNERS.indexOf(corner)]!)));+ return { 'border-radius': now.every((v) => v === 0) ? null : now.map((v) => `${v}px`).join(' ') };+ };+ const bind = (edit: (apply: FieldApply) => LookEdit) => ({+ onPreview: (_: number, apply: FieldApply) => look.preview(edit(apply)),+ onCommit: (_: number, apply: FieldApply) => look.commit(edit(apply)),+ onRevert: () => look.revert(),+ });+ const croppedNow = look.common((read) => cropped(read) != null) === true;+ return (+ <>+ <div className="grid grid-cols-[1fr_24px] items-center gap-1.5">+ <NumField label={t('inspector.radius')} prefix={<RadiusGlyph />} value={each ? MIXED : all} unit="px" min={0} max={100_000}+ placeholder={each ? t('inspector.cornersEach') : undefined} {...bind(allEdit)} />+ <button+ type="button"+ aria-pressed={each}+ aria-label={t('inspector.cornersEach')}+ title={croppedNow ? t('inspector.cornersCropped') : t('inspector.cornersEach')}+ disabled={croppedNow}+ onClick={() => setEach((v) => !v)}+ className={`flex h-[26px] w-6 items-center justify-center rounded-[5px] transition disabled:opacity-40 ${each ? 'bg-[var(--bg-active)] text-[var(--text)]' : 'text-[var(--text-faint)] hover:bg-[var(--bg-hover)] hover:text-[var(--text)]'}`}+ >+ <Scan size={12} />+ </button>+ </div>+ {each && !croppedNow ? (+ <Row>+ {CORNERS.map((c) => (+ <NumField key={c} label={t(`inspector.corners.${c}`)} prefix={<CornerGlyph corner={c} />}+ value={look.common((read) => cornerOf(read, c))} min={0} max={100_000} {...bind((apply) => cornerEdit(c, apply))} />+ ))}+ </Row>+ ) : null}+ </>+ );+}++/** A corner's mark: the quarter of a rounded square at that corner. */+function CornerGlyph({ corner }: { corner: Corner }) {+ const turn = { 'top-left': 0, 'top-right': 90, 'bottom-right': 180, 'bottom-left': 270 }[corner];+ return (+ <svg width="9" height="9" viewBox="0 0 9 9" aria-hidden style={{ transform: `rotate(${turn}deg)` }}>+ <path d="M1.5 8V5a3.5 3.5 0 0 1 3.5-3.5H8" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />+ </svg>+ );+}++/**+ * Opacity, corner radius (`radius`: for what has corners — a box, a picture, a line with its own fill) and blend,+ * as Figma's Appearance.+ */+export function AppearanceSection({ look, t, children, radius = false }: { look: Look; t: T; children?: React.ReactNode; radius?: boolean }) {const opacity = look.common((read) => {const v = Number(read('opacity') ?? 1);return Number.isFinite(v) ? round(v * 100) : 100;@@ -546,6 +613,7 @@ export function AppearanceSection({ look, t, children }: { look: Look; t: T; chionCommit={(_, apply) => look.commit(opacityEdit(apply))}onRevert={() => look.revert()}/>+ {radius ? <RadiusField look={look} t={t} /> : null}<SelectFieldlabel={t('inspector.blend')}prefix={t('inspector.blendShort')}@@ -558,6 +626,136 @@ export function AppearanceSection({ look, t, children }: { look: Look; t: T; chi);}+/* ───────────────────────────── fill ───────────────────────────── */++/**+ * Fill, as Figma's: what paints the thing — a line's color, a box's background, a shape's fill. One the thing may go+ * without (a box's background) has "−" to take it off, and "+" brings one back.+ */+export function FillSection({ look, t, fills, add }: {+ look: Look;+ t: T;+ /** The fills shown: their CSS property, label, and whether it can be taken off. */+ fills: { prop: string; label: string; removable?: boolean }[];+ /** A fill to offer with "+" when it is not there (a box with no background). */+ add?: { prop: string; label: string; value: string } | null;+}) {+ if (!fills.length && !add) return null;+ return (+ <Section+ id="fill"+ title={t('inspector.fill')}+ aside={add ? (+ <SectionAction label={t('inspector.fillAdd')} onClick={() => look.commit(() => ({ [add.prop]: add.value }))}><Plus size={12} /></SectionAction>+ ) : null}+ >+ {fills.map((f) => (+ <div key={f.prop} className="flex items-center gap-1.5">+ <div className="min-w-0 flex-1">+ <ColorField+ label={f.label}+ value={look.common((read) => read(f.prop) ?? '')}+ onPreview={(c) => look.preview(() => ({ [f.prop]: c }))}+ onCommit={(c) => look.commit(() => ({ [f.prop]: c }))}+ />+ </div>+ {f.removable ? (+ /* see-through, not "none of mine": that would bring back the page's own fill */+ <SectionAction label={t('inspector.fillRemove')} onClick={() => look.commit(() => ({ [f.prop]: 'transparent' }))}><Minus size={12} /></SectionAction>+ ) : null}+ </div>+ ))}+ </Section>+ );+}++/* ───────────────────────────── stroke ───────────────────────────── */++/**+ * Stroke, as Figma's: color, weight, where it lies against the edge (inside, across, outside) and its line (solid,+ * dashed, dotted). Drawn as an `outline` with its offset (lib/clip-look placedStrokeOf): it adds nothing to the box,+ * so the layout does not move as it is added or thickened.+ */+export function StrokeSection({ look, t }: { look: Look; t: T }) {+ const stroke = look.common((read) => placedStrokeOf(read));+ const has = stroke !== undefined;+ const edit = (part: Partial<PlacedStroke> | ((now: PlacedStroke) => Partial<PlacedStroke>)): LookEdit => (read) => {+ const was = placedStrokeOf(read);+ const now: PlacedStroke = was ?? PLACED_STROKE_DEFAULT;+ return placedStrokeCss({ ...now, ...(typeof part === 'function' ? part(now) : part) }, was);+ };+ const width = (apply: FieldApply): LookEdit => edit((now) => ({ width: Math.max(0, round(apply(now.width))) }));+ /* a mask (faded edges, a mask shape) or a crop shows the box and nothing past it: a stroke outside, or half of one+ across the edge, is cut away with it */+ const cut = look.common((read) => {+ const m = read('mask-image');+ const c = read('clip-path');+ return Boolean((m && m !== 'none') || (c && c !== 'none'));+ });+ const position = look.common((read) => placedStrokeOf(read)?.position);+ return (+ <Section+ id="stroke"+ title={t('inspector.stroke')}+ aside={has ? (+ <SectionAction label={t('inspector.effectRemove')} onClick={() => look.commit((read) => placedStrokeCss(null, placedStrokeOf(read)))}><Minus size={12} /></SectionAction>+ ) : (+ <SectionAction label={t('inspector.strokeAdd')} onClick={() => look.commit(edit({}))}><Plus size={12} /></SectionAction>+ )}+ >+ {stroke === null ? (+ <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t('inspector.effectCustom')}</p>+ ) : has ? (+ <>+ <ColorField+ label={t('inspector.strokeColor')}+ value={look.common((read) => placedStrokeOf(read)?.color ?? '')}+ onPreview={(c) => look.preview(edit({ color: c }))}+ onCommit={(c) => look.commit(edit({ color: c }))}+ />+ <Row>+ <SelectField+ label={t('inspector.strokePosition')}+ value={look.common((read) => placedStrokeOf(read)?.position ?? 'inside')}+ /* a mask or a crop cuts away all that is past the edge: only inside is drawn whole there (a stroke placed+ otherwise before shows where it is, to be moved inside) */+ options={(['inside', 'center', 'outside'] as const)+ .filter((p) => cut === false || p === 'inside' || p === position)+ .map((p) => ({ value: p, label: t(`inspector.strokePositions.${p}`) }))}+ onCommit={(v) => look.commit(edit({ position: v as StrokePosition }))}+ />+ <NumField+ label={t('inspector.strokeWidth')}+ prefix={<span className="block h-[7px] w-[9px] rounded-[1.5px] border-[1.5px]" style={{ borderColor: 'currentColor' }} />}+ value={look.common((read) => placedStrokeOf(read)?.width)}+ unit="px"+ min={0}+ max={1000}+ onPreview={(_, apply) => look.preview(width(apply))}+ onCommit={(_, apply) => look.commit(width(apply))}+ onRevert={() => look.revert()}+ />+ </Row>+ <Segmented+ label={t('inspector.strokeStyle')}+ value={look.common((read) => placedStrokeOf(read)?.style ?? '')}+ small+ options={(['solid', 'dashed', 'dotted'] as const).map((s) => ({+ value: s,+ title: t(`inspector.strokeStyles.${s}`),+ label: <span className="block w-4 border-t-[1.5px]" style={{ borderTopStyle: s, borderTopColor: 'currentColor' }} />,+ }))}+ onChange={(s) => look.commit(edit({ style: s as StrokeStyle }))}+ />+ {cut !== false && position !== 'inside' ? (+ <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t('inspector.strokeCut')}</p>+ ) : null}+ </>+ ) : null}+ </Section>+ );+}+/* ───────────────────────────── adjust ───────────────────────────── */const ADJUST_RANGE: Record<AdjustKey, { min: number; max: number; unit: string; fieldMax?: number }> = {@@ -574,9 +772,12 @@ const ADJUST_RANGE: Record<AdjustKey, { min: number; max: number; unit: string;* grayscale): 0 is as is, a double-click puts one back, the reset all. Filter functions without a control here* (sepia, a url) are kept as written, in their place.*/+/* the picture's color; its blur is an effect (Figma's layer blur) */+const COLOR_KEYS = ADJUST_KEYS.filter((k) => k !== 'blur');+export function AdjustSection({ look, t }: { look: Look; t: T }) {const readable = look.common((read) => filterParts(read('filter')) != null);- const touched = look.common((read) => ADJUST_KEYS.some((k) => adjustOf(read('filter'))[k] !== 0));+ const touched = look.common((read) => COLOR_KEYS.some((k) => adjustOf(read('filter'))[k] !== 0));const edit = (key: AdjustKey, apply: FieldApply): LookEdit => (read) => {const now = adjustOf(read('filter'))[key];const r = ADJUST_RANGE[key];@@ -597,13 +798,13 @@ export function AdjustSection({ look, t }: { look: Look; t: T }) {aside={touched === false ? null : (<SectionActionlabel={t('inspector.resetSection')}- onClick={() => look.commit((read) => ({ filter: ADJUST_KEYS.reduce<string | null>((f, k) => withAdjust(f ?? undefined, k, 0), read('filter') ?? null) }))}+ onClick={() => look.commit((read) => ({ filter: COLOR_KEYS.reduce<string | null>((f, k) => withAdjust(f ?? undefined, k, 0), read('filter') ?? null) }))}><RotateCcw size={11} /></SectionAction>)}>- {ADJUST_KEYS.map((key) => {+ {COLOR_KEYS.map((key) => {const r = ADJUST_RANGE[key];const v = look.common((read) => adjustOf(read('filter'))[key]);return (@@ -630,20 +831,23 @@ export function AdjustSection({ look, t }: { look: Look; t: T }) {/* ───────────────────────────── effects ───────────────────────────── */-type EffectId = 'shadow' | 'stroke' | 'fade';+type EffectId = 'shadow' | 'inner' | 'blur' | 'backdrop' | 'fade';/**- * Effects a picture may have, each added with "+" and taken off with "−", none taking room unless used:- * a drop shadow, a stroke, faded edges.+ * Effects, as Figma's, each added with "+" and taken off with "−", none taking room unless used: a drop shadow, an+ * inner shadow (`inner`: for what has a box of its own to cast it in), a layer blur, a background blur — and faded+ * edges, a video editor's.*- * The shadow is `filter: drop-shadow()`, not `box-shadow`: it follows what is drawn — the letters of a title on a- * see-through page, a cut-out PNG, a layer of text — where a box shadow would draw the rectangle behind them, and it- * is the same for a clip and a layer. (A `box-shadow` already written stays as it is, in the raw CSS.)- * The stroke is `border`; faded edges are `mask-image` gradients, one an axis, intersected by `mask-composite`.+ * The drop shadow is `filter: drop-shadow()`, not `box-shadow`: it follows what is drawn — the letters of a title on a+ * see-through page, a cut-out PNG — where a box shadow would draw the rectangle behind them. The inner shadow is an+ * `inset` box-shadow; the layer blur `filter: blur()`; the background blur `backdrop-filter: blur()`; faded edges are+ * `mask-image` gradients, one an axis, intersected by `mask-composite`.*/-export function EffectsSection({ look, t }: { look: Look; t: T }) {+export function EffectsSection({ look, t, inner = false }: { look: Look; t: T; inner?: boolean }) {const shadow = look.common((read) => shadowOf(read('filter')));- const stroke = look.common((read) => strokeOf(read('border')));+ const innerShadow = look.common((read) => innerShadowOf(read('box-shadow')));+ const blur = look.common((read) => { const b = adjustOf(read('filter')).blur; return b ? b : undefined; });+ const backdrop = look.common((read) => backdropBlurOf(read('backdrop-filter')));/* faded edges share mask-image with the Mask section's shape (clip-mask): read and written beside it */const fadeRead = (read: LookRead) => fadeIn(read('mask-image'), read('mask-composite'));const fadeWrite = (read: LookRead, next: Fade | null): LookSet => withFade(read('mask-image'), read('mask-composite'), next) ?? {};@@ -653,25 +857,36 @@ export function EffectsSection({ look, t }: { look: Look; t: T }) {const has = (v: unknown) => v !== undefined;const missing: { id: EffectId; label: string }[] = [...(!has(shadow) && filterReadable ? [{ id: 'shadow' as const, label: t('inspector.shadow') }] : []),- ...(!has(stroke) ? [{ id: 'stroke' as const, label: t('inspector.stroke') }] : []),+ ...(inner && !has(innerShadow) ? [{ id: 'inner' as const, label: t('inspector.innerShadow') }] : []),+ ...(!has(blur) && filterReadable ? [{ id: 'blur' as const, label: t('inspector.layerBlur') }] : []),+ ...(!has(backdrop) ? [{ id: 'backdrop' as const, label: t('inspector.backgroundBlur') }] : []),...(!has(fade) ? [{ id: 'fade' as const, label: t('inspector.fade') }] : []),];const add = (id: EffectId) => {setAdding(false);if (id === 'shadow') look.commit((read) => ({ filter: withShadow(read('filter'), shadowOf(read('filter')) ?? SHADOW_DEFAULT) }));- if (id === 'stroke') look.commit((read) => ({ border: strokeCss(strokeOf(read('border')) ?? STROKE_DEFAULT) }));+ if (id === 'inner') look.commit(() => ({ 'box-shadow': innerShadowCss(INNER_SHADOW_DEFAULT) }));+ if (id === 'blur') look.commit((read) => ({ filter: withAdjust(read('filter'), 'blur', 4) }));+ if (id === 'backdrop') look.commit(() => ({ 'backdrop-filter': backdropBlurCss(8) }));if (id === 'fade') look.commit((read) => fadeWrite(read, fadeRead(read) ?? FADE_DEFAULT));};const remove = (id: EffectId) => {if (id === 'shadow') look.commit((read) => ({ filter: withShadow(read('filter'), null) }));- if (id === 'stroke') look.commit(() => ({ border: null }));+ if (id === 'inner') look.commit(() => ({ 'box-shadow': null }));+ if (id === 'blur') look.commit((read) => ({ filter: withAdjust(read('filter'), 'blur', 0) }));+ if (id === 'backdrop') look.commit(() => ({ 'backdrop-filter': null }));if (id === 'fade') look.commit((read) => fadeWrite(read, null));};const removeBtn = (id: EffectId) => (<SectionAction label={t('inspector.effectRemove')} onClick={() => remove(id)}><Minus size={12} /></SectionAction>);+ const bind = (edit: (apply: FieldApply) => LookEdit) => ({+ onPreview: (_: number, apply: FieldApply) => look.preview(edit(apply)),+ onCommit: (_: number, apply: FieldApply) => look.commit(edit(apply)),+ onRevert: () => look.revert(),+ });- /* shadow: each thing's own, or the default for one without */+ /* drop shadow: each thing's own, or the default for one without */const shadowField = (key: 'x' | 'y' | 'blur') => {const edit = (apply: FieldApply): LookEdit => (read) => {const now: Shadow = shadowOf(read('filter')) ?? SHADOW_DEFAULT;@@ -685,18 +900,26 @@ export function EffectsSection({ look, t }: { look: Look; t: T }) {value={look.common((read) => shadowOf(read('filter'))?.[key])}unit="px"{...(key === 'blur' ? { min: 0 } : {})}- onPreview={(_, apply) => look.preview(edit(apply))}- onCommit={(_, apply) => look.commit(edit(apply))}- onRevert={() => look.revert()}+ {...bind(edit)}/>);};const shadowColor = (color: string): LookEdit => (read) => ({ filter: withShadow(read('filter'), { ...(shadowOf(read('filter')) ?? SHADOW_DEFAULT), color }) });- const strokeEdit = (part: Partial<Stroke>): LookEdit => (read) => ({ border: strokeCss({ ...(strokeOf(read('border')) ?? STROKE_DEFAULT), ...part }) });- const strokeWidth = (apply: FieldApply): LookEdit => (read) => {- const now = strokeOf(read('border')) ?? STROKE_DEFAULT;- return { border: strokeCss({ ...now, width: Math.max(0, round(apply(now.width))) }) };+ /* inner shadow: x, y, blur, spread and color */+ const innerEdit = (part: (now: InnerShadow) => Partial<InnerShadow>): LookEdit => (read) => {+ const now = innerShadowOf(read('box-shadow')) ?? INNER_SHADOW_DEFAULT;+ return { 'box-shadow': innerShadowCss({ ...now, ...part(now) }) };};+ const innerField = (key: 'x' | 'y' | 'blur' | 'spread', prefix: string, label: string) => (+ <NumField+ label={label}+ prefix={prefix}+ value={look.common((read) => innerShadowOf(read('box-shadow'))?.[key])}+ unit="px"+ {...(key === 'blur' ? { min: 0 } : {})}+ {...bind((apply) => innerEdit((now) => ({ [key]: key === 'blur' ? Math.max(0, round(apply(now[key]))) : round(apply(now[key])) })))}+ />+ );const fadeOn = (side: FadeSide) => look.common((read) => fadeRead(read)?.sides[side] ?? false);const fadeSize = look.common((read) => fadeRead(read)?.size ?? null);const fadeToggle = (side: FadeSide) => {@@ -714,6 +937,7 @@ export function EffectsSection({ look, t }: { look: Look; t: T }) {const custom = (label: string) => (<SubLabel>{label} · <span className="text-[var(--text-faint)]">{t('inspector.effectCustom')}</span></SubLabel>);+ const none = !has(shadow) && !has(innerShadow) && !has(blur) && !has(backdrop) && !has(fade);return (<Section@@ -745,9 +969,7 @@ export function EffectsSection({ look, t }: { look: Look; t: T }) {</Popover>) : null}>- {!has(shadow) && !has(stroke) && !has(fade) ? (- <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t('inspector.effectsNone')}</p>- ) : null}+ {none ? <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t('inspector.effectsNone')}</p> : null}{shadow === null ? custom(t('inspector.shadow')) : has(shadow) ? (<><SubLabel aside={removeBtn('shadow')}>{t('inspector.shadow')}</SubLabel>@@ -760,38 +982,52 @@ export function EffectsSection({ look, t }: { look: Look; t: T }) {/></>) : null}- {stroke === null ? custom(t('inspector.stroke')) : has(stroke) ? (+ {innerShadow === null ? custom(t('inspector.innerShadow')) : has(innerShadow) ? (<>- <SubLabel aside={removeBtn('stroke')}>{t('inspector.stroke')}</SubLabel>- <Row>- <NumField- label={t('inspector.strokeWidth')}- prefix={<span className="block h-[7px] w-[9px] rounded-[1.5px] border-[1.5px]" style={{ borderColor: 'currentColor' }} />}- value={look.common((read) => strokeOf(read('border'))?.width)}- unit="px"- min={0}- max={1000}- onPreview={(_, apply) => look.preview(strokeWidth(apply))}- onCommit={(_, apply) => look.commit(strokeWidth(apply))}- onRevert={() => look.revert()}- />- <Segmented- label={t('inspector.strokeStyle')}- value={look.common((read) => strokeOf(read('border'))?.style ?? '')}- small- options={(['solid', 'dashed', 'dotted'] as const).map((s) => ({- value: s,- title: t(`inspector.strokeStyles.${s}`),- label: <span className="block w-4 border-t-[1.5px]" style={{ borderTopStyle: s, borderTopColor: 'currentColor' }} />,- }))}- onChange={(s) => look.commit(strokeEdit({ style: s as Stroke['style'] }))}- />- </Row>+ <SubLabel aside={removeBtn('inner')}>{t('inspector.innerShadow')}</SubLabel>+ <Row>{innerField('x', 'X', t('inspector.shadowX'))}{innerField('y', 'Y', t('inspector.shadowY'))}</Row>+ <Row>{innerField('blur', 'B', t('inspector.shadowBlur'))}{innerField('spread', 'S', t('inspector.shadowSpread'))}</Row><ColorField- label={t('inspector.strokeColor')}- value={look.common((read) => strokeOf(read('border'))?.color ?? '')}- onPreview={(c) => look.preview(strokeEdit({ color: c }))}- onCommit={(c) => look.commit(strokeEdit({ color: c }))}+ label={t('inspector.shadowColor')}+ value={look.common((read) => innerShadowOf(read('box-shadow'))?.color ?? '')}+ onPreview={(c) => look.preview(innerEdit(() => ({ color: c })))}+ onCommit={(c) => look.commit(innerEdit(() => ({ color: c })))}+ />+ </>+ ) : null}+ {blur === null ? custom(t('inspector.layerBlur')) : has(blur) ? (+ <>+ <SubLabel aside={removeBtn('blur')}>{t('inspector.layerBlur')}</SubLabel>+ <SliderField+ label={t('inspector.layerBlur')}+ value={blur === MIXED ? MIXED : blur ?? 0}+ min={0}+ max={40}+ neutral={0}+ unit="px"+ fieldMin={0}+ fieldMax={1000}+ onPreview={(_, apply) => look.preview((read) => ({ filter: withAdjust(read('filter'), 'blur', Math.max(0, round(apply(adjustOf(read('filter')).blur ?? 0)))) }))}+ onCommit={(_, apply) => look.commit((read) => ({ filter: withAdjust(read('filter'), 'blur', Math.max(0, round(apply(adjustOf(read('filter')).blur ?? 0)))) }))}+ onRevert={() => look.revert()}+ />+ </>+ ) : null}+ {backdrop === null ? custom(t('inspector.backgroundBlur')) : has(backdrop) ? (+ <>+ <SubLabel aside={removeBtn('backdrop')}>{t('inspector.backgroundBlur')}</SubLabel>+ <SliderField+ label={t('inspector.backgroundBlur')}+ value={backdrop === MIXED ? MIXED : backdrop ?? 0}+ min={0}+ max={40}+ neutral={0}+ unit="px"+ fieldMin={0}+ fieldMax={1000}+ onPreview={(_, apply) => look.preview((read) => ({ 'backdrop-filter': backdropBlurCss(Math.max(0, round(apply(backdropBlurOf(read('backdrop-filter')) ?? 0)))) }))}+ onCommit={(_, apply) => look.commit((read) => ({ 'backdrop-filter': backdropBlurCss(Math.max(0, round(apply(backdropBlurOf(read('backdrop-filter')) ?? 0)))) }))}+ onRevert={() => look.revert()}/></>) : null}@@ -868,8 +1104,10 @@ export function TypographySection({ look, t, svg, sample }: { look: Look; t: T;const spacing = look.common((read) => metricOf('letter-spacing', read('letter-spacing')));const align = look.common((read) => read('text-align') ?? '');const textCase = look.common((read) => read('text-transform') ?? 'none');- const colorProp = svg ? 'fill' : 'color';- const color = look.common((read) => read(colorProp) ?? '');+ const decoration = look.common((read) => {+ const v = read('text-decoration-line') ?? 'none';+ return /underline/.test(v) ? 'underline' : /line-through/.test(v) ? 'line-through' : 'none';+ });const styles = family === MIXED || !family ? null : stylesOf(family, installed ?? [], project);/* not drawn as named: not installed, not declared for the page — once the lists came, and the browser agrees */const missing = React.useMemo(() => {@@ -998,12 +1236,22 @@ export function TypographySection({ look, t, svg, sample }: { look: Look; t: T;/></Row>)}- <ColorField- label={svg ? t('inspector.fill') : t('inspector.color')}- value={color}- onPreview={(c) => look.preview(() => ({ [colorProp]: c }))}- onCommit={(c) => look.commit(() => ({ [colorProp]: c }))}- />+ {svg ? null : (+ <Row>+ <Segmented+ label={t('inspector.textDecoration')}+ value={decoration}+ small+ options={[+ { value: 'none', label: '—', title: t('inspector.decorations.none') },+ { value: 'underline', label: <Underline size={ICON} />, title: t('inspector.decorations.underline') },+ { value: 'line-through', label: <Strikethrough size={ICON} />, title: t('inspector.decorations.lineThrough') },+ ]}+ onChange={(v) => look.commit(() => ({ 'text-decoration-line': v === 'none' ? null : v }))}+ />+ <span />+ </Row>+ )}</Section>);}diff --git a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsxindex 226f421..8e8c240 100644--- a/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx+++ b/packages/openfilm/studio/ui/src/components/settings/SettingsModal.tsx@@ -11,7 +11,7 @@ import { LANGUAGES, phrasesUnder, useLanguage, useLanguageChoice, useT, type Lanimport { shortcutHint } from '@/lib/shortcut-hint';import { SHORTCUTS, type ShortcutKey } from '@/lib/timeline-keys';import { studioHost } from '@/lib/host';-import { api, type StudioVersion } from '@/api';+import { api, type StudioPrefs, type StudioVersion } from '@/api';import { AgentsSection } from './AgentsSection';import { ModelsSection } from './ModelsSection';import { ProvidersSection } from './ProvidersSection';@@ -38,8 +38,8 @@ const SECTION_ICON: Record<SettingsSection, React.ReactNode> = {};/** what a search through each section reads: its name and every phrase it shows */-const SECTION_WORDS: Record<SettingsSection, string> = {- general: 'settings.appearance',+const SECTION_WORDS: Record<SettingsSection, string | string[]> = {+ general: ['settings.appearance', 'settings.playback'],agents: 'settings.agents',providers: 'settings.providers',models: 'settings.models',@@ -72,7 +72,7 @@ export function SettingsModal({ open, onClose, section: opening }: SettingsModal/* the sections a search finds: by their names and by every phrase on them */const words = React.useMemo(() => Object.fromEntries((Object.keys(SECTION_WORDS) as SettingsSection[]).map((id) => [- id, [t(`settings.sections.${id}`), ...phrasesUnder(SECTION_WORDS[id], language)].join('\n').toLowerCase(),+ id, [t(`settings.sections.${id}`), ...[SECTION_WORDS[id]].flat().flatMap((under) => phrasesUnder(under, language))].join('\n').toLowerCase(),])) as Record<SettingsSection, string>, [t, language]);const needle = query.trim().toLowerCase();const nav = NAV.map((group) => ({ ...group, sections: group.sections.filter((id) => !needle || words[id].includes(needle)) }))@@ -222,11 +222,50 @@ function GeneralSection() {)}/></SettingsGroup>+ <PlaybackGroup /><AboutGroup /></SettingsPage>);}+/**+ * How the preview plays heavy footage (studio/server/proxies.mjs): from a lighter copy made in the background, as+ * CapCut's proxies, and how tall that copy is. Exports always read the originals.+ */+function PlaybackGroup() {+ const t = useT();+ const [prefs, setPrefs] = React.useState<StudioPrefs | null>(null);+ React.useEffect(() => { void api.prefs().then(setPrefs).catch(() => {}); }, []);+ if (!prefs) return null;+ const change = (proxies: Partial<StudioPrefs['proxies']>) => {+ setPrefs({ proxies: { ...prefs.proxies, ...proxies } });+ void api.setPrefs({ proxies }).then(setPrefs).catch(() => {});+ };+ return (+ <SettingsGroup title={t('settings.playback.group')}>+ <SettingsItem+ title={t('settings.playback.proxies')}+ description={t('settings.playback.proxiesHint')}+ control={<SettingsSwitch checked={prefs.proxies.on} onChange={(on) => change({ on })} label={t('settings.playback.proxies')} />}+ />+ {prefs.proxies.on ? (+ <SettingsItem+ title={t('settings.playback.proxySize')}+ description={t('settings.playback.proxySizeHint')}+ control={(+ <SettingsSegmented<'540' | '720' | '1080'>+ label={t('settings.playback.proxySize')}+ value={String(prefs.proxies.height) as '540' | '720' | '1080'}+ onChange={(v) => change({ height: Number(v) as 540 | 720 | 1080 })}+ options={[{ value: '540', label: '540p' }, { value: '720', label: '720p' }, { value: '1080', label: '1080p' }]}+ />+ )}+ />+ ) : null}+ </SettingsGroup>+ );+}+/*** This Studio's version and whether npm has a newer openfilm. In the desktop app, Studio comes with the app and is* updated with it; anywhere else the person (or their agent) runs the latest, and the CLI restarts Studio on it.diff --git a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsxindex ec4ae96..e326293 100644--- a/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx+++ b/packages/openfilm/studio/ui/src/components/use-editor-tools.tsx@@ -17,11 +17,11 @@ import {} from '@/lib/markers';import type { ClipEdit } from '@/lib/film-clip-edits';import { heardClips, toggleSolo } from '@/lib/solo';-import type { EditMode, EditModel } from '@/lib/timeline-edit';+import { magnetOn, type EditMode, type EditModel } from '@/lib/timeline-edit';import type { KeyCommand } from '@/lib/timeline-keys';import type { TimelineBlock, TimelineTrack } from '@/lib/timeline-layout';import type { MediaListing } from '@/lib/workspace-resources';-import { readTimelinePrefs } from '@/lib/timeline-prefs';+import { followOf, readTimelinePrefs } from '@/lib/timeline-prefs';import { sizeOf, trackHeightsOf, withTrackHeight, TRACK_SIZES, type TrackSize } from '@/lib/track-heights';import type { Player } from '@/editor/player';import type { ContextMenuEntry } from './ContextMenu';@@ -239,8 +239,9 @@ export function useEditorTools({try { still = await api.freezeFrame(projectId, block.src, srcMs); }catch (e) { toast.showError(t('editorTools.freezeFail').replace('{reason}', (e as Error).message)); return; }const prefs = readTimelinePrefs();- const mode: EditMode = prefs.magnet ? 'insert' : 'overwrite';- const ops = planFreeze(editModel(), { clip, track: ti, atMs: at, still, mode, sync: prefs.sync });+ const model = editModel();+ const mode: EditMode = magnetOn(model, ti, prefs.magnet) ? 'insert' : 'overwrite';+ const ops = planFreeze(model, { clip, track: ti, atMs: at, still, mode, ...followOf(prefs) });if (!ops) { toast.show(t('timeline.trackLocked')); return; }const failed = await edit(ops, `history.stepFroze|${clip.id}`);if (failed) toast.showError(failed);diff --git a/packages/openfilm/studio/ui/src/components/useBlockDrag.ts b/packages/openfilm/studio/ui/src/components/useBlockDrag.tsindex ebc01d3..7308f1f 100644--- a/packages/openfilm/studio/ui/src/components/useBlockDrag.ts+++ b/packages/openfilm/studio/ui/src/components/useBlockDrag.ts@@ -40,17 +40,19 @@ import {} from '@/lib/timeline-drag';import {linkedIds,+ magnetOn,planEdges,planMove,planRippleTrim,rollMoves,slideMoves,+ sourceLeftMs,type EditMode,type EditModel,type EditPlan,type TrackDest,} from '@/lib/timeline-edit';-import type { TimelinePrefs } from '@/lib/timeline-prefs';+import { followOf, type TimelinePrefs } from '@/lib/timeline-prefs';import { snapToFrame } from '@/lib/timecode';import type { TimelineBlock, TimelineTrack } from '@/lib/timeline-layout';@@ -84,6 +86,8 @@ export interface GestureTip {deltaMs: number;/** The clip's length now, for a trim. */lengthMs?: number;+ /** A trim that reached the end of the clip's source on that side: it can go no further. */+ sourceEnd?: boolean;/** Where to show it: this film time, on this row. */atMs: number;lane: number;@@ -289,7 +293,8 @@ export function useBlockDrag(opts: {const snapCache = new Map<string, SnapTarget[]>();/* without the magnet a trim stops at the neighbors on the clip's own track (every row of it) */const fence = mode === 'trim-start' || mode === 'trim-end' ? trimFence(geom, singleLanes[homeLaneIndex]?.occupied ?? []) : undefined;- const ripple = prefs.magnet && (mode === 'trim-start' || mode === 'trim-end');+ /* the magnet acts on the main track alone: a trim there ripples, elsewhere it stops at the neighbors */+ const ripple = magnetOn(model, homeLane?.docIndex, prefs.magnet) && (mode === 'trim-start' || mode === 'trim-end');let dragging = false;let last: DragPreview | null = null;@@ -342,13 +347,16 @@ export function useBlockDrag(opts: {const edge = mode === 'trim-end' ? 'end' : 'start';const want = edge === 'end' ? out.endMs - geom.endMs : out.startMs - geom.startMs;plan = ripple- ? planRippleTrim(m, ids, edge, want, { sync: p.sync })+ ? planRippleTrim(m, ids, edge, want, followOf(p)): planEdges(m, ids.map((id) => ({ id, kind: edge })), want);if (plan.deltaMs === want) snappedTo = out.snappedTo;const own = plan.placed.get(block.clipId!);+ /* how much source is left past that edge once it moved (pulled out, the edge moves away from the clip) */+ const left = (sourceLeftMs(m, block.clipId!, edge) ?? Infinity) - (edge === 'end' ? plan.deltaMs : -plan.deltaMs);tip = {kind: ripple ? 'ripple' : 'trim', deltaMs: plan.deltaMs, lengthMs: own ? own.endMs - own.startMs : geom.endMs - geom.startMs,atMs: edge === 'end' || ripple ? (own?.endMs ?? geom.endMs) : (own?.startMs ?? geom.startMs), lane: homeLaneIndex,+ ...(left < 1 ? { sourceEnd: true } : {}),};} else if (mode === 'roll') {const out = applyDrag(geom, 'trim-end', deltaMs, targets, pxPerMs);@@ -417,7 +425,13 @@ export function useBlockDrag(opts: {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 });+ /* the track it lands on: the magnet inserts on the main track; elsewhere with the magnet it covers nothing (a clip+ landing on another goes to a free track, see planMove), ⌥ inserting there */+ const landsOn = drop.action === 'move' ? drop.trackIndex : drop.action === 'insert' ? null : homeLane?.docIndex;+ const onMain = magnetOn(m, landsOn, p.magnet);+ const editMode: EditMode = p.magnet && !onMain+ ? (altNow ? 'insert' : 'overwrite')+ : moveEditMode({ magnet: onMain, 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);@@ -433,7 +447,8 @@ export function useBlockDrag(opts: {pointerMs: grabMs + deltaMs,to,mode: editMode,- sync: p.sync,+ magnet: p.magnet,+ ...followOf(p),});lastPlan = plan;document.body.style.cursor = outside ? 'copy' : 'grabbing';diff --git a/packages/openfilm/studio/ui/src/editor/Preview.tsx b/packages/openfilm/studio/ui/src/editor/Preview.tsxindex 7838b63..783e744 100644--- a/packages/openfilm/studio/ui/src/editor/Preview.tsx+++ b/packages/openfilm/studio/ui/src/editor/Preview.tsx@@ -4,9 +4,9 @@* what is under a point. The stage (studio/server/stage.js) answers the picture-area* editing's questions (`stage`) and tells of an in-place text edit ending and of keys pressed in the picture.*- * An edit is applied to the page in place (a move, a trim, a volume, a tweak, and clips added or removed: a split, a- * paste, a drop, a delete), what it puts on screen made ready out of sight first (src/timeline.mjs); only another stage- * or head of the film, a page or file it uses changed on disk, or a clip that cannot load, loads the film again, in a+ * An edit is applied to the page in place (a move, a trim, a volume, a tweak, clips added or removed: a split, a+ * paste, a drop, a delete, and another stage size), what it puts on screen made ready out of sight first+ * (src/timeline.mjs); only another head of the film (its styles), a page or file it uses changed on disk, or a clip that cannot load, loads the film again, in a* second, hidden frame that replaces the shown one once its first picture is drawn whole (its videos loaded, however* long that takes), and is told the edits made meanwhile. Either way the picture never goes black for an edit.*/@@ -17,6 +17,9 @@ import type { ClipSpan } from '@/lib/film-shape';import type { Sound } from './player';import { reloaded, shownAfter, updateKeys, type Frame } from './preview-frames';+/** How far the film's frame reaches past the picture's box on each side, in px (see the `stage-frames` clip). */+const BLEED = 1;+export type FilmInfo = { duration: number; width: number; height: number; sounds: Sound[]; spans: ClipSpan[] };/** What is selected in the picture: an element of a page (named by selector and match), or a whole clip. */export type Target = {@@ -253,6 +256,10 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ foldereturn (<div className="stage-box" ref={box}><div className="stage" style={{ width: fit.w, height: fit.h }}>+ {/* the frames, clipped to the picture's whole-px box; each reaches BLEED px past it on every side, so the edge+ of a frame (a part of a device px a browser rounds its own way, a backdrop it paints under the film) is+ never on screen as a line along the picture */}+ <div className="stage-frames">{frames.map((f) => (<iframekey={f.key}@@ -265,9 +272,14 @@ export const Preview = forwardRef<PreviewHandle, Props>(function Preview({ folde/* the one loading is transparent, not hidden: the film is on another site, in a process of its own, and aframe hidden from there is not drawn at all, so a page that waits to draw (an image's decode()) wouldnever be ready */- style={{ width: stage.w, height: stage.h, transform: `scale(${fit.k})`, ...(f === shown ? {} : { opacity: 0, pointerEvents: 'none' }) }}+ style={{+ width: stage.w, height: stage.h,+ transform: `translate(${-BLEED}px, ${-BLEED}px) scale(${(fit.w + 2 * BLEED) / stage.w}, ${(fit.h + 2 * BLEED) / stage.h})`,+ ...(f === shown ? {} : { opacity: 0, pointerEvents: 'none' }),+ }}/>))}+ </div>{shown && !error ? children : null}{!shown && !error ? <div className="cover"><span role="status" className="text-sweep">{t('project.previewStageMount')}</span></div> : null}{error ? (diff --git a/packages/openfilm/studio/ui/src/globals.css b/packages/openfilm/studio/ui/src/globals.cssindex 425ddeb..e7eb4e5 100644--- a/packages/openfilm/studio/ui/src/globals.css+++ b/packages/openfilm/studio/ui/src/globals.css@@ -505,11 +505,20 @@ body.tl-scrubbing * {/* handles of what is selected reach past the picture's edge */overflow: visible;}+.stage-frames {+ position: absolute;+ inset: 0;+ overflow: hidden;+ background: #000;+}.stage iframe {position: absolute;left: 0;top: 0;border: 0;+ /* the film's own scheme (it sets none): a frame of another scheme than its page gets an opaque white backdrop in+ Chrome, which shows as a light line along the picture's right and bottom edges in the dark theme */+ color-scheme: light;transform-origin: 0 0;pointer-events: none;}diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.tsindex 7293ac6..eb6eb20 100644--- a/packages/openfilm/studio/ui/src/i18n/en.ts+++ b/packages/openfilm/studio/ui/src/i18n/en.ts@@ -162,9 +162,10 @@ export const en = {get: 'Get',cancel: 'Cancel',retry: 'Try again',- size: '{size} so far',+ left: 'About {time} left',+ close: 'Close',phase: {- lookup: 'Looking up the repository…',+ lookup: 'Getting the list of files…',download: 'Downloading…',checkout: 'Writing files…',copy: 'Opening…',@@ -178,8 +179,8 @@ export const en = {noFolder: 'That folder isn’t in the repository.',noFilm: 'There’s no film.html in that folder, so it isn’t an OpenFilm film.',tooBig: 'It’s too big to get, so it was stopped.',- timeout: 'It took too long, so it was stopped.',- git: 'Studio needs git to get films. Install git, then try again.',+ timeout: 'Nothing came for a while, so it was stopped. Check your internet connection, then try again.',+ git: 'This one needs git: it is private, or not on GitHub. Install git, then try again.',},},examples: {@@ -233,7 +234,7 @@ export const en = {slides: 'Slides & PDF',project: 'Project',alpha: 'Transparent assets',- nle: 'Editing software',+ nle: 'Editing project',},destHint: {social: 'Presets for every platform',@@ -245,7 +246,7 @@ export const en = {slides: 'One slide per shot',project: 'The whole project, to hand on',alpha: 'Alpha for AE, Final Cut, web',- nle: 'Premiere Pro, DaVinci Resolve',+ nle: '{app}, Premiere Pro, DaVinci Resolve',},destDesc: {social: 'Pick one or more platforms. Each gets the right shape, size and frame rate, and they export in one go.',@@ -257,7 +258,7 @@ export const en = {slides: 'A deck or PDF with one slide per shot — ready to present or print.',project: 'The project itself — its film, pages and media, and the parts you choose — as a zip or a folder that opens in OpenFilm.',alpha: 'Video with a transparent background — the whole film or a single element — to layer into your own edits, apps and websites.',- nle: 'The timeline itself, ready to keep cutting: an XML your editor imports, each page as a ProRes 4444 clip with alpha, your footage and sounds on their own tracks.',+ nle: 'The timeline itself, ready to keep cutting: a {app} draft or an XML your editor imports, each page as a clip with alpha, your footage and sounds on their own tracks.',},group: {landscape: 'Landscape 16:9',@@ -336,6 +337,8 @@ export const en = {range: 'Range',rangeAll: 'Whole film',rangePart: 'A part',+ rangeFrom: 'From',+ rangeTo: 'To',saveTo: 'Save to',change: 'Change…',pickTitle: 'Choose where to save exports',@@ -364,12 +367,17 @@ export const en = {},alphaScale: 'Size',alphaHint: 'Only what the film draws is kept; the stage background is removed. If an element paints its own full-screen background, the export will come out opaque — put that background on its own clip.',- nleTitle: 'Editor XML',+ nleFor: 'For',+ nleDraftTitle: '{app} draft',+ nleSrt: 'Include subtitles (SRT)',+ nleSubs: 'Include subtitles',+ nleHintPremiere: 'Creates a folder with the XML and a media folder. In Premiere Pro: File › Import. Keep the folder where it is, or relink after moving it.',+ nleHintResolve: 'Creates a folder with the XML and a media folder. In DaVinci Resolve: File › Import › Timeline. Keep the folder where it is, or relink after moving it.',+ nleHintDraft: "Makes a draft in {app}'s drafts folder, so it is on {app}'s home screen (if {app} is open, restart it). Pages come as clips with alpha, subtitles as a text track.",+ nleHintDraftNone: "{app} isn't on this computer: the draft is made in the export folder. Move it into {app}'s drafts folder (Settings › Drafts location).",nleAudio: 'Sound on the timeline',nleAudioClips: 'Separate clips',nleAudioStems: 'Mixed stems',- nleSrt: 'Include subtitles (SRT)',- nleHint: 'Creates a folder with the XML and a media folder. Premiere Pro: File › Import. DaVinci Resolve: File › Import › Timeline. Keep the folder where it is, or relink after moving it.',projectZip: 'Zip',projectZipHint: 'One file, easy to send or upload.',projectFolder: 'Folder',@@ -491,6 +499,7 @@ export const en = {stepSlid: 'Slid {clip}',stepRippleTrimmed: 'Ripple trimmed {clip}',stepGapClosed: 'Closed a gap',+ stepMainClosed: 'Closed up the main track',stepLinked: 'Linked {clip}',stepUnlinked: 'Unlinked {clip}',stepSpeed: 'Changed the speed of {clip}',@@ -673,6 +682,8 @@ export const en = {propDimensions: 'Dimensions',propFps: 'Frame rate',propModified: 'Modified',+ propLinked: "Kept at",+ propProxy: "Proxy",kindAudio: 'Audio',uploadFailed: 'Import failed, please retry',unreadable: '“{name}” was imported, but it can’t be read as a picture, video or sound ({why}). Check the file, or import another copy.',@@ -681,7 +692,6 @@ export const en = {media: {insertSource: "Insert at the playhead",overwriteSource: "Overwrite at the playhead",- addToTimeline: "Add to timeline",close: 'Close',results: 'Results',moveFailed: 'Could not move it there.',@@ -696,6 +706,7 @@ export const en = {cannotPreview: 'This file cannot be previewed here.',scrub: 'Position',search: 'Search media',+ searchShort: "Search",clearSearch: 'Clear search',sort: 'Sort',import: 'Import media',@@ -706,10 +717,10 @@ export const en = {filter_image: 'Images',filter_audio: 'Audio',filter_page: 'Pages',- importing: 'Importing {n} file(s)… {p}%',+ filter_other: "Other",dismiss: 'Dismiss',emptyTitle: 'No media yet',- emptyBody: 'Import video, images or sound, or drop them here. Whatever your agent saves in this project shows up here too.',+ emptyBody: "Import video, images, sound or any other file, or drop them here. Whatever your agent saves in this project shows up here too.",noMatch: 'Nothing matches your search.',copyPath: 'Copy path',dropHint: 'Drop to import into this project',@@ -717,6 +728,36 @@ export const en = {sort_time: 'Date modified',sort_duration: 'Duration',sort_type: 'Type',+ moveTo: "Move to",+ moveHere: "It’s already here",+ deleteMany: "Delete {n} items",+ deleteManyTitle: "Delete {n} items?",+ deleteManyConfirm: "They move to the Trash, where you can take them back.",+ deleteManyAlsoClip: "They move to the Trash, where you can take them back. The clip using one of them on the timeline is removed too.",+ deleteManyAlsoClips: "They move to the Trash, where you can take them back. The {n} clips using them on the timeline are removed too.",+ importFiles: "Import files…",+ importFilesNote: "A copy goes into the project",+ linkFiles: "Link files…",+ linkFilesNote: "They stay where they are, on a NAS or another disk",+ linkFolder: "Link a folder…",+ pickImport: "Choose files to import",+ pickLink: "Choose files to link",+ pickLinkFolder: "Choose a folder to link",+ pickRelink: "Where is it now?",+ noDialog: "This system has no file dialog Studio can open. Drop the files here instead.",+ revealOriginal: "Show original",+ relink: "Relink…",+ relinkFailed: "Couldn’t link it there",+ collect: "Copy into project",+ collectNote: "The original stays where it is",+ collectFailed: "Couldn’t copy it into the project",+ linkMissing: "Not found",+ linkedFrom: "Linked from {path}",+ proxy: "Proxy",+ proxyMaking: "Making a proxy… {p}%",+ proxyWaiting: "Proxy waiting its turn",+ proxyFailed: "A proxy couldn’t be made: it plays from the original",+ proxyReady: "Ready: the viewer plays it",},assetsPane: {show: 'Show assets',@@ -827,8 +868,9 @@ export const en = {at: 'Start',duration: 'Duration',inPoint: 'In point',+ inPointWhole: 'The clip plays all of its file. Shorten it to move the in point.',speed: 'Speed',- speedLimit: 'Slower than {n}× runs into the next clip. Turn on the magnet in the timeline to push it along.',+ speedLimit: 'Slower than {n}× runs into the next clip. On the main track, the magnet in the timeline pushes it along.',speedTooSlow: 'Slower than {n}× runs into the next clip on its track.',sound: 'Sound',gainDb: 'Volume',@@ -930,12 +972,27 @@ export const en = {effectAdd: 'Add an effect',effectRemove: 'Remove',effectCustom: 'written by hand, under Advanced',- effectsNone: 'None yet: add a shadow, a stroke or faded edges with +.',+ effectsNone: 'None yet: add a shadow, a blur or faded edges with +.',shadowX: 'Shadow X',shadowY: 'Shadow Y',shadowBlur: 'Shadow blur',shadowColor: 'Shadow color',stroke: 'Stroke',+ strokeAdd: 'Add stroke',+ strokePosition: 'Stroke position',+ strokePositions: { inside: 'Inside', center: 'Center', outside: 'Outside' },+ strokeCut: 'A crop, a mask or faded edges cut away what is drawn past the edge: pick Inside to see all of it.',+ fillAdd: 'Add fill',+ fillRemove: 'Remove fill',+ innerShadow: 'Inner shadow',+ layerBlur: 'Layer blur',+ backgroundBlur: 'Background blur',+ shadowSpread: 'Spread',+ cornersEach: 'Independent corners',+ cornersCropped: 'A crop rounds its corners alike',+ corners: { 'top-left': 'Top left', 'top-right': 'Top right', 'bottom-right': 'Bottom right', 'bottom-left': 'Bottom left' },+ textDecoration: 'Decoration',+ decorations: { none: 'None', underline: 'Underline', lineThrough: 'Strikethrough' },strokeWidth: 'Stroke width',strokeStyle: 'Stroke style',strokeColor: 'Stroke color',@@ -1113,18 +1170,22 @@ export const en = {zoomFit: 'Fit to width',zoom: 'Zoom',snap: 'Snap',- snapOn: 'On: snaps to edges, the playhead, and words',+ snapOn: 'On: snaps to clip edges, the playhead and markers',snapOff: 'Off: drops exactly where you let go',- magnet: 'Magnet',- magnetOn: 'On: a clip put down inserts and pushes what follows, delete closes the gap, trims ripple. Hold Alt while dropping for overwrite',- magnetOff: 'Off: a clip put down overwrites what is under it. Hold Alt while dropping to insert',+ magnet: 'Main track magnet',+ magnetOn: 'On: the main track (the lowest picture track) stays closed up. A clip put down there inserts, delete closes the gap, trims ripple. Other tracks never cover a clip: one put where another is goes to a free track, and delete leaves a gap. Hold Alt while dropping for the other way',+ magnetOff: 'Off: the main track is like the others. A clip put down overwrites what is under it. Hold Alt while dropping to insert',+ linkage: 'Linkage',+ linkageOn: 'On: when clips on the main track move, the titles, B-roll and sound that start over them move along. A long clip under several shots (a music bed) stays',+ linkageOff: 'Off: an edit on the main track moves the main track only',sync: 'Sync lock',- syncOn: 'On: a ripple moves every unlocked track along, so sound and B-roll stay in sync',+ syncOn: 'On (as Premiere): a ripple on any track moves every unlocked track along, as far as all of them have room',syncOff: "Off: a ripple moves only the clips' own tracks",linked: 'Linked clips',linkedOn: 'On: a video and its detached sound are selected and edited together. Alt-click picks one',linkedOff: 'Off: linked clips are selected and edited one by one',rippleShort: "Clips on another track were in the way: {s} s left open so everything stays in sync. Turn off sync lock to close it on this track alone.",+ gapClosedAlone: 'Clips on other tracks were in the way, so the gap closed on this track alone.',menuCloseGap: 'Close gap',menuRippleStart: 'Ripple trim start to playhead',menuRippleEnd: 'Ripple trim end to playhead',@@ -1137,6 +1198,7 @@ export const en = {roll: 'Roll',slip: 'Slip',slide: 'Slide',+ sourceEnd: 'End of the media',},trackLocked: 'Track locked',dropNotClip: "This asset can't go on the timeline",@@ -1220,12 +1282,9 @@ export const en = {crossfade: 'Audio crossfade',remove: 'Remove transition',atCut: 'Transition',- atStart: 'At its start',- atEnd: 'At its end',locked: 'A clip it changes is on a locked track',none: 'There is no cut there: select a clip, or put the playhead by a cut',short: 'The clips are too short for that',- failed: 'The transition could not be made: {error}',mark: '{kind} · {s} s — drag an edge to change its length; Delete removes it',handle: '{what}: {s} s — drag inward to fade (⌥: this clip alone)',fadeTip: '{what} {s} s',@@ -1297,6 +1356,13 @@ export const en = {themeHint: 'Light, dark, or the same as your system.',languageHint: 'The language OpenFilm shows itself in.',},+ playback: {+ group: "Playback",+ proxies: "Proxies for heavy footage",+ proxiesHint: "Footage past 1080p, or slow to decode (ProRes, HEVC, 10-bit), plays from a lighter copy made in the background. Exports always use the originals.",+ proxySize: "Proxy size",+ proxySizeHint: "Smaller plays more smoothly; larger looks sharper in the viewer.",+ },about: {group: 'About',check: 'Check for updates',diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.tsindex 3d7980e..535499e 100644--- a/packages/openfilm/studio/ui/src/i18n/es.ts+++ b/packages/openfilm/studio/ui/src/i18n/es.ts@@ -161,9 +161,10 @@ export const es: Words = {get: 'Obtener',cancel: 'Cancelar',retry: 'Reintentar',- size: '{size} hasta ahora',+ left: 'Quedan unos {time}',+ close: 'Cerrar',phase: {- lookup: 'Buscando el repositorio…',+ lookup: 'Obteniendo la lista de archivos…',download: 'Descargando…',checkout: 'Escribiendo archivos…',copy: 'Abriendo…',@@ -177,8 +178,8 @@ export const es: Words = {noFolder: 'Esa carpeta no está en el repositorio.',noFilm: 'No hay film.html en esa carpeta, así que no es una película de OpenFilm.',tooBig: 'Es demasiado grande, así que se detuvo.',- timeout: 'Tardó demasiado, así que se detuvo.',- git: 'Studio necesita git para obtener películas. Instala git y vuelve a intentarlo.',+ timeout: 'No llegó nada durante un rato, así que se detuvo. Revisa tu conexión a internet y vuelve a intentarlo.',+ git: 'Este necesita git: es privado o no está en GitHub. Instala git y vuelve a intentarlo.',},},examples: {@@ -232,7 +233,7 @@ export const es: Words = {slides: 'Diapositivas y PDF',project: 'Proyecto',alpha: 'Recursos con transparencia',- nle: 'Software de edición',+ nle: 'Proyecto de edición',},destHint: {social: 'Ajustes preestablecidos para cada plataforma',@@ -244,7 +245,7 @@ export const es: Words = {slides: 'Una diapositiva por plano',project: 'El proyecto entero, para pasarlo',alpha: 'Alfa para AE, Final Cut, web',- nle: 'Premiere Pro, DaVinci Resolve',+ nle: '{app}, Premiere Pro, DaVinci Resolve',},destDesc: {social: 'Elige una o más plataformas. Cada una recibe la forma, el tamaño y la velocidad de fotogramas adecuados, y se exportan de una vez.',@@ -256,7 +257,7 @@ export const es: Words = {slides: 'Una presentación o PDF con una diapositiva por plano, lista para presentar o imprimir.',project: 'El proyecto en sí —su película, páginas y medios, y las partes que elijas— como un zip o una carpeta que se abre en OpenFilm.',alpha: 'Video con fondo transparente (la película entera o un solo elemento) para superponerlo en tus propias ediciones, apps y sitios web.',- nle: 'La propia línea de tiempo, lista para seguir editando: un XML que importa tu editor, cada página como un clip ProRes 4444 con alfa, y tu metraje y sonidos en sus propias pistas.',+ nle: 'La propia línea de tiempo, lista para seguir editando: un borrador de {app} o un XML que importa tu editor, cada página como un clip con alfa, y tu metraje y sonidos en sus propias pistas.',},group: {landscape: 'Horizontal 16:9',@@ -335,6 +336,8 @@ export const es: Words = {range: 'Intervalo',rangeAll: 'Película completa',rangePart: 'Una parte',+ rangeFrom: 'Desde',+ rangeTo: 'Hasta',saveTo: 'Guardar en',change: 'Cambiar…',pickTitle: 'Elige dónde guardar las exportaciones',@@ -363,12 +366,17 @@ export const es: Words = {},alphaScale: 'Tamaño',alphaHint: 'Solo se conserva lo que dibuja la película; se quita el fondo del escenario. Si un elemento pinta su propio fondo a pantalla completa, la exportación saldrá opaca: pon ese fondo en su propio clip.',- nleTitle: 'XML para el editor',+ nleFor: 'Para',+ nleDraftTitle: 'Borrador de {app}',+ nleSrt: 'Incluir subtítulos (SRT)',+ nleSubs: 'Incluir subtítulos',+ nleHintPremiere: 'Crea una carpeta con el XML y una carpeta de medios. En Premiere Pro: Archivo › Importar. Deja la carpeta donde está o vuelve a vincular los medios tras moverla.',+ nleHintResolve: 'Crea una carpeta con el XML y una carpeta de medios. En DaVinci Resolve: Archivo › Importar › Línea de tiempo. Deja la carpeta donde está o vuelve a vincular los medios tras moverla.',+ nleHintDraft: 'Crea un borrador en la carpeta de borradores de {app}, así aparece en su pantalla de inicio (si {app} está abierto, reinícialo). Las páginas llegan como clips con alfa y los subtítulos como una pista de texto.',+ nleHintDraftNone: '{app} no está en este equipo: el borrador se crea en la carpeta de exportación. Muévelo a la carpeta de borradores de {app} (Ajustes › Ubicación de borradores).',nleAudio: 'Sonido en la línea de tiempo',nleAudioClips: 'Clips separados',nleAudioStems: 'Stems mezclados',- nleSrt: 'Incluir subtítulos (SRT)',- nleHint: 'Crea una carpeta con el XML y una carpeta de medios. Premiere Pro: Archivo › Importar. DaVinci Resolve: Archivo › Importar › Línea de tiempo. Deja la carpeta donde está o vuelve a vincular los medios tras moverla.',projectZip: 'Zip',projectZipHint: 'Un solo archivo, fácil de enviar o subir.',projectFolder: 'Carpeta',@@ -490,6 +498,7 @@ export const es: Words = {stepSlid: '{clip} deslizado entre sus vecinos',stepRippleTrimmed: 'Recorte con desplazamiento de {clip}',stepGapClosed: 'Hueco cerrado',+ stepMainClosed: 'Pista principal cerrada',stepLinked: '{clip} vinculado',stepUnlinked: '{clip} desvinculado',stepSpeed: 'Velocidad de {clip} cambiada',@@ -672,6 +681,8 @@ export const es: Words = {propDimensions: 'Dimensiones',propFps: 'Velocidad de fotogramas',propModified: 'Modificado',+ propLinked: "Guardado en",+ propProxy: "Proxy",kindAudio: 'Audio',uploadFailed: 'Error al importar, inténtalo de nuevo',unreadable: '“{name}” se importó, pero no se puede leer como imagen, video o sonido ({why}). Revisa el archivo o importa otra copia.',@@ -680,7 +691,6 @@ export const es: Words = {media: {insertSource: "Insertar en el cabezal",overwriteSource: "Sobrescribir en el cabezal",- addToTimeline: "Añadir a la línea de tiempo",close: 'Cerrar',results: 'Resultados',moveFailed: 'No se pudo mover ahí.',@@ -695,6 +705,7 @@ export const es: Words = {cannotPreview: 'Este archivo no se puede previsualizar aquí.',scrub: 'Posición',search: 'Buscar medios',+ searchShort: "Buscar",clearSearch: 'Borrar búsqueda',sort: 'Ordenar',import: 'Importar medios',@@ -705,10 +716,10 @@ export const es: Words = {filter_image: 'Imágenes',filter_audio: 'Audio',filter_page: 'Páginas',- importing: 'Importando {n} archivo(s)… {p} %',+ filter_other: "Otros",dismiss: 'Descartar',emptyTitle: 'Aún no hay medios',- emptyBody: 'Importa video, imágenes o sonido, o suéltalos aquí. Todo lo que tu agente guarde en este proyecto también aparece aquí.',+ emptyBody: "Importa video, imágenes, sonido o cualquier otro archivo, o suéltalos aquí. Todo lo que tu agente guarde en este proyecto también aparece aquí.",noMatch: 'Nada coincide con la búsqueda.',copyPath: 'Copiar ruta',dropHint: 'Suelta para importar a este proyecto',@@ -716,6 +727,36 @@ export const es: Words = {sort_time: 'Fecha de modificación',sort_duration: 'Duración',sort_type: 'Tipo',+ moveTo: "Mover a",+ moveHere: "Ya está aquí",+ deleteMany: "Eliminar {n} elementos",+ deleteManyTitle: "¿Eliminar {n} elementos?",+ deleteManyConfirm: "Se mueven a la Papelera, desde donde puedes recuperarlos.",+ deleteManyAlsoClip: "Se mueven a la Papelera, desde donde puedes recuperarlos. También se quita el clip que usa uno de ellos en la línea de tiempo.",+ deleteManyAlsoClips: "Se mueven a la Papelera, desde donde puedes recuperarlos. También se quitan los {n} clips que los usan en la línea de tiempo.",+ importFiles: "Importar archivos…",+ importFilesNote: "Se copia en el proyecto",+ linkFiles: "Vincular archivos…",+ linkFilesNote: "Se quedan donde están, en un NAS u otro disco",+ linkFolder: "Vincular una carpeta…",+ pickImport: "Elige los archivos que importar",+ pickLink: "Elige los archivos que vincular",+ pickLinkFolder: "Elige la carpeta que vincular",+ pickRelink: "¿Dónde está ahora?",+ noDialog: "Este sistema no tiene un diálogo de archivos que Studio pueda abrir. Suelta los archivos aquí.",+ revealOriginal: "Mostrar el original",+ relink: "Volver a vincular…",+ relinkFailed: "No se pudo vincular ahí",+ collect: "Copiar al proyecto",+ collectNote: "El original se queda donde está",+ collectFailed: "No se pudo copiar al proyecto",+ linkMissing: "No encontrado",+ linkedFrom: "Vinculado desde {path}",+ proxy: "Proxy",+ proxyMaking: "Creando el proxy… {p} %",+ proxyWaiting: "Proxy en espera",+ proxyFailed: "No se pudo crear el proxy: se reproduce el original",+ proxyReady: "Listo: el visor lo reproduce",},assetsPane: {show: 'Mostrar recursos',@@ -826,8 +867,9 @@ export const es: Words = {at: 'Inicio',duration: 'Duración',inPoint: 'Punto de entrada',+ inPointWhole: 'El clip reproduce todo su archivo. Acórtalo para mover el punto de entrada.',speed: 'Velocidad',- speedLimit: 'Más lento que {n}× choca con el clip siguiente. Activa el imán en la línea de tiempo para empujarlo.',+ speedLimit: 'Más lento que {n}× choca con el clip siguiente. En la pista principal, el imán de la línea de tiempo lo empuja.',speedTooSlow: 'Más lento que {n}× choca con el clip siguiente de su pista.',sound: 'Sonido',gainDb: 'Volumen',@@ -929,12 +971,27 @@ export const es: Words = {effectAdd: 'Añadir un efecto',effectRemove: 'Quitar',effectCustom: 'escrito a mano, en Avanzado',- effectsNone: 'Ninguno todavía: añade una sombra, un trazo o bordes difuminados con +.',+ effectsNone: 'Ninguno todavía: añade una sombra, un desenfoque o bordes difuminados con +.',shadowX: 'Sombra X',shadowY: 'Sombra Y',shadowBlur: 'Desenfoque de la sombra',shadowColor: 'Color de la sombra',stroke: 'Trazo',+ strokeAdd: 'Añadir trazo',+ strokePosition: 'Posición del trazo',+ strokePositions: { inside: 'Interior', center: 'Centro', outside: 'Exterior' },+ strokeCut: 'Un recorte, una máscara o los bordes difuminados cortan lo que se dibuja fuera del borde: elige Interior para verlo entero.',+ fillAdd: 'Añadir relleno',+ fillRemove: 'Quitar relleno',+ innerShadow: 'Sombra interior',+ layerBlur: 'Desenfoque de capa',+ backgroundBlur: 'Desenfoque de fondo',+ shadowSpread: 'Extensión',+ cornersEach: 'Esquinas independientes',+ cornersCropped: 'Un recorte redondea todas sus esquinas por igual',+ corners: { 'top-left': 'Arriba a la izquierda', 'top-right': 'Arriba a la derecha', 'bottom-right': 'Abajo a la derecha', 'bottom-left': 'Abajo a la izquierda' },+ textDecoration: 'Decoración',+ decorations: { none: 'Ninguna', underline: 'Subrayado', lineThrough: 'Tachado' },strokeWidth: 'Grosor del trazo',strokeStyle: 'Estilo del trazo',strokeColor: 'Color del trazo',@@ -1112,18 +1169,22 @@ export const es: Words = {zoomFit: 'Ajustar al ancho',zoom: 'Zoom',snap: 'Ajuste',- snapOn: 'Activado: se ajusta a bordes, al cabezal de reproducción y a palabras',+ snapOn: 'Activado: se ajusta a los bordes de los clips, al cabezal de reproducción y a los marcadores',snapOff: 'Desactivado: se coloca justo donde lo sueltas',- magnet: 'Imán',- magnetOn: 'Activado: un clip soltado se inserta y empuja lo que sigue, eliminar cierra el hueco, recortar desplaza. Mantén Alt al soltar para sobrescribir',- magnetOff: 'Desactivado: un clip soltado sobrescribe lo que hay debajo. Mantén Alt al soltar para insertar',+ magnet: 'Imán de la pista principal',+ magnetOn: 'Activado: la pista principal (la pista de imagen más baja) queda siempre sin huecos. Un clip soltado ahí se inserta, eliminar cierra el hueco, recortar desplaza. En las demás pistas ningún clip tapa a otro: uno soltado donde ya hay otro pasa a una pista libre, y eliminar deja un hueco. Mantén Alt al soltar para lo contrario',+ magnetOff: 'Desactivado: la pista principal es como las demás. Un clip soltado sobrescribe lo que hay debajo. Mantén Alt al soltar para insertar',+ linkage: 'Vinculación',+ linkageOn: 'Activada: cuando se mueven clips de la pista principal, los títulos, el B-roll y el sonido que empiezan sobre ellos se mueven con ellos. Un clip largo bajo varias tomas (una música de fondo) se queda',+ linkageOff: 'Desactivada: editar la pista principal mueve solo la pista principal',sync: 'Bloqueo de sincronía',- syncOn: 'Activado: un desplazamiento mueve todas las pistas desbloqueadas, así el sonido y el B-roll siguen sincronizados',+ syncOn: 'Activado (como en Premiere): un desplazamiento en cualquier pista mueve todas las pistas desbloqueadas, mientras todas tengan espacio',syncOff: 'Desactivado: un desplazamiento mueve solo las pistas de los clips',linked: 'Clips vinculados',linkedOn: 'Activado: un video y su audio separado se seleccionan y editan juntos. Alt-clic elige uno',linkedOff: 'Desactivado: los clips vinculados se seleccionan y editan uno a uno',rippleShort: 'Había clips en otra pista: quedan {s} s abiertos para que todo siga sincronizado. Desactiva el bloqueo de sincronía para cerrarlo solo en esta pista.',+ gapClosedAlone: 'Había clips en otras pistas, así que el hueco se cerró solo en esta pista.',menuCloseGap: 'Cerrar hueco',menuRippleStart: 'Recortar inicio hasta el cabezal y desplazar',menuRippleEnd: 'Recortar final hasta el cabezal y desplazar',@@ -1136,6 +1197,7 @@ export const es: Words = {roll: 'Corte',slip: 'Contenido',slide: 'Deslizar',+ sourceEnd: 'Fin del medio',},trackLocked: 'Pista bloqueada',dropNotClip: 'Este recurso no se puede poner en la línea de tiempo',@@ -1219,12 +1281,9 @@ export const es: Words = {crossfade: 'Fundido cruzado de audio',remove: 'Quitar transición',atCut: 'Transición',- atStart: 'Al principio',- atEnd: 'Al final',locked: 'Un clip que cambia está en una pista bloqueada',none: 'Ahí no hay ningún corte: selecciona un clip o pon el cabezal junto a un corte',short: 'Los clips son demasiado cortos',- failed: 'No se pudo hacer la transición: {error}',mark: '{kind} · {s} s — arrastra un borde para cambiar la duración; Supr la quita',handle: '{what}: {s} s — arrastra hacia dentro para fundir (⌥: solo este clip)',fadeTip: '{what} {s} s',@@ -1296,6 +1355,13 @@ export const es: Words = {themeHint: 'Claro, oscuro o igual que el sistema.',languageHint: 'El idioma en que se muestra OpenFilm.',},+ playback: {+ group: "Reproducción",+ proxies: "Proxies para el metraje pesado",+ proxiesHint: "El metraje de más de 1080p, o lento de decodificar (ProRes, HEVC, 10 bits), se reproduce desde una copia ligera hecha en segundo plano. Las exportaciones siempre usan los originales.",+ proxySize: "Tamaño del proxy",+ proxySizeHint: "Más pequeño se reproduce con más fluidez; más grande se ve más nítido en el visor.",+ },about: {group: 'Acerca de',check: 'Buscar actualizaciones',diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.tsindex ae5ba6e..60d1784 100644--- a/packages/openfilm/studio/ui/src/i18n/ja.ts+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts@@ -161,9 +161,10 @@ export const ja: Words = {get: '取得',cancel: 'キャンセル',retry: 'もう一度',- size: '{size} 取得済み',+ left: '残り約 {time}',+ close: '閉じる',phase: {- lookup: 'リポジトリを確認しています…',+ lookup: 'ファイルの一覧を取得しています…',download: 'ダウンロードしています…',checkout: 'ファイルを書き出しています…',copy: '開いています…',@@ -177,8 +178,8 @@ export const ja: Words = {noFolder: 'そのフォルダーはリポジトリにありません。',noFilm: 'そのフォルダーには film.html がないため、OpenFilm のフィルムではありません。',tooBig: '大きすぎるため、取得を止めました。',- timeout: '時間がかかりすぎたため、止めました。',- git: 'フィルムの取得には git が必要です。git をインストールしてから、もう一度お試しください。',+ timeout: 'しばらく何も届かなかったため、止めました。インターネット接続を確認して、もう一度お試しください。',+ git: 'これは非公開か GitHub 以外にあるため、git が必要です。git をインストールしてから、もう一度お試しください。',},},examples: {@@ -232,7 +233,7 @@ export const ja: Words = {slides: 'スライド・PDF',project: 'プロジェクト',alpha: '透過素材',- nle: '編集ソフト',+ nle: '編集プロジェクト',},destHint: {social: '各プラットフォーム向けプリセット',@@ -244,7 +245,7 @@ export const ja: Words = {slides: '1 ショット 1 スライド',project: 'プロジェクト全体を渡す',alpha: 'AE、Final Cut、Web 用のアルファ付き',- nle: 'Premiere Pro、DaVinci Resolve',+ nle: '{app}、Premiere Pro、DaVinci Resolve',},destDesc: {social: 'プラットフォームを 1 つ以上選んでください。それぞれに合った形、サイズ、フレームレートで、まとめて書き出します。',@@ -256,7 +257,7 @@ export const ja: Words = {slides: '1 ショット 1 スライドのデッキまたは PDF — そのままプレゼンや印刷に使えます。',project: 'プロジェクトそのもの(フィルム、ページ、素材、選んだ部分)を、OpenFilm で開ける zip またはフォルダーとして書き出します。',alpha: '背景が透明なビデオ — 映像全体または単一の要素 — を、自分の編集、アプリ、Web サイトに重ねて使えます。',- nle: 'タイムラインそのものを、編集を続けられる形で書き出します。編集ソフトで読み込める XML、ページはそれぞれアルファ付き ProRes 4444 クリップとして、映像素材やサウンドは個別のトラックに配置されます。',+ nle: 'タイムラインそのものを、編集を続けられる形で書き出します。{app} の下書き、または編集ソフトで読み込める XML。ページはそれぞれアルファ付きクリップとして、映像素材やサウンドは個別のトラックに配置されます。',},group: {landscape: '横長 16:9',@@ -335,6 +336,8 @@ export const ja: Words = {range: '範囲',rangeAll: '映像全体',rangePart: '一部',+ rangeFrom: '開始',+ rangeTo: '終了',saveTo: '保存先',change: '変更…',pickTitle: '書き出しの保存先を選択',@@ -363,12 +366,17 @@ export const ja: Words = {},alphaScale: 'サイズ',alphaHint: '映像が描画したものだけが残り、ステージの背景は除去されます。要素自体が全画面の背景を描いている場合、書き出しは不透明になります — その背景は別のクリップに分けてください。',- nleTitle: '編集ソフト用 XML',+ nleFor: '書き出し先',+ nleDraftTitle: '{app} の下書き',+ nleSrt: '字幕を含める(SRT)',+ nleSubs: '字幕を含める',+ nleHintPremiere: 'XML とメディアフォルダーを含むフォルダーを作成します。Premiere Pro で:ファイル › 読み込み。フォルダーはそのままの場所に置くか、移動した場合はメディアを再リンクしてください。',+ nleHintResolve: 'XML とメディアフォルダーを含むフォルダーを作成します。DaVinci Resolve で:ファイル › 読み込み › タイムライン。フォルダーはそのままの場所に置くか、移動した場合はメディアを再リンクしてください。',+ nleHintDraft: '{app} の下書きフォルダーに直接作成するので、{app} のホーム画面に表示されます({app} を開いている場合は再起動してください)。ページはアルファ付きクリップ、字幕はテキストトラックになります。',+ nleHintDraftNone: 'このコンピューターに {app} が見つかりません。下書きは書き出しフォルダーに作成されます。{app} の下書きフォルダー(設定 › 下書きの保存先)に移動してください。',nleAudio: 'タイムライン上のサウンド',nleAudioClips: '個別のクリップ',nleAudioStems: 'ミックス済みステム',- nleSrt: '字幕を含める(SRT)',- nleHint: 'XML とメディアフォルダーを含むフォルダーを作成します。Premiere Pro:ファイル › 読み込み。DaVinci Resolve:ファイル › 読み込み › タイムライン。フォルダーはそのままの場所に置くか、移動した場合はメディアを再リンクしてください。',projectZip: 'Zip',projectZipHint: '1 つのファイルで、送信やアップロードが簡単です。',projectFolder: 'フォルダー',@@ -490,6 +498,7 @@ export const ja: Words = {stepSlid: '{clip} をスライド',stepRippleTrimmed: '{clip} をリップルトリム',stepGapClosed: '隙間を詰めました',+ stepMainClosed: 'メイントラックを詰めました',stepLinked: '{clip} をリンク',stepUnlinked: '{clip} のリンクを解除',stepSpeed: '{clip} の速度を変更',@@ -672,6 +681,8 @@ export const ja: Words = {propDimensions: '寸法',propFps: 'フレームレート',propModified: '変更日',+ propLinked: "保存場所",+ propProxy: "プロキシ",kindAudio: 'オーディオ',uploadFailed: '読み込みに失敗しました。もう一度お試しください',unreadable: '「{name}」は読み込まれましたが、画像・ビデオ・サウンドとして読み取れません({why})。ファイルを確認するか、別のコピーを読み込んでください。',@@ -680,7 +691,6 @@ export const ja: Words = {media: {insertSource: "再生ヘッドに挿入",overwriteSource: "再生ヘッドに上書き",- addToTimeline: "タイムラインに追加",close: '閉じる',results: '結果',moveFailed: 'そこへ移動できませんでした。',@@ -695,6 +705,7 @@ export const ja: Words = {cannotPreview: 'このファイルはここではプレビューできません。',scrub: '位置',search: 'メディアを検索',+ searchShort: "検索",clearSearch: '検索をクリア',sort: '並べ替え',import: 'メディアを読み込み',@@ -705,10 +716,10 @@ export const ja: Words = {filter_image: '画像',filter_audio: 'オーディオ',filter_page: 'ページ',- importing: '{n} 個のファイルを読み込み中… {p}%',+ filter_other: "その他",dismiss: '閉じる',emptyTitle: 'メディアはまだありません',- emptyBody: 'ビデオ、画像、サウンドを読み込むか、ここにドロップしてください。エージェントがこのプロジェクトに保存したものもここに表示されます。',+ emptyBody: "ビデオ、画像、サウンドなど、どんなファイルでも読み込むか、ここにドロップしてください。エージェントがこのプロジェクトに保存したものもここに表示されます。",noMatch: '検索に一致するものはありません。',copyPath: 'パスをコピー',dropHint: 'ドロップしてこのプロジェクトに読み込み',@@ -716,6 +727,36 @@ export const ja: Words = {sort_time: '変更日',sort_duration: 'デュレーション',sort_type: '種類',+ moveTo: "移動先",+ moveHere: "すでにここにあります",+ deleteMany: "{n} 個の項目を削除",+ deleteManyTitle: "{n} 個の項目を削除しますか?",+ deleteManyConfirm: "ゴミ箱に移動します。ゴミ箱から元に戻せます。",+ deleteManyAlsoClip: "ゴミ箱に移動します。ゴミ箱から元に戻せます。タイムライン上でこれらを使っているクリップも削除されます。",+ deleteManyAlsoClips: "ゴミ箱に移動します。ゴミ箱から元に戻せます。タイムライン上でこれらを使っている {n} 個のクリップも削除されます。",+ importFiles: "ファイルを読み込む…",+ importFilesNote: "プロジェクトにコピーします",+ linkFiles: "ファイルをリンク…",+ linkFilesNote: "NAS や別のディスクなど、元の場所に置いたままにします",+ linkFolder: "フォルダーをリンク…",+ pickImport: "読み込むファイルを選択",+ pickLink: "リンクするファイルを選択",+ pickLinkFolder: "リンクするフォルダーを選択",+ pickRelink: "今はどこにありますか?",+ noDialog: "このシステムには Studio が開けるファイルダイアログがありません。ファイルをここにドロップしてください。",+ revealOriginal: "元のファイルを表示",+ relink: "再リンク…",+ relinkFailed: "そこにリンクできませんでした",+ collect: "プロジェクトにコピー",+ collectNote: "元のファイルはそのまま残ります",+ collectFailed: "プロジェクトにコピーできませんでした",+ linkMissing: "見つかりません",+ linkedFrom: "{path} からリンク",+ proxy: "プロキシ",+ proxyMaking: "プロキシを作成中… {p}%",+ proxyWaiting: "プロキシの作成待ち",+ proxyFailed: "プロキシを作れませんでした。元の素材で再生します",+ proxyReady: "準備完了:ビューアで再生中",},assetsPane: {show: '素材を表示',@@ -826,8 +867,9 @@ export const ja: Words = {at: '開始',duration: 'デュレーション',inPoint: 'イン点',+ inPointWhole: 'クリップはファイル全体を再生しています。イン点を動かすには、先に短くしてください。',speed: '速度',- speedLimit: '{n}× より遅くすると次のクリップに重なります。タイムラインのマグネットをオンにすると後ろへ押し出します。',+ speedLimit: '{n}× より遅くすると次のクリップに重なります。メイントラックでは、タイムラインのメイントラックマグネットで後ろへ押し出せます。',speedTooSlow: '{n}× より遅くすると同じトラックの次のクリップに重なります。',sound: 'サウンド',gainDb: '音量',@@ -929,12 +971,27 @@ export const ja: Words = {effectAdd: 'エフェクトを追加',effectRemove: '削除',effectCustom: '手書き(「詳細」)',- effectsNone: 'まだありません。+ でシャドウ、線、端のフェードを追加。',+ effectsNone: 'まだありません。+ でシャドウ、ぼかし、端のフェードを追加。',shadowX: 'シャドウ X',shadowY: 'シャドウ Y',shadowBlur: 'シャドウのぼかし',shadowColor: 'シャドウの色',stroke: '線',+ strokeAdd: '線を追加',+ strokePosition: '線の位置',+ strokePositions: { inside: '内側', center: '中央', outside: '外側' },+ strokeCut: '切り抜き・マスク・端のフェードは、端の外に描かれた線を切り落とします。すべて見せるには「内側」を選んでください。',+ fillAdd: '塗りを追加',+ fillRemove: '塗りを削除',+ innerShadow: 'インナーシャドウ',+ layerBlur: 'レイヤーぼかし',+ backgroundBlur: '背景ぼかし',+ shadowSpread: '広がり',+ cornersEach: '角を個別に',+ cornersCropped: '切り抜きの角は同じ丸みになります',+ corners: { 'top-left': '左上', 'top-right': '右上', 'bottom-right': '右下', 'bottom-left': '左下' },+ textDecoration: '装飾',+ decorations: { none: 'なし', underline: '下線', lineThrough: '取り消し線' },strokeWidth: '線の太さ',strokeStyle: '線の種類',strokeColor: '線の色',@@ -1112,18 +1169,22 @@ export const ja: Words = {zoomFit: '幅に合わせる',zoom: 'ズーム',snap: 'スナップ',- snapOn: 'オン:端、再生ヘッド、単語にスナップします',+ snapOn: 'オン:クリップの端、再生ヘッド、マーカーにスナップします',snapOff: 'オフ:離した位置にそのまま配置します',- magnet: 'マグネット',- magnetOn: 'オン:置いたクリップは挿入されて後ろを押し出し、削除で隙間を詰め、トリムはリップルします。置くときに Alt で上書き',- magnetOff: 'オフ:置いたクリップは下にあるものを上書きします。置くときに Alt で挿入',+ magnet: 'メイントラックマグネット',+ magnetOn: 'オン:メイントラック(いちばん下の映像トラック)は常に隙間なく詰まります。置いたクリップは挿入、削除で隙間を詰め、トリムはリップル。ほかのトラックではクリップが重なりません:ほかのクリップの位置に置くと空いているトラックへ移り、削除で隙間が残ります。置くときに Alt で逆',+ magnetOff: 'オフ:メイントラックもほかと同じです。置いたクリップは下にあるものを上書きします。置くときに Alt で挿入',+ linkage: '連動',+ linkageOn: 'オン:メイントラックのクリップが動くと、その上で始まるテロップ、B-roll、音声も一緒に動きます。いくつものショットにまたがる長いクリップ(BGM など)はそのままです',+ linkageOff: 'オフ:メイントラックの編集はメイントラックだけを動かします',sync: '同期ロック',- syncOn: 'オン:リップルはロックされていない全トラックを動かし、音声や B-roll の同期を保ちます',+ syncOn: 'オン(Premiere と同じ):どのトラックのリップルも、ロックされていない全トラックを動かします。全トラックに余裕がある範囲で',syncOff: 'オフ:リップルはクリップのあるトラックだけを動かします',linked: 'リンクされたクリップ',linkedOn: 'オン:ビデオと切り離したオーディオを一緒に選択・編集します。Alt クリックで一つだけ',linkedOff: 'オフ:リンクされたクリップを一つずつ選択・編集します',rippleShort: '他のトラックのクリップが邪魔をしています:同期を保つため {s} 秒の隙間が残りました。このトラックだけ詰めるには同期ロックをオフにしてください。',+ gapClosedAlone: '他のトラックのクリップが邪魔をしていたため、隙間はこのトラックだけで詰めました。',menuCloseGap: '隙間を詰める',menuRippleStart: '再生ヘッドまで先頭をリップルトリム',menuRippleEnd: '再生ヘッドから末尾をリップルトリム',@@ -1136,6 +1197,7 @@ export const ja: Words = {roll: 'ロール',slip: 'スリップ',slide: 'スライド',+ sourceEnd: '素材の端です',},trackLocked: 'トラックはロックされています',dropNotClip: 'この素材はタイムラインに配置できません',@@ -1219,12 +1281,9 @@ export const ja: Words = {crossfade: 'オーディオクロスフェード',remove: 'トランジションを削除',atCut: 'トランジション',- atStart: '先頭に',- atEnd: '末尾に',locked: '変更するクリップがロックされたトラックにあります',none: 'そこにカットはありません。クリップを選ぶか、再生ヘッドをカットのそばに置いてください',short: 'クリップが短すぎます',- failed: 'トランジションを追加できませんでした:{error}',mark: '{kind} · {s} 秒 — 端をドラッグして長さを変更、Delete で削除',handle: '{what}:{s} 秒 — 内側へドラッグしてフェード(⌥:このクリップだけ)',fadeTip: '{what} {s} 秒',@@ -1296,6 +1355,13 @@ export const ja: Words = {themeHint: 'ライト、ダーク、またはシステムに合わせる。',languageHint: 'OpenFilm の表示言語。',},+ playback: {+ group: "再生",+ proxies: "重い素材にプロキシを使う",+ proxiesHint: "1080p を超える素材や、デコードが重い素材(ProRes、HEVC、10 ビット)は、バックグラウンドで作る軽いコピーで再生します。書き出しには常に元の素材を使います。",+ proxySize: "プロキシのサイズ",+ proxySizeHint: "小さいほど滑らかに再生でき、大きいほどビューアで鮮明に見えます。",+ },about: {group: 'このアプリについて',check: 'アップデートを確認',diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.tsindex 75e10a3..21274b5 100644--- a/packages/openfilm/studio/ui/src/i18n/ko.ts+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts@@ -161,9 +161,10 @@ export const ko: Words = {get: '가져오기',cancel: '취소',retry: '다시 시도',- size: '{size} 받음',+ left: '약 {time} 남음',+ close: '닫기',phase: {- lookup: '저장소를 확인하는 중…',+ lookup: '파일 목록을 가져오는 중…',download: '다운로드하는 중…',checkout: '파일을 쓰는 중…',copy: '여는 중…',@@ -177,8 +178,8 @@ export const ko: Words = {noFolder: '저장소에 그 폴더가 없습니다.',noFilm: '그 폴더에는 film.html이 없어서 OpenFilm 필름이 아닙니다.',tooBig: '너무 커서 가져오기를 멈췄습니다.',- timeout: '시간이 너무 오래 걸려 멈췄습니다.',- git: '필름을 가져오려면 git이 필요합니다. git을 설치한 뒤 다시 시도하세요.',+ timeout: '한동안 아무것도 받지 못해 멈췄습니다. 인터넷 연결을 확인한 뒤 다시 시도하세요.',+ git: '비공개이거나 GitHub에 없는 저장소라 git이 필요합니다. git을 설치한 뒤 다시 시도하세요.',},},examples: {@@ -232,7 +233,7 @@ export const ko: Words = {slides: '슬라이드 및 PDF',project: '프로젝트',alpha: '투명 에셋',- nle: '편집 소프트웨어',+ nle: '편집 프로젝트',},destHint: {social: '모든 플랫폼용 사전 설정',@@ -244,7 +245,7 @@ export const ko: Words = {slides: '샷마다 슬라이드 1장',project: '프로젝트 전체를 전달',alpha: 'AE, Final Cut, 웹용 알파',- nle: 'Premiere Pro, DaVinci Resolve',+ nle: '{app}, Premiere Pro, DaVinci Resolve',},destDesc: {social: '플랫폼을 하나 이상 선택하세요. 각 플랫폼에 맞는 화면 비율, 크기, 프레임 레이트로 한 번에 내보냅니다.',@@ -256,7 +257,7 @@ export const ko: Words = {slides: '샷마다 슬라이드 1장으로 된 프레젠테이션 또는 PDF. 바로 발표하거나 인쇄할 수 있습니다.',project: '프로젝트 자체(영상, 페이지, 미디어, 선택한 부분)를 OpenFilm에서 바로 열 수 있는 zip 또는 폴더로 내보냅니다.',alpha: '배경이 투명한 비디오(영상 전체 또는 요소 하나). 내 편집, 앱, 웹사이트에 레이어로 겹쳐 쓸 수 있습니다.',- nle: '계속 편집할 수 있는 타임라인 그 자체: 편집 프로그램에서 가져올 수 있는 XML, 알파가 포함된 ProRes 4444 클립으로 된 각 페이지, 개별 트랙에 놓인 영상과 사운드.',+ nle: '계속 편집할 수 있는 타임라인 그 자체: {app} 초안 또는 편집 프로그램에서 가져올 수 있는 XML, 알파가 포함된 클립으로 된 각 페이지, 개별 트랙에 놓인 영상과 사운드.',},group: {landscape: '가로 16:9',@@ -335,6 +336,8 @@ export const ko: Words = {range: '범위',rangeAll: '영상 전체',rangePart: '일부 구간',+ rangeFrom: '시작',+ rangeTo: '끝',saveTo: '저장 위치',change: '변경…',pickTitle: '내보내기 저장 위치 선택',@@ -363,12 +366,17 @@ export const ko: Words = {},alphaScale: '크기',alphaHint: '영상이 그리는 것만 남기고 스테이지 배경은 제거됩니다. 요소가 화면 전체에 자체 배경을 칠하면 불투명하게 내보내집니다. 그 배경은 별도 클립으로 분리하세요.',- nleTitle: '편집용 XML',+ nleFor: '대상',+ nleDraftTitle: '{app} 초안',+ nleSrt: '자막 포함(SRT)',+ nleSubs: '자막 포함',+ nleHintPremiere: 'XML과 미디어 폴더가 들어 있는 폴더를 만듭니다. Premiere Pro에서: 파일 › 가져오기. 폴더를 그 자리에 두거나, 옮긴 뒤에는 미디어를 다시 연결하세요.',+ nleHintResolve: 'XML과 미디어 폴더가 들어 있는 폴더를 만듭니다. DaVinci Resolve에서: 파일 › 가져오기 › 타임라인. 폴더를 그 자리에 두거나, 옮긴 뒤에는 미디어를 다시 연결하세요.',+ nleHintDraft: '{app}의 초안 폴더에 바로 만들어서 {app} 홈 화면에 나타납니다({app}이 열려 있으면 다시 시작하세요). 페이지는 알파가 포함된 클립으로, 자막은 텍스트 트랙으로 들어갑니다.',+ nleHintDraftNone: '이 컴퓨터에서 {app}을 찾지 못했습니다. 초안은 내보내기 폴더에 만들어집니다. {app}의 초안 폴더(설정 › 초안 위치)로 옮기세요.',nleAudio: '타임라인의 사운드',nleAudioClips: '개별 클립',nleAudioStems: '믹스된 스템',- nleSrt: '자막 포함(SRT)',- nleHint: 'XML과 미디어 폴더가 들어 있는 폴더를 만듭니다. Premiere Pro: 파일 › 가져오기. DaVinci Resolve: 파일 › 가져오기 › 타임라인. 폴더를 그 자리에 두거나, 옮긴 뒤에는 미디어를 다시 연결하세요.',projectZip: 'Zip',projectZipHint: '파일 하나로, 보내거나 업로드하기 쉽습니다.',projectFolder: '폴더',@@ -490,6 +498,7 @@ export const ko: Words = {stepSlid: '{clip} 슬라이드',stepRippleTrimmed: '{clip} 리플 트림',stepGapClosed: '간격 메움',+ stepMainClosed: '메인 트랙을 메움',stepLinked: '{clip} 연결',stepUnlinked: '{clip} 연결 해제',stepSpeed: '{clip} 속도 변경',@@ -672,6 +681,8 @@ export const ko: Words = {propDimensions: '크기(픽셀)',propFps: '프레임 레이트',propModified: '수정한 날짜',+ propLinked: "보관 위치",+ propProxy: "프록시",kindAudio: '오디오',uploadFailed: '가져오기에 실패했습니다. 다시 시도하세요',unreadable: '“{name}”을(를) 가져왔지만 이미지, 비디오 또는 사운드로 읽을 수 없습니다({why}). 파일을 확인하거나 다른 사본을 가져오세요.',@@ -680,7 +691,6 @@ export const ko: Words = {media: {insertSource: "재생 헤드에 삽입",overwriteSource: "재생 헤드에 덮어쓰기",- addToTimeline: "타임라인에 추가",close: '닫기',results: '결과',moveFailed: '그곳으로 옮길 수 없습니다.',@@ -695,6 +705,7 @@ export const ko: Words = {cannotPreview: '이 파일은 여기서 미리 볼 수 없습니다.',scrub: '위치',search: '미디어 검색',+ searchShort: "검색",clearSearch: '검색 지우기',sort: '정렬',import: '미디어 가져오기',@@ -705,10 +716,10 @@ export const ko: Words = {filter_image: '이미지',filter_audio: '오디오',filter_page: '페이지',- importing: '파일 {n}개 가져오는 중… {p}%',+ filter_other: "기타",dismiss: '닫기',emptyTitle: '아직 미디어가 없습니다',- emptyBody: '비디오, 이미지, 사운드를 가져오거나 여기에 끌어다 놓으세요. 에이전트가 이 프로젝트에 저장한 것도 여기에 나타납니다.',+ emptyBody: "비디오, 이미지, 사운드 등 어떤 파일이든 가져오거나 여기에 끌어다 놓으세요. 에이전트가 이 프로젝트에 저장한 것도 여기에 나타납니다.",noMatch: '검색과 일치하는 항목이 없습니다.',copyPath: '경로 복사',dropHint: '놓으면 이 프로젝트로 가져옵니다',@@ -716,6 +727,36 @@ export const ko: Words = {sort_time: '수정한 날짜',sort_duration: '길이',sort_type: '유형',+ moveTo: "이동",+ moveHere: "이미 여기에 있습니다",+ deleteMany: "항목 {n}개 삭제",+ deleteManyTitle: "항목 {n}개를 삭제할까요?",+ deleteManyConfirm: "휴지통으로 옮겨지며, 휴지통에서 되살릴 수 있습니다.",+ deleteManyAlsoClip: "휴지통으로 옮겨지며, 휴지통에서 되살릴 수 있습니다. 타임라인에서 이 중 하나를 사용하는 클립도 제거됩니다.",+ deleteManyAlsoClips: "휴지통으로 옮겨지며, 휴지통에서 되살릴 수 있습니다. 타임라인에서 이 항목들을 사용하는 클립 {n}개도 제거됩니다.",+ importFiles: "파일 가져오기…",+ importFilesNote: "프로젝트에 사본을 넣습니다",+ linkFiles: "파일 연결…",+ linkFilesNote: "NAS나 다른 디스크 등 원래 위치에 그대로 둡니다",+ linkFolder: "폴더 연결…",+ pickImport: "가져올 파일 선택",+ pickLink: "연결할 파일 선택",+ pickLinkFolder: "연결할 폴더 선택",+ pickRelink: "지금 어디에 있나요?",+ noDialog: "이 시스템에는 Studio가 열 수 있는 파일 대화상자가 없습니다. 파일을 여기에 끌어다 놓으세요.",+ revealOriginal: "원본 보기",+ relink: "다시 연결…",+ relinkFailed: "그곳에 연결할 수 없습니다",+ collect: "프로젝트로 복사",+ collectNote: "원본은 그대로 남습니다",+ collectFailed: "프로젝트로 복사할 수 없습니다",+ linkMissing: "찾을 수 없음",+ linkedFrom: "{path}에서 연결됨",+ proxy: "프록시",+ proxyMaking: "프록시 만드는 중… {p}%",+ proxyWaiting: "프록시 대기 중",+ proxyFailed: "프록시를 만들 수 없어 원본으로 재생합니다",+ proxyReady: "준비됨: 뷰어에서 재생합니다",},assetsPane: {show: '에셋 표시',@@ -826,8 +867,9 @@ export const ko: Words = {at: '시작',duration: '길이',inPoint: '시작 지점',+ inPointWhole: '클립이 파일 전체를 재생하고 있습니다. 시작 지점을 옮기려면 먼저 줄이세요.',speed: '속도',- speedLimit: '{n}×보다 느리면 다음 클립과 겹칩니다. 타임라인의 자석을 켜면 뒤로 밀어냅니다.',+ speedLimit: '{n}×보다 느리면 다음 클립과 겹칩니다. 메인 트랙에서는 타임라인의 메인 트랙 자석이 뒤로 밀어냅니다.',speedTooSlow: '{n}×보다 느리면 같은 트랙의 다음 클립과 겹칩니다.',sound: '사운드',gainDb: '볼륨',@@ -929,12 +971,27 @@ export const ko: Words = {effectAdd: '효과 추가',effectRemove: '제거',effectCustom: '직접 작성됨, "고급" 참고',- effectsNone: '아직 없음: +로 그림자, 테두리, 가장자리 페이드를 추가하세요.',+ effectsNone: '아직 없음: +로 그림자, 흐림, 가장자리 페이드를 추가하세요.',shadowX: '그림자 X',shadowY: '그림자 Y',shadowBlur: '그림자 흐림',shadowColor: '그림자 색',stroke: '테두리',+ strokeAdd: '테두리 추가',+ strokePosition: '테두리 위치',+ strokePositions: { inside: '안쪽', center: '가운데', outside: '바깥쪽' },+ strokeCut: '자르기, 마스크, 가장자리 페이드는 가장자리 바깥에 그려진 테두리를 잘라냅니다. 모두 보이려면 안쪽을 고르세요.',+ fillAdd: '채우기 추가',+ fillRemove: '채우기 제거',+ innerShadow: '내부 그림자',+ layerBlur: '레이어 흐림',+ backgroundBlur: '배경 흐림',+ shadowSpread: '퍼짐',+ cornersEach: '모서리 개별 설정',+ cornersCropped: '자르기는 모든 모서리를 같게 둥글립니다',+ corners: { 'top-left': '왼쪽 위', 'top-right': '오른쪽 위', 'bottom-right': '오른쪽 아래', 'bottom-left': '왼쪽 아래' },+ textDecoration: '장식',+ decorations: { none: '없음', underline: '밑줄', lineThrough: '취소선' },strokeWidth: '테두리 두께',strokeStyle: '테두리 모양',strokeColor: '테두리 색',@@ -1112,18 +1169,22 @@ export const ko: Words = {zoomFit: '너비에 맞추기',zoom: '확대/축소',snap: '스냅',- snapOn: '켬: 가장자리, 재생 헤드, 단어에 스냅합니다',+ snapOn: '켬: 클립 가장자리, 재생 헤드, 마커에 스냅합니다',snapOff: '끔: 손을 놓은 정확한 위치에 놓입니다',- magnet: '자석',- magnetOn: '켬: 놓은 클립은 삽입되어 뒤를 밀어내고, 삭제하면 간격이 메워지며, 트림은 리플됩니다. 놓을 때 Alt로 덮어쓰기',- magnetOff: '끔: 놓은 클립이 아래 클립을 덮어씁니다. 놓을 때 Alt로 삽입',+ magnet: '메인 트랙 자석',+ magnetOn: '켬: 메인 트랙(가장 아래 화면 트랙)은 항상 빈틈없이 붙어 있습니다. 놓은 클립은 삽입되고, 삭제하면 간격이 메워지며, 트림은 리플됩니다. 다른 트랙에서는 클립이 겹치지 않습니다: 다른 클립 자리에 놓으면 빈 트랙으로 옮겨지고, 삭제하면 간격이 남습니다. 놓을 때 Alt로 반대로',+ magnetOff: '끔: 메인 트랙도 다른 트랙과 같습니다. 놓은 클립이 아래 클립을 덮어씁니다. 놓을 때 Alt로 삽입',+ linkage: '연동',+ linkageOn: '켬: 메인 트랙의 클립이 움직이면, 그 위에서 시작하는 자막, B-roll, 소리도 함께 움직입니다. 여러 샷에 걸친 긴 클립(배경음악 등)은 그대로 있습니다',+ linkageOff: '끔: 메인 트랙 편집은 메인 트랙만 움직입니다',sync: '동기 잠금',- syncOn: '켬: 리플이 잠기지 않은 모든 트랙을 함께 움직여 소리와 B-roll의 동기를 유지합니다',+ syncOn: '켬(Premiere와 같음): 어느 트랙의 리플이든 잠기지 않은 모든 트랙을 함께 움직입니다. 모든 트랙에 공간이 있는 만큼',syncOff: '끔: 리플이 클립이 있는 트랙만 움직입니다',linked: '연결된 클립',linkedOn: '켬: 비디오와 분리한 오디오를 함께 선택하고 편집합니다. Alt 클릭으로 하나만',linkedOff: '끔: 연결된 클립을 하나씩 선택하고 편집합니다',rippleShort: '다른 트랙의 클립이 막고 있습니다: 동기를 유지하려고 {s}초 간격이 남았습니다. 이 트랙만 메우려면 동기 잠금을 끄세요.',+ gapClosedAlone: '다른 트랙의 클립이 막고 있어 이 트랙에서만 간격을 메웠습니다.',menuCloseGap: '간격 메우기',menuRippleStart: '재생 헤드까지 시작 리플 트림',menuRippleEnd: '재생 헤드부터 끝 리플 트림',@@ -1136,6 +1197,7 @@ export const ko: Words = {roll: '롤',slip: '슬립',slide: '슬라이드',+ sourceEnd: '소스의 끝입니다',},trackLocked: '트랙 잠김',dropNotClip: '이 에셋은 타임라인에 놓을 수 없습니다',@@ -1219,12 +1281,9 @@ export const ko: Words = {crossfade: '오디오 크로스페이드',remove: '전환 효과 제거',atCut: '전환 효과',- atStart: '시작 부분에',- atEnd: '끝 부분에',locked: '바꿀 클립이 잠긴 트랙에 있습니다',none: '그곳에는 컷이 없습니다. 클립을 선택하거나 재생 헤드를 컷 옆에 두세요',short: '클립이 너무 짧습니다',- failed: '전환 효과를 만들 수 없습니다: {error}',mark: '{kind} · {s}초 — 가장자리를 끌어 길이 변경, Delete로 제거',handle: '{what}: {s}초 — 안쪽으로 끌어 페이드 (⌥: 이 클립만)',fadeTip: '{what} {s}초',@@ -1295,6 +1354,13 @@ export const ko: Words = {themeHint: '라이트, 다크 또는 시스템 설정을 따릅니다.',languageHint: 'OpenFilm 화면에 표시되는 언어.',},+ playback: {+ group: "재생",+ proxies: "무거운 영상에 프록시 사용",+ proxiesHint: "1080p를 넘거나 디코딩이 무거운(ProRes, HEVC, 10비트) 영상은 백그라운드에서 만든 가벼운 사본으로 재생합니다. 내보내기에는 항상 원본을 씁니다.",+ proxySize: "프록시 크기",+ proxySizeHint: "작을수록 더 부드럽게 재생되고, 클수록 뷰어에서 더 선명합니다.",+ },about: {group: '정보',check: '업데이트 확인',diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.tsindex 942b3c0..0fd800d 100644--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts@@ -162,9 +162,10 @@ export const zhCN: Words = {get: '获取',cancel: '取消',retry: '重试',- size: '已下载 {size}',+ left: '还剩约 {time}',+ close: '关闭',phase: {- lookup: '正在查找仓库…',+ lookup: '正在获取文件列表…',download: '正在下载…',checkout: '正在写入文件…',copy: '正在打开…',@@ -178,8 +179,8 @@ export const zhCN: Words = {noFolder: '仓库中没有这个文件夹。',noFilm: '这个文件夹里没有 film.html,它不是 OpenFilm 影片。',tooBig: '内容太大,已停止获取。',- timeout: '用时太长,已停止。',- git: 'Studio 需要 git 才能获取影片。请安装 git 后重试。',+ timeout: '一段时间内没有收到任何数据,已停止。请检查网络连接后重试。',+ git: '这个仓库是私有的或不在 GitHub 上,需要 git。请安装 git 后重试。',},},examples: {@@ -233,7 +234,7 @@ export const zhCN: Words = {slides: '幻灯片与 PDF',project: '项目',alpha: '透明素材',- nle: '剪辑软件',+ nle: '剪辑工程',},destHint: {social: '覆盖各平台的预设',@@ -245,7 +246,7 @@ export const zhCN: Words = {slides: '每个镜头一页',project: '整个项目,方便传给别人',alpha: '带 Alpha 通道,用于 AE、Final Cut、网页',- nle: 'Premiere Pro、DaVinci Resolve',+ nle: '{app}、Premiere Pro、DaVinci Resolve',},destDesc: {social: '选择一个或多个平台。每个平台都会得到合适的画幅、尺寸和帧率,一次全部导出。',@@ -257,7 +258,7 @@ export const zhCN: Words = {slides: '每个镜头一页的演示文稿或 PDF——可直接演示或打印。',project: '项目本身——成片、页面、素材,以及你选择的部分——导出为 zip 或文件夹,可以直接用 OpenFilm 打开。',alpha: '透明背景的视频——整部影片或单个元素——可叠加到你自己的剪辑、应用和网站中。',- nle: '时间轴本身,可以接着剪:一个剪辑软件可导入的 XML,每个页面导出为带 Alpha 通道的 ProRes 4444 片段,你的视频素材和声音各占独立的轨道。',+ nle: '时间轴本身,可以接着剪:{app}草稿,或剪辑软件可导入的 XML。每个页面导出为带 Alpha 通道的片段,你的视频素材和声音各占独立的轨道。',},group: {landscape: '横屏 16:9',@@ -336,6 +337,8 @@ export const zhCN: Words = {range: '范围',rangeAll: '整部影片',rangePart: '部分',+ rangeFrom: '起点',+ rangeTo: '终点',saveTo: '保存到',change: '更改…',pickTitle: '选择导出的保存位置',@@ -364,12 +367,17 @@ export const zhCN: Words = {},alphaScale: '尺寸',alphaHint: '只保留影片绘制的内容,舞台背景会被去除。如果某个元素自己绘制了全屏背景,导出结果将是不透明的——请把该背景放到单独的片段上。',- nleTitle: '剪辑软件 XML',+ nleFor: '用于',+ nleDraftTitle: '{app}草稿',+ nleSrt: '包含字幕(SRT)',+ nleSubs: '包含字幕',+ nleHintPremiere: '会生成一个文件夹,内含 XML 和一个媒体文件夹。在 Premiere Pro 中:文件 › 导入。请保持文件夹位置不变,移动后需要重新链接。',+ nleHintResolve: '会生成一个文件夹,内含 XML 和一个媒体文件夹。在 DaVinci Resolve 中:文件 › 导入 › 时间线。请保持文件夹位置不变,移动后需要重新链接。',+ nleHintDraft: '直接生成到{app}的草稿文件夹,打开{app}首页就能看到({app}开着的话,重启一下)。页面是带 Alpha 通道的片段,字幕是一条文字轨道。',+ nleHintDraftNone: '这台电脑上没有找到{app}:草稿会生成在导出文件夹里,把它移到{app}的草稿文件夹(设置 › 草稿位置)即可。',nleAudio: '时间轴上的声音',nleAudioClips: '独立片段',nleAudioStems: '混合分轨',- nleSrt: '包含字幕(SRT)',- nleHint: '会生成一个文件夹,内含 XML 和一个媒体文件夹。Premiere Pro:文件 › 导入。DaVinci Resolve:文件 › 导入 › 时间线。请保持文件夹位置不变,移动后需要重新链接。',projectZip: 'Zip',projectZipHint: '一个文件,方便发送或上传。',projectFolder: '文件夹',@@ -491,6 +499,7 @@ export const zhCN: Words = {stepSlid: '滑动了 {clip}',stepRippleTrimmed: '波纹裁剪了 {clip}',stepGapClosed: '合拢了间隙',+ stepMainClosed: '合拢了主轨',stepLinked: '关联了 {clip}',stepUnlinked: '取消关联 {clip}',stepSpeed: '改了 {clip} 的速度',@@ -673,6 +682,8 @@ export const zhCN: Words = {propDimensions: '尺寸',propFps: '帧率',propModified: '修改时间',+ propLinked: "存放位置",+ propProxy: "代理",kindAudio: '音频',uploadFailed: '导入失败,请重试',unreadable: '“{name}”已导入,但无法作为图片、视频或声音读取({why})。请检查该文件,或导入另一份副本。',@@ -681,7 +692,6 @@ export const zhCN: Words = {media: {insertSource: "在播放头处插入",overwriteSource: "在播放头处覆盖",- addToTimeline: "加到时间线",close: '关闭',results: '结果',moveFailed: '无法移动到那里。',@@ -696,6 +706,7 @@ export const zhCN: Words = {cannotPreview: '此文件无法在这里预览。',scrub: '位置',search: '搜索媒体',+ searchShort: "搜索",clearSearch: '清除搜索',sort: '排序',import: '导入媒体',@@ -706,10 +717,10 @@ export const zhCN: Words = {filter_image: '图片',filter_audio: '音频',filter_page: '页面',- importing: '正在导入 {n} 个文件… {p}%',+ filter_other: "其他",dismiss: '关闭',emptyTitle: '还没有媒体',- emptyBody: '导入视频、图片或声音,或直接拖到这里。智能体在此项目中保存的任何内容也会显示在这里。',+ emptyBody: "导入视频、图片、声音或任何其他文件,或直接拖到这里。智能体在此项目中保存的任何内容也会显示在这里。",noMatch: '没有符合搜索条件的内容。',copyPath: '复制路径',dropHint: '松开即可导入到此项目',@@ -717,6 +728,36 @@ export const zhCN: Words = {sort_time: '修改日期',sort_duration: '时长',sort_type: '类型',+ moveTo: "移动到",+ moveHere: "已经在这里",+ deleteMany: "删除 {n} 项",+ deleteManyTitle: "删除这 {n} 项?",+ deleteManyConfirm: "它们会被移到废纸篓,你可以从那里找回。",+ deleteManyAlsoClip: "它们会被移到废纸篓,你可以从那里找回。时间轴上使用其中一项的片段也会被移除。",+ deleteManyAlsoClips: "它们会被移到废纸篓,你可以从那里找回。时间轴上使用它们的 {n} 个片段也会被移除。",+ importFiles: "导入文件…",+ importFilesNote: "复制一份到项目里",+ linkFiles: "链接文件…",+ linkFilesNote: "文件留在原处,比如 NAS 或其他硬盘",+ linkFolder: "链接文件夹…",+ pickImport: "选择要导入的文件",+ pickLink: "选择要链接的文件",+ pickLinkFolder: "选择要链接的文件夹",+ pickRelink: "它现在在哪里?",+ noDialog: "此系统没有 Studio 能打开的文件对话框,请直接把文件拖到这里。",+ revealOriginal: "显示原文件",+ relink: "重新链接…",+ relinkFailed: "无法链接到那里",+ collect: "复制到项目",+ collectNote: "原文件保留在原处",+ collectFailed: "无法复制到项目",+ linkMissing: "找不到",+ linkedFrom: "链接自 {path}",+ proxy: "代理",+ proxyMaking: "正在生成代理… {p}%",+ proxyWaiting: "代理排队中",+ proxyFailed: "无法生成代理,将直接播放原素材",+ proxyReady: "已就绪:预览时播放代理",},assetsPane: {show: '显示素材',@@ -827,8 +868,9 @@ export const zhCN: Words = {at: '开始',duration: '时长',inPoint: '入点',+ inPointWhole: '片段已经播放整个文件。先缩短它,才能移动入点。',speed: '速度',- speedLimit: '慢于 {n}× 会碰到后一个片段。打开时间线上的磁吸,就会把后面的片段往后推。',+ speedLimit: '慢于 {n}× 会碰到后一个片段。在主轨上,打开时间线的主轨磁吸就会把后面的片段往后推。',speedTooSlow: '慢于 {n}× 会碰到同一轨上的后一个片段。',sound: '声音',gainDb: '音量',@@ -930,12 +972,27 @@ export const zhCN: Words = {effectAdd: '添加效果',effectRemove: '移除',effectCustom: '手写,见“高级”',- effectsNone: '还没有:用 + 添加投影、描边或渐隐边缘。',+ effectsNone: '还没有:用 + 添加投影、模糊或渐隐边缘。',shadowX: '投影 X',shadowY: '投影 Y',shadowBlur: '投影模糊',shadowColor: '投影颜色',stroke: '描边',+ strokeAdd: '添加描边',+ strokePosition: '描边位置',+ strokePositions: { inside: '内部', center: '居中', outside: '外部' },+ strokeCut: '裁切、遮罩或边缘渐隐会切掉画在边外的描边,选「内部」才能完整显示。',+ fillAdd: '添加填充',+ fillRemove: '移除填充',+ innerShadow: '内阴影',+ layerBlur: '图层模糊',+ backgroundBlur: '背景模糊',+ shadowSpread: '扩展',+ cornersEach: '独立圆角',+ cornersCropped: '裁切的四个角圆角相同',+ corners: { 'top-left': '左上', 'top-right': '右上', 'bottom-right': '右下', 'bottom-left': '左下' },+ textDecoration: '装饰线',+ decorations: { none: '无', underline: '下划线', lineThrough: '删除线' },strokeWidth: '描边粗细',strokeStyle: '描边样式',strokeColor: '描边颜色',@@ -1113,18 +1170,22 @@ export const zhCN: Words = {zoomFit: '适应宽度',zoom: '缩放',snap: '吸附',- snapOn: '开:吸附到边缘、播放头和词语',+ snapOn: '开:吸附到片段边缘、播放头和标记',snapOff: '关:在松手的位置精确放置',- magnet: '磁吸',- magnetOn: '开:放下片段时插入并推开后面的片段,删除时合上空隙,裁剪时波纹。放下时按住 Alt 改为覆盖',- magnetOff: '关:放下片段时覆盖下面的片段。放下时按住 Alt 改为插入',+ magnet: '主轨磁吸',+ magnetOn: '开:主轨(最下面的画面轨)始终首尾相接。放到主轨上的片段会插入,删除时合上空隙,裁剪时波纹。其他轨道上片段不会互相覆盖:放到已有片段的位置会自动换到空闲轨,删除留空。放下时按住 Alt 反过来',+ magnetOff: '关:主轨和其他轨道一样。放下片段时覆盖下面的片段,放下时按住 Alt 改为插入',+ linkage: '联动',+ linkageOn: '开:主轨上的片段移动时,开始在它上面的字幕、画中画和声音跟着一起走。横跨好几个镜头的长片段(比如背景音乐)留在原处',+ linkageOff: '关:编辑主轨时只动主轨',sync: '同步锁定',- syncOn: '开:波纹操作会带上所有未锁定的轨道,声音和 B-roll 保持同步',+ syncOn: '开(同 Premiere):任何轨道上的波纹操作都会带上所有未锁定的轨道,只要每条轨都有空间',syncOff: '关:波纹操作只动片段所在的轨道',linked: '关联片段',linkedOn: '开:视频和分离出的音频一起选中、一起编辑。按住 Alt 点击只选一个',linkedOff: '关:关联的片段逐个选中、逐个编辑',rippleShort: '其他轨道上有片段挡着:为保持同步,留下了 {s} 秒的空隙。关掉同步锁定即可只在本轨合上。',+ gapClosedAlone: '其他轨道上有片段挡着,间隙只在本轨合上了。',menuCloseGap: '合拢间隙',menuRippleStart: '波纹裁剪开头到播放头',menuRippleEnd: '波纹裁剪结尾到播放头',@@ -1137,6 +1198,7 @@ export const zhCN: Words = {roll: '滚动',slip: '滑移',slide: '滑动',+ sourceEnd: '素材到头了',},trackLocked: '轨道已锁定',dropNotClip: '此素材不能放到时间轴上',@@ -1220,12 +1282,9 @@ export const zhCN: Words = {crossfade: '音频交叉淡化',remove: '移除转场',atCut: '转场',- atStart: '在开头',- atEnd: '在结尾',locked: '要改动的片段在锁定的轨道上',none: '这里没有剪切点:请选中一个片段,或把播放头放在剪切点旁',short: '片段太短,放不下',- failed: '无法添加转场:{error}',mark: '{kind} · {s} 秒 — 拖动边缘调整时长;按 Delete 移除',handle: '{what}:{s} 秒 — 向内拖动来淡化(⌥:只改这个片段)',fadeTip: '{what} {s} 秒',@@ -1297,6 +1356,13 @@ export const zhCN: Words = {themeHint: '浅色、深色,或跟随系统。',languageHint: 'OpenFilm 界面使用的语言。',},+ playback: {+ group: "播放",+ proxies: "为大体积素材生成代理",+ proxiesHint: "超过 1080p 或解码较慢(ProRes、HEVC、10 位)的素材,会在后台生成一份轻量副本用于预览播放。导出始终使用原素材。",+ proxySize: "代理分辨率",+ proxySizeHint: "越小播放越流畅,越大预览越清晰。",+ },about: {group: '关于',check: '检查更新',diff --git a/packages/openfilm/studio/ui/src/lib/asset-timeline.test.ts b/packages/openfilm/studio/ui/src/lib/asset-timeline.test.tsindex 7b9929b..bebccfe 100644--- a/packages/openfilm/studio/ui/src/lib/asset-timeline.test.ts+++ b/packages/openfilm/studio/ui/src/lib/asset-timeline.test.ts@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { assetDropInsert, assetDropSpot, assetDropTargetOf, assetRunInsert, soundLaneHit } from './asset-timeline.ts';+import { assetClipElement, assetDropInsert, assetDropSpot, assetDropTargetOf, assetFitBox, assetPageFit, assetRunInsert, soundLaneHit } from './asset-timeline.ts';import type { TimelineTrack } from './timeline-layout.ts';/* A file from the media pane lands on the row under the pointer — a track has no kind (SPEC) — or, where its time@@ -98,3 +98,41 @@ test('a drop snapped onto a clip end that is not on a frame lands on it, not a fconst plan = assetDropInsert({ path: 'assets/a.mp4', kind: 'video' }, tracks, { lane: null, insertTrackAt: null }, 11_011);assert.equal('at' in plan && plan.at, 11.011);});++test('a picture of another shape than the canvas lands in its own shape, as large as fits, centered', () => {+ const stage = { w: 1080, h: 1440 };+ /* a square still on a 3:4 canvas: as wide as the canvas, centered top to bottom */+ assert.deepEqual(assetFitBox({ w: 800, h: 800 }, stage), { x: 0, y: 180, w: 1080, h: 1080 });+ /* a 16:9 video on a 9:16 canvas, and a portrait one on 16:9: one side meets the edge */+ assert.deepEqual(assetFitBox({ w: 1920, h: 1080 }, { w: 1080, h: 1920 }), { x: 0, y: 656, w: 1080, h: 608 });+ assert.deepEqual(assetFitBox({ w: 1080, h: 1920 }, { w: 1920, h: 1080 }), { x: 656, y: 0, w: 608, h: 1080 });+ /* the canvas's shape (to the px), or a size not known yet: no box, it fills the canvas as it always did */+ assert.equal(assetFitBox({ w: 3840, h: 2160 }, { w: 1920, h: 1080 }), null);+ assert.equal(assetFitBox({ w: 1921, h: 1080 }, { w: 1920, h: 1080 }), null);+ assert.equal(assetFitBox({}, stage), null);+ assert.equal(assetFitBox({ w: 800, h: 800 }, null), null);+});++test('the clip written for a dropped file: a box for a still or video of another shape, never for a sound or a page', () => {+ const stage = { w: 1920, h: 1080 };+ assert.deepEqual(assetClipElement({ path: 'assets/a.png', kind: 'image', w: 1000, h: 1000 }, stage), { src: 'assets/a.png', time: [0, 4], box: { x: 420, y: 0, w: 1080, h: 1080 } });+ assert.deepEqual(assetClipElement({ path: 'assets/a.mp4', kind: 'video', w: 1920, h: 1080 }, stage), { src: 'assets/a.mp4' });+ assert.deepEqual(assetClipElement({ path: 'assets/a.mp3', kind: 'audio', w: 500, h: 500 }, stage), { src: 'assets/a.mp3' });+ assert.deepEqual(assetClipElement({ path: 'scenes/a.html', kind: 'mg', w: 500, h: 500 }, stage), { src: 'scenes/a.html' });+ /* the drop and a run of files from the computer carry it through */+ const plan = assetDropInsert({ path: 'assets/a.png', kind: 'image', w: 1000, h: 1000 }, tracks, { lane: null, insertTrackAt: 0 }, 0, stage);+ assert.ok(!('error' in plan) && (plan.element.box as { w: number }).w === 1080);+ const run = assetRunInsert([{ path: 'assets/a.png', kind: 'image', w: 1000, h: 1000 }], tracks, null, 0, undefined, stage);+ assert.ok('inserts' in run && (run.inserts[0]!.element.box as { x: number }).x === 420);+});++test('a page without a size of its own keeps the size it is shown at alone, scaled whole into the canvas', () => {+ const page = { path: 'scenes/cards.html', kind: 'mg' as const, reflows: true, w: 1920, h: 1080 };+ /* on 21:9 it stays 16:9, as high as the canvas, centered; it is not laid out again at 21:9 */+ assert.deepEqual(assetClipElement(page, { w: 2520, h: 1080 }), { src: 'scenes/cards.html', box: { x: 300, y: 0, w: 1920, h: 1080 }, size: { w: 1920, h: 1080 } });+ /* on 4K it is scaled up whole, not laid out at 3840 px */+ assert.deepEqual(assetPageFit(page, { w: 3840, h: 2160 }), { size: { w: 1920, h: 1080 }, box: { x: 0, y: 0, w: 3840, h: 2160 } });+ /* on its own size, or for a page that sets its size (it is its own size already): nothing */+ assert.deepEqual(assetClipElement(page, { w: 1920, h: 1080 }), { src: 'scenes/cards.html' });+ assert.equal(assetPageFit({ w: 480, h: 320 }, { w: 2520, h: 1080 }), null);+});diff --git a/packages/openfilm/studio/ui/src/lib/asset-timeline.ts b/packages/openfilm/studio/ui/src/lib/asset-timeline.tsindex afc64ac..7fbf7c7 100644--- a/packages/openfilm/studio/ui/src/lib/asset-timeline.ts+++ b/packages/openfilm/studio/ui/src/lib/asset-timeline.ts@@ -10,7 +10,7 @@* whatever is there: an insert pushes it on, an overwrite cuts it out (lib/timeline-edit planRoom), and only the empty* space above or below the tracks opens a new one. Without one, a taken spot opens a new track, shown by a line.*/-import { filmAudioRoleOf, filmSrcIsPage, filmSrcIsStill } from './film.ts';+import { filmAudioRoleOf, filmSrcIsPage, filmSrcIsStill, type FilmBox } from './film.ts';import type { ResourceDragItem } from './resource-drag';import { exactRate, frameMs, timecodeFps } from './timecode.ts';@@ -57,16 +57,59 @@ export function dropDurMsOf(file: { path: string; kind: string; durationMs?: numreturn Math.max(MIN_BLOCK_MS, 1000);}+/** The film's canvas, in px. */+export type StageSize = { w: number; h: number };++/**+ * Where a dropped video or still sits: in its own shape, as large as the canvas holds, centered, so one side meets the+ * canvas's edge (as CapCut places it). Without a box it would be the whole canvas with the picture letterboxed inside+ * it, and the box a person picks would not be the picture. None when its shape is the canvas's, or not known yet.+ */+export function assetFitBox(file: { w?: number | undefined; h?: number | undefined }, stage: StageSize | null | undefined): FilmBox | null {+ if (!stage || !(stage.w > 0 && stage.h > 0) || !(file.w && file.w > 0 && file.h && file.h > 0)) return null;+ const k = Math.min(stage.w / file.w, stage.h / file.h);+ const w = Math.min(stage.w, Math.round(file.w * k));+ const h = Math.min(stage.h, Math.round(file.h * k));+ /* within 2 px of the canvas each way is its shape: the clip fills it as it is */+ if (stage.w - w <= 2 && stage.h - h <= 2) return null;+ return { x: Math.round((stage.w - w) / 2), y: Math.round((stage.h - h) / 2), w, h };+}++/**+ * A dropped page that sets no size of its own, on a canvas of another size: kept at the size it is shown at alone+ * (`size`, 1920 × 1080), scaled whole into the canvas and centered, as a picture is. Left to itself it would be laid+ * out again at the canvas's size, so a 16:9 page would turn 21:9 on a 21:9 canvas. Null on a canvas of its size.+ */+export function assetPageFit(+ file: { reflows?: boolean | undefined; w?: number | undefined; h?: number | undefined },+ stage: StageSize | null | undefined,+): { size: StageSize; box: FilmBox } | null {+ if (!file.reflows || !stage || !(stage.w > 0 && stage.h > 0) || !(file.w && file.w > 0 && file.h && file.h > 0)) return null;+ if (file.w === stage.w && file.h === stage.h) return null;+ const size = { w: file.w, h: file.h };+ return { size, box: assetFitBox(size, stage) ?? { x: 0, y: 0, w: stage.w, h: stage.h } };+}+/**- * The file as a film.html clip: just `src` (its kind is the track it lands on, see assetDropInsert); a still, or a page- * without a duration, also gets `time`, which is its length, not a trim.+ * The file as a film.html clip: `src` (its kind is the track it lands on, see assetDropInsert); a still, or a page+ * without a duration, also gets `time`, which is its length, not a trim. A video or still of another shape than the+ * canvas gets a box in its own shape (assetFitBox), a page without a size of its own its size and box (assetPageFit).*/-export function assetClipElement(file: Pick<ResourceDragItem, 'path' | 'kind' | 'endless'>): Record<string, unknown> | null {+export function assetClipElement(+ file: Pick<ResourceDragItem, 'path' | 'kind' | 'endless' | 'reflows'> & { w?: number | undefined; h?: number | undefined },+ stage?: StageSize | null,+): Record<string, unknown> | null {const kind = assetClipKindOf(file);if (!kind) return null;const src = file.path;- if (!isEndless(file)) return { src };- return { src, time: [0, STILL_DROP_MS / 1000] };+ const box = kind === 'video' ? assetFitBox(file, stage) : null;+ const page = kind === 'mg' ? assetPageFit(file, stage) : null;+ return {+ src,+ ...(isEndless(file) ? { time: [0, STILL_DROP_MS / 1000] } : {}),+ ...(box ? { box } : {}),+ ...(page ? { box: page.box, size: page.size } : {}),+ };}/** The clip's color and row height: sounds as voice / sfx / music by path. */@@ -176,12 +219,13 @@ export type AssetDropPlan =* answer, no track is named and the insert finds one of the kind.*/export function assetDropInsert(- file: Pick<ResourceDragItem, 'path' | 'kind'>,+ file: Pick<ResourceDragItem, 'path' | 'kind' | 'endless' | 'reflows' | 'w' | 'h'>,tracks: readonly TimelineTrack[],target: AssetDropTarget,atMs: number,+ stage?: StageSize | null,): AssetDropPlan {- const element = assetClipElement(file);+ const element = assetClipElement(file, stage);if (!element) return { error: 'not-clip' };const kind = assetClipKindOf(file)!;/* where it was dropped: on the frame grid, or on the edge it snapped to (the timeline decides, see its dropAt) */@@ -205,17 +249,18 @@ export type AssetRunInsert = { element: Record<string, unknown>; at: number; dur* document) are left out; none left is `not-clip`.*/export function assetRunInsert(- files: readonly Pick<ResourceDragItem, 'path' | 'kind' | 'durationMs' | 'endless'>[],+ files: readonly Pick<ResourceDragItem, 'path' | 'kind' | 'durationMs' | 'endless' | 'reflows' | 'w' | 'h'>[],tracks: readonly TimelineTrack[],hit: AssetLaneHit | null,atMs: number,edit?: EditMode,+ stage?: StageSize | null,): { inserts: AssetRunInsert[] } | { error: 'not-clip' | 'locked' } {const usable = files.filter((f) => assetClipElement(f));if (!usable.length) return { error: 'not-clip' };const lengths = usable.map(dropDurMsOf);const whole = { path: usable[0]!.path, kind: usable[0]!.kind, durationMs: lengths.reduce((a, b) => a + b, 0) + lengths.length * frameMs(1) };- const first = assetDropInsert(usable[0]!, tracks, assetDropTargetOf(assetDropSpot(whole, tracks, hit, atMs, edit)), atMs);+ const first = assetDropInsert(usable[0]!, tracks, assetDropTargetOf(assetDropSpot(whole, tracks, hit, atMs, edit)), atMs, stage);if ('error' in first) return first;/* after the first: the track it went onto (a new one is at the index it was opened at) */const then = typeof first.track === 'object' ? first.track.insert : first.track;@@ -223,7 +268,7 @@ export function assetRunInsert(let startMs = Math.max(0, Math.round(atMs));usable.forEach((file, i) => {const track = i === 0 ? first.track : then;- inserts.push({ element: assetClipElement(file)!, at: Math.round(startMs) / 1000, durMs: lengths[i]!, ...(track != null ? { track } : {}) });+ inserts.push({ element: assetClipElement(file, stage)!, at: Math.round(startMs) / 1000, durMs: lengths[i]!, ...(track != null ? { track } : {}) });/* the next one on the first whole frame past this one's end: rounded to the nearest, it could start inside it */startMs = frameMs(Math.ceil(((startMs + lengths[i]!) * exactRate(timecodeFps())) / 1000 - 1e-6));});diff --git a/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts b/packages/openfilm/studio/ui/src/lib/canvas-fit.test.tsindex adbc578..c3a950e 100644--- a/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts+++ b/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts@@ -1,55 +1,60 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { canvasFor, fitToCanvas } from './canvas-fit.ts';+import { canvasFor, canvasSide, fitToCanvas } from './canvas-fit.ts';++const wide = { w: 1920, h: 1080 }, tall = { w: 1080, h: 1440 }, cinema = { w: 2538, h: 1080 };+const boxOf = (out: ReturnType<typeof fitToCanvas>, id: string) => out.find((c) => c.id === id)?.box;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 });+ assert.deepEqual(canvasFor(wide, '3:4'), tall);+ assert.deepEqual(canvasFor(wide, '9:16'), { w: 1080, h: 1920 });+ assert.deepEqual(canvasFor({ w: 1080, h: 1920 }, '16:9'), wide);+ assert.deepEqual(canvasFor(wide, '2.35:1'), cinema);});-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 };+test('each picture is fitted to the new canvas on its own, as CapCut does: a full-frame video, a portrait photo, a title', () => {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: 'v', kind: 'video', own: wide, box: { x: 0, y: 0, w: 1920, h: 1080 } },+ /* a 3:4 photo on another clip, filling the height in the middle */+ { id: 'p', kind: 'still', own: { w: 810, h: 1080 }, box: { x: 555, y: 0, w: 810, h: 1080 } },+ /* a title a fifth of the width, at the top center */+ { id: 't', kind: 'still', own: { w: 400, h: 200 }, box: { x: 760, y: 0, w: 384, h: 192 } },{ 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);+ /* a video without a box is the canvas in any shape: left as it is */+ { id: 'free', kind: 'video', own: wide },+ ], wide, tall);+ /* the video fills the width; the photo fills the width too (its fitted size there), not shrunk by the video */+ assert.deepEqual(boxOf(out, 'v'), { x: 0, y: 416, w: 1080, h: 608 });+ assert.deepEqual(boxOf(out, 'p'), { x: 0, y: 0, w: 1080, h: 1440 });+ /* the title: a fifth of its fitted width, its center as far up the canvas as it was */+ assert.deepEqual(boxOf(out, 't'), { x: 428, y: 74, w: 216, h: 108 });+ assert.equal(out.some((c) => c.id === 's' || c.id === 'free'), false);+});++test('shapes picked one after another never shrink a picture: 16:9 → 3:4 → 2.35:1 → 16:9 is the whole frame again', () => {+ const video = (box: object) => [{ id: 'v', kind: 'video' as const, own: wide, box: box as never }];+ const first = boxOf(fitToCanvas(video({ x: 0, y: 0, w: 1920, h: 1080 }), wide, tall), 'v');+ assert.deepEqual(first, { x: 0, y: 416, w: 1080, h: 608 });+ const second = boxOf(fitToCanvas(video(first!), tall, cinema), 'v');+ assert.deepEqual(second, { x: 309, y: 0, w: 1920, h: 1080 });+ assert.deepEqual(boxOf(fitToCanvas(video(second!), cinema, wide), 'v'), { x: 0, y: 0, w: 1920, h: 1080 });});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: 'free', kind: 'page', own: wide, 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 } });+ ], wide, tall);+ assert.deepEqual(out.find((c) => c.id === 'free'), { id: 'free', box: { x: 0, y: 416, w: 1080, h: 608 }, size: wide });assert.equal(out.find((c) => c.id === 'sized')?.size, undefined);assert.equal(out.find((c) => c.id === 'given')?.size, undefined);});-test('shapes picked one after another never shrink the film: what it shows is fitted to each canvas, an edge met', () => {- const clip = (box?: { x: number; y: number; w: number; h: number }) => [{ id: 'v', kind: 'video' as const, own: { w: 1920, h: 1080 }, box }];- const wide = { w: 1920, h: 1080 }, tall = { w: 1080, h: 1440 }, cinema = { w: 2538, h: 1080 };- const first = fitToCanvas(clip(), wide, tall)[0].box;- assert.deepEqual(first, { x: 0, y: 416, w: 1080, h: 608 });- /* 3:4 → 2.35:1: the 16:9 picture fills the height, centered (not 3:4's small picture made smaller) */- const second = fitToCanvas(clip(first as never), tall, cinema)[0].box;- assert.deepEqual(second, { x: 310, y: 0, w: 1918, h: 1080 });- /* back to 16:9: the whole frame again */- const third = fitToCanvas(clip(second as never), cinema, wide)[0].box;- assert.deepEqual(third, { x: 0, y: 0, w: 1920, h: 1080 });-});--test('a film already shrunk in its canvas is fitted out to the edge on the next shape; a title alone fills it too', () => {- const small = fitToCanvas([{ id: 'v', kind: 'video', own: { w: 1920, h: 1080 }, box: { x: 1000, y: 400, w: 540, h: 304 } }], { w: 2538, h: 1080 }, { w: 1920, h: 1080 });- assert.deepEqual(small[0].box, { x: 0, y: 0, w: 1920, h: 1080 });- const title = fitToCanvas([{ id: 't', kind: 'still', own: { w: 400, h: 200 }, box: { x: 760, y: 440, w: 400, h: 200 } }], { w: 1920, h: 1080 }, { w: 1080, h: 1440 });- assert.deepEqual(title[0].box, { x: 0, y: 450, w: 1080, h: 540 });+test('a canvas side typed or dragged stays in reason: 16 to 8192 px, even, at most 4 times the other side', () => {+ assert.equal(canvasSide(1987, 1080), 1988);+ assert.equal(canvasSide(1, 1080), 270);+ assert.equal(canvasSide(300000, 1080), 4320);+ assert.equal(canvasSide(9000, 4000), 8192);+ assert.equal(canvasSide(2, 40), 16);});diff --git a/packages/openfilm/studio/ui/src/lib/canvas-fit.ts b/packages/openfilm/studio/ui/src/lib/canvas-fit.tsindex 370aca8..a457b5b 100644--- a/packages/openfilm/studio/ui/src/lib/canvas-fit.ts+++ b/packages/openfilm/studio/ui/src/lib/canvas-fit.ts@@ -1,12 +1,14 @@/**- * 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 what the film shows is scaled whole into it, centered, as large- * as fits: the part of the old canvas its pictures cover is fitted to the new canvas, so at least one side of it meets- * the canvas's edge. It is worked out from where the pictures are, not from the old canvas, so shapes picked one after- * another never shrink the film further. 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.+ * A film's canvas changing shape, as 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 each picture is fitted to it on its own. A picture's place is read as+ * CapCut keeps it: its size as a share of the size that fits it whole in the canvas (1: it meets the canvas's edges+ * one way), and its center as a share of the canvas from the canvas's center. Both are kept, so a full-frame video+ * stays full-frame in any shape, a portrait photo on another clip fits by its own height, a title halfway up stays+ * halfway up, and shapes picked one after another never shrink anything.+ *+ * A video or still without a box is the canvas whatever its shape (its picture fitted inside by CSS): it is left+ * without one. A page is written its box. 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';@@ -17,6 +19,20 @@ 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));+/** A canvas's sides, in px, and how far from square it may be (as a ratio typed for an export: 1:4 to 4:1). */+export const CANVAS_SIDE = { min: 16, max: 8192 } as const;+const CANVAS_STRETCH = 4;++/**+ * A canvas `side` (its width or height) of `n` px, the other side kept: whole even px within CANVAS_SIDE, and no more+ * than 4 times the other side or less than a quarter of it.+ */+export function canvasSide(n: number, other: number): number {+ const lo = Math.max(CANVAS_SIDE.min, other / CANVAS_STRETCH);+ const hi = Math.min(CANVAS_SIDE.max, other * CANVAS_STRETCH);+ return Math.min(Math.floor(hi / 2) * 2, Math.max(Math.ceil(lo / 2) * 2, 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);@@ -34,47 +50,39 @@ export interface CanvasClip { id: string; kind: FilmSrcKind | null; own?: Size |/** 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 }-type Rect = { x: number; y: number; w: number; h: number; r: number };--/** The upright rectangle around a picture as drawn (turned about its center by `r` degrees). */-function bounds(at: Rect) {- const t = (at.r * Math.PI) / 180;- const w = Math.abs(at.w * Math.cos(t)) + Math.abs(at.h * Math.sin(t));- const h = Math.abs(at.w * Math.sin(t)) + Math.abs(at.h * Math.cos(t));- const cx = at.x + at.w / 2, cy = at.y + at.h / 2;- return { x0: cx - w / 2, y0: cy - h / 2, x1: cx + w / 2, y1: cy + h / 2 };-}+/** The size of a picture shaped `ratio` (width / height) that fits whole in `canvas`, meeting its edges one way. */+const fitted = (ratio: number, canvas: Size): Size => (+ canvas.w / canvas.h > ratio ? { w: canvas.h * ratio, h: canvas.h } : { w: canvas.w, h: canvas.w / ratio }+);/**- * Each picture clip's box on the new canvas `to` (the old one is `from`): what the pictures cover of the old canvas- * (the canvas itself when they cover none of it) is scaled to fit `to` whole and centered in it. Sounds have no- * picture and are left out.+ * Each picture clip's box on the new canvas `to` (the old one is `from`), as CapCut fits each clip: the same share of+ * its fitted size, its center the same share of the canvas from the canvas's center. Sounds, and videos and stills+ * without a box (they are the canvas), are left out.*/export function fitToCanvas(clips: readonly CanvasClip[], from: Size, to: Size): CanvasFit[] {- const drawn = clips.flatMap((clip) => {- if (!clip.kind || clip.kind === 'sound') return [];+ const out: CanvasFit[] = [];+ for (const clip of clips) {+ if (!clip.kind || clip.kind === 'sound') continue;+ if (clip.kind !== 'page' && !clip.box) continue;const own = clip.own && clip.own.w > 0 && clip.own.h > 0 ? clip.own : from;- return [{ clip, at: pictureRect(clip.kind, own, from, clip.box ?? undefined) as Rect }];- });- /* what the film shows: its pictures' extent, as far as the old canvas shows it */- let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;- for (const { at } of drawn) {- const b = bounds(at);- x0 = Math.min(x0, b.x0); y0 = Math.min(y0, b.y0); x1 = Math.max(x1, b.x1); y1 = Math.max(y1, b.y1);- }- x0 = Math.max(0, x0); y0 = Math.max(0, y0); x1 = Math.min(from.w, x1); y1 = Math.min(from.h, y1);- if (!(x1 - x0 >= 1 && y1 - y0 >= 1)) { x0 = 0; y0 = 0; x1 = from.w; y1 = from.h; }- const k = Math.min(to.w / (x1 - x0), to.h / (y1 - y0));- const mx = (x0 + x1) / 2, my = (y0 + y1) / 2;- return drawn.map(({ clip, at }) => {- const w = at.w * k, h = at.h * k;- const cx = (at.x + at.w / 2 - mx) * k + to.w / 2;- const cy = (at.y + at.h / 2 - my) * k + to.h / 2;+ const at = pictureRect(clip.kind, own, from, clip.box ?? undefined);+ if (!(at.w > 0 && at.h > 0)) continue;+ /* the box's shape; its picture's own when they differ only by rounding (a box written in whole px), so shapes+ picked one after another do not drift */+ const ownRatio = own.w / own.h;+ const ratio = Math.abs(at.w / at.h / ownRatio - 1) < 0.01 ? ownRatio : at.w / at.h;+ const share = at.w / fitted(ratio, from).w;+ const fit = fitted(ratio, to);+ const w = fit.w * share, h = fit.h * share;+ const cx = to.w / 2 + ((at.x + at.w / 2 - from.w / 2) / from.w) * to.w;+ const cy = to.h / 2 + ((at.y + at.h / 2 - from.h / 2) / from.h) * to.h;/* whole px; an edge within 2 px of the canvas's meets it, so rounding never leaves a hairline of black */const near = (v: number, edge: number) => (Math.abs(v - edge) <= 2 ? edge : Math.round(v));const left = near(cx - w / 2, 0), top = near(cy - h / 2, 0);const box: FilmBox = { x: left, y: top, w: near(cx + w / 2, to.w) - left, h: near(cy + h / 2, to.h) - top };if (at.r) box.r = at.r;- return clip.kind === 'page' && clip.reflows && !clip.size ? { id: clip.id, box, size: { w: from.w, h: from.h } } : { id: clip.id, box };- });+ 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/clip-look.test.ts b/packages/openfilm/studio/ui/src/lib/clip-look.test.tsindex c25719b..85110f7 100644--- a/packages/openfilm/studio/ui/src/lib/clip-look.test.ts+++ b/packages/openfilm/studio/ui/src/lib/clip-look.test.ts@@ -2,7 +2,7 @@ import { test } from 'node:test';import assert from 'node:assert/strict';import {adjustOf, cropCss, cropForRatio, cropOf, cropRatio, declared, fadeCss, fadeOf, framingCss, framingOf, ownedDeclaration, shadowOf,- strokeCss, strokeOf, withAdjust, withDeclarations, withShadow,+ backdropBlurCss, backdropBlurOf, innerShadowCss, innerShadowOf, placedStrokeCss, placedStrokeOf, radiusCorners, strokeCss, strokeOf, withAdjust, withDeclarations, withShadow,} from './clip-look.ts';test('a clip\'s own CSS: each control writes its properties, the rest stays as it was', () => {@@ -93,3 +93,40 @@ test('what the controls say is left out of the raw CSS', () => {assert.ok(!ownedDeclaration('box-shadow', '0 8px 24px #000', none));assert.ok(ownedDeclaration('mask-image', 'linear-gradient(to right, transparent, #000 15%)', none));});++test('a stroke lies inside, across or outside the edge, as Figma\'s: an outline and its offset', () => {+ const read = (css: Record<string, string>) => (prop: string) => css[prop];+ assert.deepEqual(placedStrokeOf(read({ outline: 'rgb(255, 255, 255) solid 4px', 'outline-offset': '-4px' })), { width: 4, style: 'solid', color: 'rgb(255, 255, 255)', position: 'inside' });+ assert.equal(placedStrokeOf(read({ outline: '#fff solid 4px', 'outline-offset': '-2px' }))?.position, 'center');+ assert.equal(placedStrokeOf(read({ outline: '#fff solid 4px', 'outline-offset': '0px' }))?.position, 'outside');+ assert.equal(placedStrokeOf(read({ outline: 'rgb(0, 0, 0) none 0px' })), undefined, 'as computed with none');+ /* a stroke written before, as a border: inside, and the border goes when it is written again */+ const old = placedStrokeOf(read({ border: '2px solid #fff' }));+ assert.deepEqual(old, { width: 2, style: 'solid', color: '#fff', position: 'inside', border: true });+ assert.deepEqual(placedStrokeCss({ ...old!, position: 'outside' }, old), { outline: '2px solid #fff', 'outline-offset': null, border: null });+ assert.deepEqual(placedStrokeCss({ width: 3, style: 'dashed', color: '#f00', position: 'center' }), { outline: '3px dashed #f00', 'outline-offset': '-1.5px' });+ assert.deepEqual(placedStrokeCss(null), { outline: null, 'outline-offset': null });+});++test('an inner shadow is one inset box-shadow; a background blur is backdrop-filter: blur()', () => {+ assert.deepEqual(innerShadowOf('rgba(0, 0, 0, 0.4) 0px 4px 12px 0px inset'), { x: 0, y: 4, blur: 12, spread: 0, color: 'rgba(0, 0, 0, 0.4)' });+ assert.deepEqual(innerShadowOf('inset 2px 3px #000'), { x: 2, y: 3, blur: 0, spread: 0, color: '#000' });+ assert.equal(innerShadowOf('none'), undefined);+ assert.equal(innerShadowOf('0px 4px 12px #000'), null, 'a drop shadow is not one: the raw CSS\'s');+ assert.equal(innerShadowOf('inset 0 1px #000, 0 2px #fff'), null, 'several: the raw CSS\'s');+ assert.equal(innerShadowCss({ x: 0, y: 4, blur: 12, spread: 2, color: '#00000066' }), 'inset 0px 4px 12px 2px #00000066');+ assert.equal(backdropBlurOf('blur(8px)'), 8);+ assert.equal(backdropBlurOf('none'), undefined);+ assert.equal(backdropBlurOf('blur(8px) saturate(2)'), null);+ assert.equal(backdropBlurCss(0), null);+ assert.equal(backdropBlurCss(12.34), 'blur(12.3px)');+});++test('corners from the border-radius shorthand: one to four lengths, filled in as CSS does', () => {+ assert.deepEqual(radiusCorners(undefined), [0, 0, 0, 0]);+ assert.deepEqual(radiusCorners('20px'), [20, 20, 20, 20]);+ assert.deepEqual(radiusCorners('4px 20px'), [4, 20, 4, 20]);+ assert.deepEqual(radiusCorners('4px 20px 8px'), [4, 20, 8, 20]);+ assert.deepEqual(radiusCorners('4px 20px 20px 20px'), [4, 20, 20, 20]);+ assert.deepEqual(radiusCorners('10px 5px / 2px'), [10, 5, 10, 5]);+});diff --git a/packages/openfilm/studio/ui/src/lib/clip-look.ts b/packages/openfilm/studio/ui/src/lib/clip-look.tsindex dac0756..3686313 100644--- a/packages/openfilm/studio/ui/src/lib/clip-look.ts+++ b/packages/openfilm/studio/ui/src/lib/clip-look.ts@@ -43,6 +43,16 @@ export function pxOf(v: string | number | undefined): number | undefined {return m ? Number(m[1]) : undefined;}+/**+ * The four corners of a `border-radius` shorthand in px (top left, top right, bottom right, bottom left): 1 to 4+ * lengths, the missing ones filled in as CSS does; the vertical radii after `/` are not read.+ */+export function radiusCorners(v: string | undefined): [number, number, number, number] {+ const parts = (v ?? '0').split('/')[0]!.trim().split(/\s+/).map((w) => pxOf(w) ?? 0);+ const [tl = 0, tr = tl, br = tl, bl = tr] = parts;+ return [tl, tr, br, bl];+}+/* ───────────── crop: clip-path inset ───────────── *//** A crop: how much of each edge is cut away, in % of the box (top, right, bottom, left). */@@ -309,6 +319,86 @@ export function strokeCss(s: Stroke): string | null {return s.width > 0 ? `${round(s.width, 1)}px ${s.style} ${s.color}` : null;}+/* ───────────── stroke with a place: outline ───────────── */++/** Where a stroke lies against the edge, as Figma's: inside it, across it, or outside it. */+export type StrokePosition = 'inside' | 'center' | 'outside';+/** A stroke and where it lies; `border`: read from an older `border` (written as an outline once changed). */+export type PlacedStroke = Stroke & { position: StrokePosition; border?: true };++export const PLACED_STROKE_DEFAULT: PlacedStroke = { ...STROKE_DEFAULT, position: 'inside' };++/**+ * A picture's stroke, as Figma draws one: an `outline` (it adds nothing to the box or the layout), its+ * `outline-offset` saying where it lies (−width: inside, −width/2: across the edge, 0: outside). A `border` without an+ * outline is a stroke written before, inside the box. Undefined: none; null: one the panel cannot read.+ */+export function placedStrokeOf(read: (prop: string) => string | undefined): PlacedStroke | null | undefined {+ const outline = strokeOf(read('outline'));+ if (outline === null) return null;+ if (outline) {+ const off = pxOf(read('outline-offset') ?? '0') ?? 0;+ const position: StrokePosition = off <= -0.75 * outline.width ? 'inside' : off <= -0.25 * outline.width ? 'center' : 'outside';+ return { ...outline, position };+ }+ const border = strokeOf(read('border'));+ return border ? { ...border, position: 'inside', border: true } : border;+}++/** The CSS that draws `s` (null: none): an outline at its place; a stroke read from a border has the border taken off. */+export function placedStrokeCss(s: PlacedStroke | null, was?: PlacedStroke | null): Record<string, string | null> {+ const off = !s ? 0 : s.position === 'inside' ? -s.width : s.position === 'center' ? -s.width / 2 : 0;+ return {+ outline: s ? strokeCss(s) : null,+ 'outline-offset': s && s.width > 0 && off ? `${round(off, 1)}px` : null,+ ...(was?.border ? { border: null } : {}),+ };+}++/* ───────────── inner shadow: an inset box-shadow ───────────── */++/** A shadow cast inside the box, over its fill (Figma's inner shadow). */+export type InnerShadow = { x: number; y: number; blur: number; spread: number; color: string };++export const INNER_SHADOW_DEFAULT: InnerShadow = { x: 0, y: 4, blur: 12, spread: 0, color: '#00000066' };++/** One `inset` box-shadow: undefined when there is none, null when it is anything else (several, or not inset). */+export function innerShadowOf(boxShadow: string | undefined): InnerShadow | null | undefined {+ const s = (boxShadow ?? '').trim();+ if (!s || s === 'none') return undefined;+ let depth = 0;+ for (const ch of s) { if (ch === '(') depth += 1; else if (ch === ')') depth -= 1; else if (ch === ',' && depth === 0) return null; }+ const parts = words(s);+ if (!parts.some((w) => w.toLowerCase() === 'inset')) return null;+ const lengths: number[] = [];+ const color: string[] = [];+ for (const w of parts) {+ if (w.toLowerCase() === 'inset') continue;+ const n = pxOf(w);+ if (n != null) lengths.push(n); else color.push(w);+ }+ if (lengths.length < 2 || lengths.length > 4 || color.length > 1) return null;+ return { x: lengths[0]!, y: lengths[1]!, blur: lengths[2] ?? 0, spread: lengths[3] ?? 0, color: color[0] ?? 'currentcolor' };+}++export function innerShadowCss(s: InnerShadow | null): string | null {+ return s ? `inset ${round(s.x, 1)}px ${round(s.y, 1)}px ${round(Math.max(0, s.blur), 1)}px ${round(s.spread, 1)}px ${s.color}` : null;+}++/* ───────────── background blur: backdrop-filter ───────────── */++/** What is behind blurred (Figma's background blur): px; undefined when none, null when it is anything else. */+export function backdropBlurOf(v: string | undefined): number | null | undefined {+ const s = (v ?? '').trim();+ if (!s || s === 'none') return undefined;+ const m = /^blur\(\s*([\d.]+)px\s*\)$/i.exec(s);+ return m ? Number(m[1]) : null;+}++export function backdropBlurCss(px: number | null): string | null {+ return px != null && px > 0 ? `blur(${round(px, 1)}px)` : null;+}+/* ───────────── fade edges: mask-image ───────────── */export type FadeSide = 'top' | 'right' | 'bottom' | 'left';diff --git a/packages/openfilm/studio/ui/src/lib/clip-mask.test.ts b/packages/openfilm/studio/ui/src/lib/clip-mask.test.tsindex 7aa33e9..466861f 100644--- a/packages/openfilm/studio/ui/src/lib/clip-mask.test.ts+++ b/packages/openfilm/studio/ui/src/lib/clip-mask.test.ts@@ -166,3 +166,7 @@ test('a new shape keeps the last one\'s place, and only what it has', () => {const square = maskDefault('ellipse', BOX);assert.ok(Math.abs((square.w / 100) * 1920 - (square.h / 100) * 1080) < 1, 'as wide as high on the picture');});++test('a new mask has a hard edge, whatever its shape: feathering is the person\'s to add', () => {+ for (const shape of MASK_SHAPES) assert.equal(maskDefault(shape, BOX).feather, 0, shape);+});diff --git a/packages/openfilm/studio/ui/src/lib/clip-mask.ts b/packages/openfilm/studio/ui/src/lib/clip-mask.tsindex a7a29f1..cc0a900 100644--- a/packages/openfilm/studio/ui/src/lib/clip-mask.ts+++ b/packages/openfilm/studio/ui/src/lib/clip-mask.ts@@ -313,7 +313,8 @@ export function maskDefault(shape: MaskShape, box?: MaskBox | null, from?: Maskw: sized ? from!.w : square.w,h: sized ? from!.h : square.h,rotate: from && MASK_FIELDS[from.shape].rotate ? from.rotate : 0,- feather: from && MASK_FIELDS[from.shape].feather ? from.feather : shape === 'rect' ? 0 : 10,+ /* a hard edge until the person feathers it (CapCut's) */+ feather: from && MASK_FIELDS[from.shape].feather ? from.feather : 0,radius: from?.radius ?? 0,invert: from?.invert ?? false,};diff --git a/packages/openfilm/studio/ui/src/lib/export-jobs.ts b/packages/openfilm/studio/ui/src/lib/export-jobs.tsindex 87ff87b..58afd0c 100644--- a/packages/openfilm/studio/ui/src/lib/export-jobs.ts+++ b/packages/openfilm/studio/ui/src/lib/export-jobs.ts@@ -19,7 +19,7 @@ export type ExportRequest = { range?: [number, number]; label?: string } & (| { kind: 'subtitles'; format: 'srt' | 'vtt' | 'txt' }| (Framing & { kind: 'slides'; format: 'pptx' | 'pdf'; shortEdge: number; at?: number[] })/* for an editing program: an xmeml folder; `media: 'link'` points at the sources where they are instead of cloning them */- | { kind: 'nle'; fps: number; audio: 'clips' | 'stems'; media?: 'copy' | 'link'; subtitles: boolean }+ | { kind: 'nle'; format?: 'xml' | 'jianying' | 'capcut'; fps: number; audio: 'clips' | 'stems'; media?: 'copy' | 'link'; subtitles: boolean }/* the project itself: its work, and the parts of its .film asked; a zip of its folder, or the folder */| { kind: 'project'; parts: ProjectPart[]; as: 'zip' | 'folder' });@@ -90,7 +90,7 @@ async function call<T>(url: string, init?: RequestInit & { json?: unknown }): Pr* The project's exports, where they go by default, what this machine encodes, how many subtitle cues the film has, and* how big the project and its parts are.*/-export function listExports(projectId: string): Promise<{ exports: ExportJob[]; folder: string; can: ExportCapabilities; subtitles?: number; project?: ProjectSizes }> {+export function listExports(projectId: string): Promise<{ exports: ExportJob[]; folder: string; can: ExportCapabilities; drafts?: { jianying: boolean; capcut: boolean }; subtitles?: number; project?: ProjectSizes }> {return call(endpoint(projectId), { cache: 'no-store' });}diff --git a/packages/openfilm/studio/ui/src/lib/export-spec.test.ts b/packages/openfilm/studio/ui/src/lib/export-spec.test.tsindex 9444c52..1cdc83f 100644--- a/packages/openfilm/studio/ui/src/lib/export-spec.test.ts+++ b/packages/openfilm/studio/ui/src/lib/export-spec.test.ts@@ -57,3 +57,13 @@ test('a part of the film starts where clips start and ends where clips end, each});assert.deepEqual(rangeMarks([], 3000), { starts: [{ ms: 0, title: '' }], ends: [{ ms: 3000, title: '' }] });});++test('a frame comes out in its own shape: 16:9 around a 2:1 film is 1920 × 1080, not its rounded pixels\' 1918', () => {+ const wide = { w: 2160, h: 1080 };+ assert.deepEqual(filmFrameBox(wide, '16:9'), { ...filmFrameBox(wide, '16:9'), w: 2160, h: 1216 });+ assert.deepEqual(exportFramedDims(wide, '16:9', 'contain', 1080), { w: 1920, h: 1080 });+ assert.deepEqual(exportFramedDims(wide, '16:9', 'contain', 2160), { w: 3840, h: 2160 });+ assert.deepEqual(exportFramedDims(wide, '9:16', 'cover', 1080), { w: 1080, h: 1920 });+ assert.deepEqual(exportFramedDims(wide, '4:5', 'contain', 1080), { w: 1080, h: 1350 });+ assert.deepEqual(exportGifDims(filmFrameBox(wide, '16:9'), 640), { w: 640, h: 360 });+});diff --git a/packages/openfilm/studio/ui/src/lib/export-spec.ts b/packages/openfilm/studio/ui/src/lib/export-spec.tsindex 8b9a4e1..609121a 100644--- a/packages/openfilm/studio/ui/src/lib/export-spec.ts+++ b/packages/openfilm/studio/ui/src/lib/export-spec.ts@@ -70,9 +70,12 @@ function even(n: number): number {return Math.max(2, Math.round(n / 2) * 2);}-/** A picture's size with its short side at `shortEdge`, the box's shape kept; no side over 4096. */-export function exportDimsForShortEdge(box: { w: number; h: number }, shortEdge: number): { w: number; h: number } {- const r = box.w / Math.max(1, box.h);+/**+ * A picture's size with its short side at `shortEdge`, the box's exact shape kept (`ratio`, when it has one: a 16:9+ * frame at 1080 is 1920 × 1080); no side over 4096.+ */+export function exportDimsForShortEdge(box: { w: number; h: number; ratio?: number }, shortEdge: number): { w: number; h: number } {+ const r = box.ratio ?? box.w / Math.max(1, box.h);let w: number;let h: number;if (r >= 1) {@@ -91,8 +94,8 @@ export function exportDimsForShortEdge(box: { w: number; h: number }, shortEdge:}/** A GIF's size: its long side at `width`. */-export function exportGifDims(box: { w: number; h: number }, width: number): { w: number; h: number } {- const r = box.w / Math.max(1, box.h);+export function exportGifDims(box: { w: number; h: number; ratio?: number }, width: number): { w: number; h: number } {+ const r = box.ratio ?? box.w / Math.max(1, box.h);return r >= 1 ? { w: even(width), h: even(width / r) } : { w: even(width * r), h: even(width) };}diff --git a/packages/openfilm/studio/ui/src/lib/film-frame.ts b/packages/openfilm/studio/ui/src/lib/film-frame.tsindex 420daaa..d88ffef 100644--- a/packages/openfilm/studio/ui/src/lib/film-frame.ts+++ b/packages/openfilm/studio/ui/src/lib/film-frame.ts@@ -58,6 +58,8 @@ export interface FilmFrameBox {/** The frame's pixel size (an export comes out this size). */w: number;h: number;+ /** Its exact shape: the frame's own ratio, not its even-rounded pixels' (16:9 around a 2:1 film is 2160 × 1216). */+ ratio: number;/** The film inside the frame, scaled. With `cover`, `left`/`top` go negative: the overflow is cut by the frame. */inner: { w: number; h: number; left: number; top: number; scale: number };}@@ -75,7 +77,7 @@ export function filmFrameBox(const sh = Math.max(1, stage.h);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 } };+ return { w: even(sw), h: even(sh), ratio: sw / sh, inner: { w: sw, h: sh, left: 0, top: 0, scale: 1 } };}/* the frame must hold the film both ways: take the larger */const byWidth = { w: sw, h: sw / ratio };@@ -91,6 +93,7 @@ export function filmFrameBox(return {w,h,+ ratio,inner: { w: iw, h: ih, left: (w - iw) / 2, top: (h - ih) / 2, scale },};}diff --git a/packages/openfilm/studio/ui/src/lib/freeze-frame.ts b/packages/openfilm/studio/ui/src/lib/freeze-frame.tsindex a1299bf..736ea38 100644--- a/packages/openfilm/studio/ui/src/lib/freeze-frame.ts+++ b/packages/openfilm/studio/ui/src/lib/freeze-frame.ts@@ -29,6 +29,7 @@ export interface FreezeSpec {still: string;mode: EditMode;sync: boolean;+ linkage?: boolean;durMs?: number;}@@ -45,6 +46,6 @@ export function planFreeze(model: EditModel, spec: FreezeSpec): Op[] | null {...(cls ? { class: cls } : {}),...(style ? { style } : {}),};- const room = planRoom(model, [{ track: spec.track, startMs, endMs: startMs + durMs }], { mode: spec.mode, sync: spec.sync });+ const room = planRoom(model, [{ track: spec.track, startMs, endMs: startMs + durMs }], { mode: spec.mode, sync: spec.sync, linkage: spec.linkage });return [{ op: 'insert', clip: still, at: Math.round(startMs) / 1000, track: spec.track }, ...room.ops];}diff --git a/packages/openfilm/studio/ui/src/lib/group-drag.test.ts b/packages/openfilm/studio/ui/src/lib/group-drag.test.tsnew file mode 100644index 0000000..9633b41--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/group-drag.test.ts@@ -0,0 +1,31 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { groupDragged, type GroupDrag } from './stage-gesture.ts';++const t = (x: number, y: number, s = 1, rotate = 0) => ({ x, y, scaleX: s, scaleY: s, rotate });+const size = { w: 100, h: 50 };+const drag = (d: Partial<GroupDrag>): GroupDrag => ({ kind: 'move', dx: 0, dy: 0, kx: 1, ky: 1, turn: 0, anchor: { x: 0, y: 0 }, ...d });+const near = (a: Record<string, number>, b: Record<string, number>) => {+ for (const k of Object.keys(b)) assert.ok(Math.abs(a[k]! - b[k]!) < 1e-9, `${k}: ${a[k]} vs ${b[k]}`);+};++test('several clips dragged together move by the same amount', () => {+ assert.deepEqual(groupDragged(drag({ dx: 30, dy: -10 }), t(100, 40), size), t(130, 30));+});++test('scaled from a corner, every clip keeps its place in proportion about the corner that stays', () => {+ const d = drag({ kind: 'scale', kx: 0.5, ky: 0.5, anchor: { x: 100, y: 40 } });+ near(groupDragged(d, t(100, 40, 2), size), t(100, 40, 1));+ near(groupDragged(d, t(700, 340), size), t(400, 190, 0.5));+});++test('stretched from an edge, only that way: each clip is stretched too', () => {+ const d = drag({ kind: 'scale', kx: 2, ky: 1, anchor: { x: 0, y: 0 } });+ near(groupDragged(d, t(100, 0), size), { x: 200, y: 0, scaleX: 2, scaleY: 1, rotate: 0 });+});++test('turned, each clip goes round the middle of the frame and turns by as much', () => {+ /* a clip whose center is 100 px right of the middle, turned a quarter: its center 100 px below, itself turned 90° */+ const d = drag({ kind: 'rotate', turn: 90, anchor: { x: 0, y: 0 } });+ near(groupDragged(d, t(50, -25), size), t(-50, 75, 1, 90));+});diff --git a/packages/openfilm/studio/ui/src/lib/media-bar.test.ts b/packages/openfilm/studio/ui/src/lib/media-bar.test.tsnew file mode 100644index 0000000..ae40430--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/media-bar.test.ts@@ -0,0 +1,29 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { BAR_BUTTON, MIN_FIELD, TYPING_FIELD, barLayout, rest } from './media-bar.ts';++/* about what the English words measure at 12.5px */+const words = { hint: 41, upload: 42 };+/* the width at which Upload keeps its word: the field shows its whole hint beside it */+const wordWidth = 20 + 39 + 42 + 4 * BAR_BUTTON + 5 * 4 + 39 + 41;++test('narrowing, Upload loses its word first, then the field gets shorter, then the search is a button', () => {+ assert.deepEqual(barLayout(500, words, 4, false), { field: true, uploadWord: true, tight: false, cramped: false });+ assert.deepEqual(barLayout(wordWidth, words, 4, false), { field: true, uploadWord: true, tight: false, cramped: false });+ assert.deepEqual(barLayout(wordWidth - 1, words, 4, false), { field: true, uploadWord: false, tight: false, cramped: false });+ /* the field stays down to its icon, its hint cut or gone; too short to type in, it opens over the bar */+ const fieldAt = (room: number) => 20 + BAR_BUTTON + 4 * BAR_BUTTON + 5 * 4 + room;+ assert.equal(rest(fieldAt(MIN_FIELD), false, BAR_BUTTON, 4), MIN_FIELD);+ assert.deepEqual(barLayout(fieldAt(TYPING_FIELD), words, 4, false), { field: true, uploadWord: false, tight: false, cramped: false });+ assert.deepEqual(barLayout(fieldAt(TYPING_FIELD) - 1, words, 4, false), { field: true, uploadWord: false, tight: false, cramped: true });+ assert.deepEqual(barLayout(fieldAt(MIN_FIELD), words, 4, false), { field: true, uploadWord: false, tight: false, cramped: true });+ assert.deepEqual(barLayout(fieldAt(MIN_FIELD) - 1, words, 4, false), { field: false, uploadWord: false, tight: true, cramped: true });+ /* the narrowest pane (200 px): every button whole */+ assert.ok(rest(200, true, BAR_BUTTON, 4) >= BAR_BUTTON);+});++test('a search typed keeps room for its clear button; a close button is one more square', () => {+ assert.equal(barLayout(wordWidth, words, 4, true).uploadWord, false);+ assert.equal(barLayout(wordWidth + 32, words, 5, false).uploadWord, true);+ assert.equal(barLayout(wordWidth + 31, words, 5, false).uploadWord, false);+});diff --git a/packages/openfilm/studio/ui/src/lib/media-bar.ts b/packages/openfilm/studio/ui/src/lib/media-bar.tsnew file mode 100644index 0000000..b7fcf40--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/media-bar.ts@@ -0,0 +1,58 @@+/**+ * The media pane's top bar at the pane's width, worked out from what its words measure in the person's language and+ * font. The search field takes whatever room is left, so nothing is left empty. As the pane narrows, Upload loses its+ * word first, then the field gets shorter (its hint cut, or gone, down to its icon), and only when even that does not+ * fit does the search become a button. A field too short to type in opens over the bar when clicked. The square+ * buttons (view, filter, sort, new folder, close) always stay.+ */++/** What the words measure, in px, at the bar's type. */+export interface BarWords {+ /** The search's hint ("Search"). */+ hint: number;+ /** Upload's word. */+ upload: number;+}++export interface BarLayout {+ /** The search as a field (else a button). */+ field: boolean;+ /** Upload with its word (else its icon). */+ uploadWord: boolean;+ /** Tighter padding and gaps: the narrowest form. */+ tight: boolean;+ /** The field is too short to type in: clicked, it opens over the bar. */+ cramped: boolean;+}++/** A square button. */+export const BAR_BUTTON = 28;+/* the search field around its hint: padding 8 + icon 13 + gap 6 + padding 8, and room for the caret */+const FIELD_CHROME = 39;+/** The shortest field: its icon. */+export const MIN_FIELD = 44;+/** The shortest field to type in where it is: its icon and a few letters. */+export const TYPING_FIELD = 72;+/* the clear button, while something is typed */+const CLEAR = 18;+/* Upload around its word: padding 10 + icon 13 + gap 6 + padding 10 */+const UPLOAD_CHROME = 39;++/** The bar for `width` px, with `buttons` square buttons after Upload; `typed`: the search has text. */+export function barLayout(width: number, words: BarWords, buttons: number, typed: boolean): BarLayout {+ const clear = typed ? CLEAR : 0;+ /* Upload keeps its word while the field still shows its whole hint beside it */+ if (rest(width, false, UPLOAD_CHROME + words.upload, buttons) >= FIELD_CHROME + words.hint + clear) {+ return { field: true, uploadWord: true, tight: false, cramped: false };+ }+ const room = rest(width, false, BAR_BUTTON, buttons);+ if (room >= MIN_FIELD) return { field: true, uploadWord: false, tight: false, cramped: room < TYPING_FIELD + clear };+ return { field: false, uploadWord: false, tight: true, cramped: true };+}++/** The room the search field gets: the width less padding, Upload, the square buttons and the gaps between. */+export function rest(width: number, tight: boolean, upload: number, buttons: number): number {+ const pad = tight ? 16 : 20;+ const gap = tight ? 2 : 4;+ return width - pad - upload - buttons * BAR_BUTTON - (buttons + 1) * gap;+}diff --git a/packages/openfilm/studio/ui/src/lib/media-place.ts b/packages/openfilm/studio/ui/src/lib/media-place.tsindex a12585d..5e9aee7 100644--- a/packages/openfilm/studio/ui/src/lib/media-place.ts+++ b/packages/openfilm/studio/ui/src/lib/media-place.ts@@ -8,12 +8,12 @@* room, else a new one under the others).*/import type { Op } from '../api.ts';-import { assetClipElement, assetClipKindOf, dropDurMsOf } from './asset-timeline.ts';+import { assetClipElement, assetClipKindOf, dropDurMsOf, type StageSize } from './asset-timeline.ts';import type { ResourceDragItem } from './resource-drag';-import { planRoom, soundTrackFor, TOUCH_MS, type EditMode, type EditModel, type TrackDest } from './timeline-edit.ts';+import { magnetOn, planRoom, soundTrackFor, TOUCH_MS, type EditMode, type EditModel, type TrackDest } from './timeline-edit.ts';import { snapToFrame } from './timecode.ts';-export type PlaceFile = Pick<ResourceDragItem, 'path' | 'kind' | 'durationMs' | 'endless'>;+export type PlaceFile = Pick<ResourceDragItem, 'path' | 'kind' | 'durationMs' | 'endless' | 'reflows' | 'w' | 'h'>;/** A part of the file, in its own ms (the source viewer's in and out). */export type SourceRange = { inMs: number; outMs: number };@@ -25,8 +25,13 @@ export interface PlaceSpec {target: number | null;/** Where: the playhead (ms), or `end`, after the last clip of the track it goes on. */at: number | 'end';- mode: EditMode;+ /** Insert or overwrite; not given, the magnet decides: an insert on the main track when it is on. */+ mode?: EditMode;+ magnet?: boolean;sync: boolean;+ linkage?: boolean;+ /** The canvas: a picture of another shape gets a box in its own (asset-timeline assetFitBox). */+ stage?: StageSize | null;}export type PlacePlan = { ops: Op[]; track: TrackDest; startMs: number; durMs: number } | { error: 'not-clip' | 'locked' };@@ -34,8 +39,8 @@ export type PlacePlan = { ops: Op[]; track: TrackDest; startMs: number; durMs: nconst isSoundTrack = (role: string | undefined) => role === 'audio';/** The clip as film.html takes it: the file, trimmed to the part marked (a still keeps its length). */-function elementOf(file: PlaceFile, range: SourceRange | null | undefined): { element: Record<string, unknown>; durMs: number } | null {- const element = assetClipElement(file);+function elementOf(file: PlaceFile, range: SourceRange | null | undefined, stage: StageSize | null | undefined): { element: Record<string, unknown>; durMs: number } | null {+ const element = assetClipElement(file, stage);if (!element) return null;const still = Array.isArray(element.time);if (range && range.outMs > range.inMs && !(still && assetClipKindOf(file) === 'video')) {@@ -46,7 +51,7 @@ function elementOf(file: PlaceFile, range: SourceRange | null | undefined): { elexport function placeMedia(model: EditModel, spec: PlaceSpec): PlacePlan {const kind = assetClipKindOf(spec.file);- const made = kind ? elementOf(spec.file, spec.range) : null;+ const made = kind ? elementOf(spec.file, spec.range, spec.stage) : null;if (!kind || !made) return { error: 'not-clip' };const sound = kind === 'audio';const fits = (role: string | undefined) => (sound ? isSoundTrack(role) : !isSoundTrack(role));@@ -81,6 +86,7 @@ export function placeMedia(model: EditModel, spec: PlaceSpec): PlacePlan {if (typeof track !== 'number') return { ops: [insert], track, startMs, durMs: made.durMs };/* at the very end nothing follows: no room to make */const after = (model.find((t) => t.index === track)?.clips ?? []).some((c) => c.endMs > startMs + TOUCH_MS);- const room = after && !roomy ? planRoom(model, [{ track, startMs, endMs: startMs + made.durMs }], { mode: spec.mode, sync: spec.sync }).ops : [];+ const mode = spec.mode ?? (magnetOn(model, track, spec.magnet ?? false) ? 'insert' : 'overwrite');+ const room = after && !roomy ? planRoom(model, [{ track, startMs, endMs: startMs + made.durMs }], { mode, sync: spec.sync, linkage: spec.linkage }).ops : [];return { ops: [insert, ...room], track, startMs, durMs: made.durMs };}diff --git a/packages/openfilm/studio/ui/src/lib/media-selection.test.ts b/packages/openfilm/studio/ui/src/lib/media-selection.test.tsnew file mode 100644index 0000000..dfdfb2a--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/media-selection.test.ts@@ -0,0 +1,36 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { boxBetween, boxHits, boxPick, moveTargets, pickItem } from './media-selection.ts';++const order = ['assets/a', 'assets/b.png', 'assets/c.mp4', 'assets/d.pdf', 'scenes/e.html'];+const plain = { toggle: false, range: false };++test('a click picks one; ⌘ adds or takes away; ⇧ picks the run from the last one clicked', () => {+ assert.deepEqual(pickItem(['assets/b.png', 'assets/c.mp4'], 'assets/d.pdf', order, 'assets/b.png', plain), ['assets/d.pdf']);+ assert.deepEqual(pickItem(['assets/b.png'], 'assets/d.pdf', order, 'assets/b.png', { toggle: true, range: false }), ['assets/b.png', 'assets/d.pdf']);+ assert.deepEqual(pickItem(['assets/b.png', 'assets/d.pdf'], 'assets/b.png', order, 'assets/d.pdf', { toggle: true, range: false }), ['assets/d.pdf']);+ /* either way from the anchor; with ⌘ too, the run is added to what was picked */+ assert.deepEqual(pickItem(['assets/d.pdf'], 'assets/b.png', order, 'assets/d.pdf', { toggle: false, range: true }), ['assets/b.png', 'assets/c.mp4', 'assets/d.pdf']);+ assert.deepEqual(pickItem(['assets/a'], 'assets/d.pdf', order, 'assets/c.mp4', { toggle: true, range: true }), ['assets/a', 'assets/c.mp4', 'assets/d.pdf']);+ /* no anchor shown (it was in another folder): ⇧ picks just that one */+ assert.deepEqual(pickItem([], 'assets/c.mp4', order, 'assets/x', { toggle: false, range: true }), ['assets/c.mp4']);+});++test('a dragged box picks what it touches, whichever way it was dragged; with ⌘ or ⇧, on top of what was picked', () => {+ const tile = (key: string, left: number, top: number) => ({ key, box: { left, top, right: left + 100, bottom: top + 80 } });+ const items = [tile('a', 0, 0), tile('b', 110, 0), tile('c', 0, 90), tile('d', 110, 90)];+ const box = boxBetween({ x: 150, y: 120 }, { x: 50, y: 40 });+ assert.deepEqual(box, { left: 50, top: 40, right: 150, bottom: 120 });+ assert.deepEqual(boxHits(items, box), ['a', 'b', 'c', 'd']);+ /* touching an edge is not touching */+ assert.deepEqual(boxHits(items, { left: 100, top: 0, right: 110, bottom: 200 }), []);+ assert.deepEqual(boxHits(items, boxBetween({ x: 120, y: 85 }, { x: 300, y: 300 })), ['d']);+ assert.deepEqual(boxPick(['a'], ['d'], false), ['d']);+ assert.deepEqual(boxPick(['a', 'd'], ['d', 'c'], true), ['a', 'd', 'c']);+});++test('things can move to the top or any folder, never into a folder being moved or one inside it', () => {+ const folders = ['footage/b-roll', 'footage', 'music', 'footage10', 'footage2'];+ assert.deepEqual(moveTargets(folders, []), ['', 'footage', 'footage/b-roll', 'footage2', 'footage10', 'music']);+ assert.deepEqual(moveTargets(folders, ['footage']), ['', 'footage2', 'footage10', 'music']);+});diff --git a/packages/openfilm/studio/ui/src/lib/media-selection.ts b/packages/openfilm/studio/ui/src/lib/media-selection.tsnew file mode 100644index 0000000..ffad925--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/media-selection.ts@@ -0,0 +1,64 @@+/**+ * What is picked in the media pane, the way a file manager picks (Finder, File Explorer): a click picks one, ⌘ (Ctrl)+ * adds one or takes it away, ⇧ picks the run from the one clicked last, and a box dragged over empty space picks what+ * it touches (with ⌘ or ⇧ held, on top of what was picked). Items are named by their project-relative path, a+ * folder's too, so a key is the path a move or a delete takes.+ */++export interface PickMods {+ /** ⌘ or Ctrl held: add or take away. */+ toggle: boolean;+ /** ⇧ held: the run from the anchor. */+ range: boolean;+}++/** What is picked after a click on `key`; `order` is the items as shown, `anchor` the one clicked last. */+export function pickItem(+ picked: readonly string[],+ key: string,+ order: readonly string[],+ anchor: string | null,+ mods: PickMods,+): string[] {+ const from = anchor == null ? -1 : order.indexOf(anchor);+ const to = order.indexOf(key);+ if (mods.range && from >= 0 && to >= 0) {+ const run = order.slice(Math.min(from, to), Math.max(from, to) + 1);+ return mods.toggle ? [...new Set([...picked, ...run])] : run;+ }+ if (mods.toggle) return picked.includes(key) ? picked.filter((k) => k !== key) : [...picked, key];+ return [key];+}++export interface Box {+ left: number;+ top: number;+ right: number;+ bottom: number;+}++/** The box between two points, whichever way it was dragged. */+export function boxBetween(a: { x: number; y: number }, b: { x: number; y: number }): Box {+ return { left: Math.min(a.x, b.x), top: Math.min(a.y, b.y), right: Math.max(a.x, b.x), bottom: Math.max(a.y, b.y) };+}++/** The items a dragged box touches, in the order given. */+export function boxHits(items: readonly { key: string; box: Box }[], box: Box): string[] {+ return items+ .filter(({ box: b }) => b.left < box.right && b.right > box.left && b.top < box.bottom && b.bottom > box.top)+ .map(({ key }) => key);+}++/** What a box picks: what it touches, or that on top of what was picked before it (`add`). */+export function boxPick(before: readonly string[], hits: readonly string[], add: boolean): string[] {+ return add ? [...new Set([...before, ...hits])] : [...hits];+}++/**+ * Where things can be moved: the top ('') and every folder (paths under assets/), less the folders being moved and+ * the folders inside them (a folder cannot go into itself).+ */+export function moveTargets(folders: readonly string[], moving: readonly string[]): string[] {+ const inside = (dir: string) => moving.some((m) => dir === m || dir.startsWith(`${m}/`));+ return ['', ...folders.filter((dir) => !inside(dir)).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))];+}diff --git a/packages/openfilm/studio/ui/src/lib/project-sources.test.ts b/packages/openfilm/studio/ui/src/lib/project-sources.test.tsindex 635cad5..ae79517 100644--- a/packages/openfilm/studio/ui/src/lib/project-sources.test.ts+++ b/packages/openfilm/studio/ui/src/lib/project-sources.test.ts@@ -1,8 +1,8 @@import { test } from 'node:test';import assert from 'node:assert/strict';import {- SourceError, examplesCollapsed, fetchErrorKey, followFetch, formatBytes, formatSeconds, looksLikeRepoUrl, pathCrumbs,- setExamplesCollapsed, type FetchJob,+ SourceError, createSpeedMeter, examplesCollapsed, fetchErrorKey, followFetch, formatBytes, formatSeconds, looksLikeRepoUrl,+ pathCrumbs, secondsLeft, setExamplesCollapsed, type FetchJob,} from './project-sources.ts';test('what looks like a repository address enables "Get"', () => {@@ -23,6 +23,22 @@ test('sizes and lengths as people read them', () => {assert.equal(formatSeconds(5.6), '0:06');});+test('a download\'s speed is what came over the last few seconds; the time left follows from it', () => {+ const speed = createSpeedMeter(5000);+ assert.equal(speed(0, 0), null, 'nothing to go on yet');+ assert.equal(speed(500_000, 500), null, 'under a second');+ assert.equal(speed(1_000_000, 1000), 1_000_000);+ for (let s = 2; s <= 10; s++) speed(1_000_000 * s, s * 1000);+ /* it stalls: within the window the speed falls, it does not keep the old average */+ assert.equal(speed(10_000_000, 14_000), 1_000_000 * 1 / 5);+ assert.equal(speed(10_000_000, 16_000), 0);+ /* fewer bytes: another download, measured afresh */+ assert.equal(speed(0, 17_000), null);+ assert.equal(secondsLeft(2_000_000, 10_000_000, 1_000_000), 8);+ assert.equal(secondsLeft(2_000_000, null, 1_000_000), null, 'no total');+ assert.equal(secondsLeft(2_000_000, 10_000_000, 0), null, 'nothing coming');+});+test('breadcrumbs from the home folder, on macOS, Linux and Windows paths', () => {assert.deepEqual(pathCrumbs('/Volumes/work/Movies/Films', '/Volumes/work'), [{ name: '~', path: '/Volumes/work' }, { name: 'Movies', path: '/Volumes/work/Movies' }, { name: 'Films', path: '/Volumes/work/Movies/Films' },@@ -41,7 +57,7 @@ test('each failure code has its own words; others say the server\'s message', ()assert.equal(fetchErrorKey(undefined), null);});-const job = (over: Partial<FetchJob> = {}): FetchJob => ({ id: 'j', url: 'u', label: 'o/r', state: 'running', phase: 'lookup', percent: null, bytes: 0, ...over });+const job = (over: Partial<FetchJob> = {}): FetchJob => ({ id: 'j', url: 'u', label: 'o/r', state: 'running', phase: 'lookup', percent: null, bytes: 0, total: null, ...over });const now = () => Promise.resolve();test('a fetch is followed until it is done, each state told', async () => {diff --git a/packages/openfilm/studio/ui/src/lib/project-sources.ts b/packages/openfilm/studio/ui/src/lib/project-sources.tsindex 1232e2b..383ab67 100644--- a/packages/openfilm/studio/ui/src/lib/project-sources.ts+++ b/packages/openfilm/studio/ui/src/lib/project-sources.ts@@ -31,6 +31,8 @@ export type FetchJob = {phase: FetchPhase;percent: number | null;bytes: number;+ /** the size of the whole, when it is known before it downloads (GitHub over https); null through git */+ total: number | null;error?: string;code?: string;project?: { id: string };@@ -80,6 +82,28 @@ export function formatBytes(bytes: number): string {return `${(bytes / 1024 ** 3).toFixed(1)} GB`;}+/**+ * How fast a download goes, in bytes a second: what came over the last few seconds (`windowMs`), so a stall shows+ * soon and a burst does not jump it. Null until it has a second to go on.+ */+export function createSpeedMeter(windowMs = 5000): (bytes: number, at: number) => number | null {+ const samples: { at: number; bytes: number }[] = [];+ return (bytes, at) => {+ /* fewer bytes than before: a new download, measured afresh */+ if (samples.length && bytes < samples[samples.length - 1].bytes) samples.length = 0;+ samples.push({ at, bytes });+ while (samples.length > 2 && at - samples[1].at >= windowMs) samples.shift();+ const span = (at - samples[0].at) / 1000;+ return span >= 1 ? Math.max(0, (bytes - samples[0].bytes) / span) : null;+ };+}++/** Seconds a download has left at `speed`; null when that cannot be told (no total, or nothing coming). */+export function secondsLeft(bytes: number, total: number | null, speed: number | null): number | null {+ if (!total || !speed || speed <= 0) return null;+ return Math.max(0, (total - bytes) / speed);+}+/** A length in seconds as m:ss. */export function formatSeconds(seconds: number): string {const total = Math.max(0, Math.round(seconds));diff --git a/packages/openfilm/studio/ui/src/lib/resource-drag.ts b/packages/openfilm/studio/ui/src/lib/resource-drag.tsindex 21c7061..d37f6eb 100644--- a/packages/openfilm/studio/ui/src/lib/resource-drag.ts+++ b/packages/openfilm/studio/ui/src/lib/resource-drag.ts@@ -29,6 +29,8 @@ export interface ResourceDragItem {durationMs?: number;/** A web page without a duration (no end): written with a length of its own, as a still. */endless?: boolean;+ /** A web page that sets no size of its own (its `w` × `h` is the size it is shown at alone). */+ reflows?: boolean;w?: number;h?: number;fps?: number;@@ -95,6 +97,7 @@ function normalizeResourceDragItem(value: unknown): ResourceDragItem | null {mtimeMs: typeof item.mtimeMs === 'number' && Number.isFinite(item.mtimeMs) ? item.mtimeMs : 0,...(durationMs === undefined ? {} : { durationMs }),...(item.endless === true ? { endless: true } : {}),+ ...(item.reflows === true ? { reflows: true } : {}),...(w === undefined ? {} : { w }),...(h === undefined ? {} : { h }),...(fps === undefined ? {} : { fps }),diff --git a/packages/openfilm/studio/ui/src/lib/select-all-key.test.ts b/packages/openfilm/studio/ui/src/lib/select-all-key.test.tsnew file mode 100644index 0000000..9e3ab96--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/select-all-key.test.ts@@ -0,0 +1,17 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { isSelectAll } from './select-all-key.ts';++const key = (k: string, mods: Partial<{ metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean }> = {}) => (+ { key: k, metaKey: false, ctrlKey: false, shiftKey: false, altKey: false, ...mods }+);++test('select all is ⌘A on a Mac and Ctrl+A elsewhere; with Shift or Alt it is another shortcut', () => {+ assert.equal(isSelectAll(key('a', { metaKey: true }), true), true);+ assert.equal(isSelectAll(key('A', { metaKey: true }), true), true);+ assert.equal(isSelectAll(key('a', { ctrlKey: true }), true), false, 'Ctrl+A on a Mac moves the caret');+ assert.equal(isSelectAll(key('a', { ctrlKey: true }), false), true);+ assert.equal(isSelectAll(key('a', { metaKey: true, shiftKey: true }), true), false);+ assert.equal(isSelectAll(key('a', { metaKey: true, altKey: true }), true), false);+ assert.equal(isSelectAll(key('a'), true), false);+});diff --git a/packages/openfilm/studio/ui/src/lib/select-all-key.ts b/packages/openfilm/studio/ui/src/lib/select-all-key.tsnew file mode 100644index 0000000..91b7f4d--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/select-all-key.ts@@ -0,0 +1,7 @@+/** A key that can be select-all: what a keydown, or a key passed on from the film, says of itself. */+export interface KeyLike { key: string; metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean }++/** ⌘A on a Mac, Ctrl+A elsewhere, without Shift or Alt: select all, as Figma, Photoshop and Premiere have it. */+export function isSelectAll(e: KeyLike, mac: boolean): boolean {+ return (mac ? e.metaKey : e.ctrlKey) && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'a';+}diff --git a/packages/openfilm/studio/ui/src/lib/stage-gesture.ts b/packages/openfilm/studio/ui/src/lib/stage-gesture.tsindex 5feba96..0c08f47 100644--- a/packages/openfilm/studio/ui/src/lib/stage-gesture.ts+++ b/packages/openfilm/studio/ui/src/lib/stage-gesture.ts@@ -199,3 +199,36 @@ export function alignShift(edge: AlignEdge, rect: ClientBox, union: ClientBox):: edge === 'vcenter' ? union.top + union.height / 2 - (rect.top + rect.height / 2) : 0,};}++/**+ * How several whole clips are being dragged together (stage px): moved by (dx, dy); scaled by (kx, ky) about the+ * corner or edge that stays (`anchor`), the same on both axes from a corner; or turned by `turn` degrees about the+ * middle of their frame (`anchor`).+ */+export interface GroupDrag {+ kind: 'move' | 'scale' | 'rotate';+ dx: number; dy: number;+ kx: number; ky: number;+ turn: number;+ anchor: { x: number; y: number };+}++/**+ * Where one of several clips dragged together is now. `t0` is where it was (its unturned top left, stage px, and its+ * scale), `size` its picture's own size: its center moves with the others, scaled or turned about the same point, so+ * the gaps between them change with them (Figma); a turn turns each one by as much.+ */+export function groupDragged<T extends { x: number; y: number; scaleX: number; scaleY: number; rotate: number }>(+ d: GroupDrag, t0: T, size: { w: number; h: number },+): T {+ if (d.kind === 'move') return { ...t0, x: t0.x + d.dx, y: t0.y + d.dy };+ const w0 = size.w * t0.scaleX, h0 = size.h * t0.scaleY;+ const cx = t0.x + w0 / 2 - d.anchor.x, cy = t0.y + h0 / 2 - d.anchor.y;+ if (d.kind === 'scale') {+ const w = w0 * d.kx, h = h0 * d.ky;+ return { ...t0, x: d.anchor.x + cx * d.kx - w / 2, y: d.anchor.y + cy * d.ky - h / 2, scaleX: t0.scaleX * d.kx, scaleY: t0.scaleY * d.ky };+ }+ const a = (d.turn * Math.PI) / 180;+ const nx = cx * Math.cos(a) - cy * Math.sin(a), ny = cx * Math.sin(a) + cy * Math.cos(a);+ return { ...t0, x: d.anchor.x + nx - w0 / 2, y: d.anchor.y + ny - h0 / 2, rotate: t0.rotate + d.turn };+}diff --git a/packages/openfilm/studio/ui/src/lib/stage-types.ts b/packages/openfilm/studio/ui/src/lib/stage-types.tsindex 0c3929a..b76d5c5 100644--- a/packages/openfilm/studio/ui/src/lib/stage-types.ts+++ b/packages/openfilm/studio/ui/src/lib/stage-types.ts@@ -103,8 +103,8 @@ export interface StageGeometry {parentR?: number;/** A clip's picture at its own size: typed numbers are worked out from it. */box?: MgBox;- /** A group: how many layers, and of which kinds. */- group?: { n: number; kinds: readonly StageNodeKind[] };+ /** A group: how many layers, of which kinds, and which (the inspector edits their looks together). */+ group?: { n: number; kinds: readonly StageNodeKind[]; elements?: readonly StageElement[] };stage: { w: number; h: number };}diff --git a/packages/openfilm/studio/ui/src/lib/timeline-clipboard.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-clipboard.test.tsindex 13b22b9..96eeb86 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-clipboard.test.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-clipboard.test.ts@@ -157,6 +157,24 @@ test('a paste in overwrite mode cuts what is under it; a locked track refuses itassert.equal(pasteEdit(copied, locked, editModelOf(locked), 3000, 'doc-0', { mode: 'overwrite', sync: true }), null);});+test('with the magnet, as CapCut: a paste on the main track inserts; off it a copy never covers a clip', () => {+ const film: Film = { tracks: [{ clips: [filmClip('t1', 0, 2)] }, { clips: [filmClip('a', 0, 2), filmClip('b', 2, 2)] }] };+ const tracks = [+ track(0, [blockOf('t1', 0, 0, 0, 2000)], { role: 'mg' }),+ track(1, [blockOf('a', 1, 0, 0, 2000), blockOf('b', 1, 1, 2000, 4000)], { role: 'video' }),+ ];+ const model = editModelOf(tracks);+ /* the title pasted at 1 s over itself: a new title track opens above for the copy */+ const title = pasteEdit(clipboardItemsOf([tracks[0]!.blocks[0]!], tracks), tracks, model, 1000, 'doc-0', { magnet: true, sync: false, linkage: true })!;+ assert.deepEqual(spans(applyOps(structuredClone(film) as never, title as never) as unknown as Film), [[['t1-2', 1, null]], [['t1', 0, null]], [['a', 0, null], ['b', 2, null]]]);+ /* at 3 s its own track is free: it goes there */+ const free = pasteEdit(clipboardItemsOf([tracks[0]!.blocks[0]!], tracks), tracks, model, 3000, 'doc-0', { magnet: true, sync: false, linkage: true })!;+ assert.deepEqual(spans(applyOps(structuredClone(film) as never, free as never) as unknown as Film)[0], [['t1', 0, null], ['t1-2', 3, null]]);+ /* a shot pasted at 2 s on the main track goes in between and pushes b on; the title over a stays */+ const shot = pasteEdit(clipboardItemsOf([tracks[1]!.blocks[0]!], tracks), tracks, model, 2000, 'doc-1', { magnet: true, sync: false, linkage: true })!;+ assert.deepEqual(spans(applyOps(structuredClone(film) as never, shot as never) as unknown as Film), [[['t1', 0, null]], [['a', 0, null], ['a-2', 2, null], ['b', 4, null]]]);+});+test('copies of linked clips pasted together are linked to each other, not to the originals', () => {const tracks = [track(0, [blockOf('v', 0, 0, 0, 2000)]), track(1, [blockOf('s', 1, 0, 0, 2000), blockOf('t', 1, 1, 3000, 4000)])];const model = editModelOf(tracks, new Map([['v', 'v'], ['s', 'v'], ['t', 'x']]));diff --git a/packages/openfilm/studio/ui/src/lib/timeline-clipboard.ts b/packages/openfilm/studio/ui/src/lib/timeline-clipboard.tsindex 14d3fc1..666595b 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-clipboard.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-clipboard.ts@@ -12,7 +12,7 @@ import type { Op } from '../api.ts';import { FILM_DOC_FILE } from './film.ts';import { newTrackSide } from './timeline-drag.ts';-import { freshLink, planRoom, type EditMode, type EditModel } from './timeline-edit.ts';+import { freshLink, freeTrackFor, mainTrackOf, planRoom, type EditMode, type EditModel, type Follow, type TrackDest } from './timeline-edit.ts';import type { TimelineBlock, TimelineTrack } from './timeline-layout';export type TimelineClipboardItem = {@@ -243,11 +243,12 @@ export function copyLinks(clipIds: readonly string[], model: EditModel): Map<str}/**- * A paste as an edit in the timeline's mode, never onto a new track: copied from one track, the copies go onto the- * track pointed at (`forceLane`) if any; from several, each back onto its own. The group's earliest clip lands at- * `atMs`, the rest keep their spacing. An insert makes room there (pushing what follows on, with sync lock on every- * unlocked track); an overwrite takes that time off the tracks. The copies go in first, so a clip pasted over itself- * is copied whole before it is cut. Null when a track it goes onto is locked or gone.+ * A paste as an edit in the timeline's mode: copied from one track, the copies go onto the track pointed at+ * (`forceLane`) if any; from several, each back onto its own. The group's earliest clip lands at `atMs`, the rest+ * keep their spacing. An insert makes room there (pushing what follows on, with sync lock on every unlocked track);+ * an overwrite takes that time off the tracks. With the magnet given (as CapCut's): an insert on the main track, and+ * off it a copy whose time is taken goes to a free track or a new one. The copies go in first, so a clip pasted over+ * itself is copied whole before it is cut. Null when a track it goes onto is locked or gone.*/export function pasteEdit(clipboard: readonly TimelineClipboardItem[],@@ -255,7 +256,7 @@ export function pasteEdit(model: EditModel,atMs: number,forceLane: string | null,- opts: { mode: EditMode; sync: boolean },+ opts: Follow & ({ mode: EditMode } | { magnet: boolean }),): Op[] | null {if (!clipboard.length) return [];const base = Math.min(...clipboard.map((item) => item.startMs));@@ -267,14 +268,46 @@ export function pasteEdit(return { item, track: row?.docIndex, locked: Boolean(row?.locked), startMs, endMs: startMs + item.durMs };});if (spans.some((s) => s.track == null || s.locked)) return null;- const room = planRoom(model, spans.map((s) => ({ track: s.track!, startMs: s.startMs, endMs: s.endMs })), opts);const links = copyLinks(clipboard.map((item) => item.clipId), model);- const inserts: Op[] = spans.map((s) => ({+ const insertOf = (s: (typeof spans)[number], track: TrackDest): Op => ({op: 'insert',from: s.item.clipId,at: s.startMs / 1000,- track: s.track!,+ track,...(links.has(s.item.clipId) ? { link: links.get(s.item.clipId)! } : {}),+ });+ if ('mode' in opts || !opts.magnet) {+ const mode = 'mode' in opts ? opts.mode : 'overwrite';+ const room = planRoom(model, spans.map((s) => ({ track: s.track!, startMs: s.startMs, endMs: s.endMs })), { mode, sync: opts.sync, linkage: opts.linkage });+ return [...spans.map((s) => insertOf(s, s.track!)), ...room.ops];+ }+ /* the magnet, as CapCut's: onto the main track an insert (what follows moves on); off it nothing is covered — a+ copy whose time is taken goes to a free track, else a new one */+ const main = mainTrackOf(model);+ const onMain = spans.filter((s) => s.track === main);+ const room = planRoom(model, onMain.map((s) => ({ track: s.track!, startMs: s.startMs, endMs: s.endMs })), { mode: 'insert', sync: opts.sync, linkage: opts.linkage });+ /* the tracks as the insert left them */+ const after: EditModel = model.map((t) => ({+ ...t,+ clips: t.clips.flatMap((c) => {+ if (!room.placed.has(c.id)) return [c];+ const at = room.placed.get(c.id);+ return at && at.track === t.index ? [{ ...c, startMs: at.startMs, endMs: at.endMs }] : [];+ }),}));- return [...inserts, ...room.ops];+ const taken: { track: number; startMs: number; endMs: number }[] = [];+ const placed = spans.map((s) => {+ if (s.track === main) return { s, track: s.track as TrackDest };+ const track = freeTrackFor(after, s.track!, s, taken);+ if (typeof track === 'number') taken.push({ track, startMs: s.startMs, endMs: s.endMs });+ return { s, track };+ });+ /* new tracks last, the lowest place first, so the places of the others hold while they open */+ const opened = placed.filter((p) => typeof p.track === 'object')+ .sort((a, b) => (b.track as { insert: number }).insert - (a.track as { insert: number }).insert);+ return [+ ...placed.filter((p) => typeof p.track === 'number').map((p) => insertOf(p.s, p.track)),+ ...room.ops,+ ...opened.map((p) => insertOf(p.s, p.track)),+ ];}diff --git a/packages/openfilm/studio/ui/src/lib/timeline-edit.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-edit.test.tsindex f0d3f69..7ed257c 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-edit.test.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-edit.test.ts@@ -7,8 +7,12 @@ import {freshLink,gapAt,insertPointOn,+ hostOf,linkedIds,+ magnetOn,+ mainTrackOf,planCloseGap,+ planCloseMainGaps,planEdges,planLink,planMove,@@ -18,9 +22,11 @@ import {planRoom,planSpeed,planUnlink,+ ridesOn,rollMoves,slideMoves,soundTrackFor,+ sourceLeftMs,type EditClip,type EditModel,type EditPlan,@@ -150,6 +156,179 @@ test('closing a gap moves what is after it back, on every unlocked track with syassert.deepEqual(planCloseGap(locked, 0, gap, { sync: true }).ops, []);});+test('a gap a synced track has no room for still closes, on its own track alone', () => {+ /* the gap before the first clip on the top track ends at 4.6 s, where a clip on the track below is playing and+ the next starts right after it: a synced ripple could not move at all */+ const m = model([['top', 4.6, 9.6]], [['title', 0, 5], ['cards', 5, 10]], [['bed', 0, 15]]);+ const gap = gapAt(m, 0, 1000)!;+ assert.deepEqual(gap, { startMs: 0, endMs: 4600 });+ const plan = planCloseGap(m, 0, gap, { sync: true });+ assert.equal(plan.alone, true);+ assert.equal(plan.shortMs, 0);+ assert.deepEqual(after(m, plan), [[['top', 0, 5]], [['title', 0, 5], ['cards', 5, 10]], [['bed', 0, 15]]]);+ /* with room on every track, sync lock is kept */+ assert.equal(planCloseGap(model([['a', 0, 2], ['b', 4, 5]], [['vo', 4, 6]]), 0, { startMs: 2000, endMs: 4000 }, { sync: true }).alone, undefined);+});++test('how much source a clip can still show at each edge', () => {+ /* 2–6 s of a 10 s file, at 2 s on the film; a still has no end */+ const m = model([['v', 2, 6, { inMs: 2000, sourceMs: 10_000 }], ['p', 6, 8, { still: true, sourceMs: Infinity }]]);+ assert.equal(sourceLeftMs(m, 'v', 'start'), 2000);+ assert.equal(sourceLeftMs(m, 'v', 'end'), 4000);+ assert.equal(sourceLeftMs(m, 'p', 'end'), Infinity);+ assert.equal(sourceLeftMs(m, 'gone', 'end'), undefined);+});++/* ── the main track and linkage (as CapCut) ── */++/* titles over the picture, the picture (the main track), music under it */+const film = (titles: Spec[], main: Spec[], music: Spec[] = []) => model(+ { role: 'mg', clips: titles }, { role: 'video', clips: main }, { role: 'audio', clips: music },+);+const LINK = { sync: false, linkage: true } as const;++test('the main track is the lowest picture track; the magnet acts on it alone', () => {+ const m = film([['t', 0, 1]], [['a', 0, 2]], [['bed', 0, 9]]);+ assert.equal(mainTrackOf(m), 1);+ assert.equal(magnetOn(m, 1, true), true);+ assert.equal(magnetOn(m, 0, true), false);+ assert.equal(magnetOn(m, 1, false), false);+ assert.equal(mainTrackOf(model({ role: 'audio', clips: [] })), null);+});++test('a clip rides on the main-track clip its start falls in, or the last one after the end', () => {+ const main = film([], [['a', 0, 2], ['b', 2, 5]])[1]!;+ assert.equal(hostOf(main, { startMs: 2500 })?.id, 'b');+ assert.equal(hostOf(main, { startMs: 2000 })?.id, 'b');+ assert.equal(hostOf(main, { startMs: 7000 })?.id, 'b');+ assert.equal(hostOf(film([], [['a', 1, 2]])[1]!, { startMs: 500 }), null);+});++test('with linkage a ripple delete on the main track carries the titles and sound after it, whatever is in the way', () => {+ /* t2 sits over b, t3 over c; the bed runs under everything, so sync lock could not move at all */+ const m = model(+ { role: 'mg', clips: [['t2', 2.5, 3.5], ['t3', 5.5, 6.5]] },+ { role: 'video', clips: [['a', 0, 2], ['b', 2, 5], ['c', 5, 7]] },+ { role: 'audio', clips: [['bed', 0, 9]] },+ { role: 'audio', clips: [['sfx', 5, 6]] },+ );+ const plan = planRemove(m, ['b'], { ripple: true, ...LINK });+ assert.equal(plan.shortMs, 0);+ /* t2 rode on b, which went: it stays where it was, now over c. t3 moves back with c onto it, so it goes to a new+ title track above; the sound effect moves back; the bed spans the cut and stays */+ assert.deepEqual(after(m, plan), [[['t3', 2.5, 3.5]], [['t2', 2.5, 3.5]], [['a', 0, 2], ['c', 2, 4]], [['bed', 0, 9]], [['sfx', 2, 3]]]);+ assert.equal(planRemove(m, ['b'], { ripple: true, sync: true }).shortMs, 1000);+});++test('linkage: a carried clip that runs into one that stayed goes to a free track above, else a new one', () => {+ /* t1 rides on a (stays), t2 on b (moves back 2 s, onto t1) */+ const m = film([['t1', 0.5, 1.8], ['t2', 2.5, 3.5]], [['a', 0, 1], ['x', 1, 2.5], ['b', 2.5, 5]]);+ const out = after(m, planRemove(m, ['x'], { ripple: true, ...LINK }));+ /* a new track opened above the titles takes t2; t1 stays on its own */+ assert.deepEqual(out, [[['t2', 1, 2]], [['t1', 0.5, 1.8]], [['a', 0, 1], ['b', 1, 3.5]]]);+ /* with a free title track above, it goes there */+ const roomy = model({ role: 'mg', clips: [] }, { role: 'mg', clips: [['t1', 0.5, 1.8], ['t2', 2.5, 3.5]] }, { role: 'video', clips: [['a', 0, 1], ['x', 1, 2.5], ['b', 2.5, 5]] });+ assert.deepEqual(after(roomy, planRemove(roomy, ['x'], { ripple: true, ...LINK })), [[['t2', 1, 2]], [['t1', 0.5, 1.8]], [['a', 0, 1], ['b', 1, 3.5]]]);+});++test('with the magnet a delete closes up the main track only; titles leave a gap', () => {+ const m = film([['t1', 0, 1], ['t2', 1, 2], ['t3', 2, 3]], [['a', 0, 2], ['b', 2, 4], ['c', 4, 6]]);+ const plan = planRemove(m, ['b', 't2'], { ripple: 'main', ...LINK });+ /* the title track keeps its gap where t2 was; c closes up and carries nothing (t3 rode on b, which went) */+ assert.deepEqual(after(m, plan), [[['t1', 0, 1], ['t3', 2, 3]], [['a', 0, 2], ['c', 2, 4]]]);+});++test('with linkage a ripple trim of a main-track clip carries what comes after it, not what rides on it', () => {+ /* the music's second clip starts right where its first ends, half a second after a's end */+ const m = film([['ta', 0.5, 1], ['tb', 3, 4]], [['a', 0, 2], ['b', 2, 5]], [['m1', 0, 2.5], ['m2', 2.5, 9]]);+ const plan = planRippleTrim(m, ['a'], 'end', -1000, LINK);+ assert.equal(plan.deltaMs, -1000);+ /* m1 starts over a and stays; m2 starts over b and moves back onto m1, so it goes to a new sound track below */+ assert.deepEqual(after(m, plan), [[['ta', 0.5, 1], ['tb', 2, 3]], [['a', 0, 1], ['b', 1, 4]], [['m1', 0, 2.5]], [['m2', 1.5, 8]]]);+ /* sync lock alone could not: the music is in the way */+ assert.equal(planRippleTrim(m, ['a'], 'end', -1000, { sync: true }).deltaMs, 0);+});++test('with linkage an insert on the main track pushes what comes after on every track', () => {+ const m = film([['tb', 3, 4]], [['a', 0, 2], ['b', 2, 5]], [['bed', 0, 9]]);+ const plan = planRoom(m, [{ track: 1, startMs: 2000, endMs: 3000 }], { mode: 'insert', ...LINK });+ assert.deepEqual(after(m, plan), [[['tb', 4, 5]], [['a', 0, 2], ['b', 3, 6]], [['bed', 0, 9]]]);+});++test('with linkage a main-track clip moved along the main track takes its titles along', () => {+ /* b (2–5 s, its title at 3 s) goes to the front */+ const m = film([['ta', 0.5, 1.5], ['tb', 3, 4]], [['a', 0, 2], ['b', 2, 5]]);+ const plan = planMove(m, { ids: ['b'], deltaMs: -2000, pointerMs: 500, mode: 'insert', magnet: true, ...LINK })!;+ const out = after(m, plan);+ assert.deepEqual(out[1], [['b', 0, 3], ['a', 3, 5]]);+ assert.deepEqual(out.flat().filter(([id]) => id.startsWith('t')).sort(), [['ta', 3.5, 4.5], ['tb', 1, 2]]);+});++test('linkage leaves a long clip crossing more than one cut where it is: a music bed is the film\'s, not a shot\'s', () => {+ const main = film([], [['a', 0, 2], ['b', 2, 5], ['c', 5, 7]])[1]!;+ assert.equal(ridesOn(main, { startMs: 0, endMs: 9000 }), false, 'under every shot');+ assert.equal(ridesOn(main, { startMs: 1000, endMs: 3000 }), true, 'across one cut');+ assert.equal(ridesOn(main, { startMs: 2500, endMs: 3500 }), true, 'inside a shot');+ /* b moved to the front: its title goes with it, the bed under everything stays at 0 */+ const m = film([['tb', 3, 4]], [['a', 0, 2], ['b', 2, 5], ['c', 5, 7]], [['bed', 0, 7]]);+ const plan = planMove(m, { ids: ['b'], deltaMs: -2000, pointerMs: 500, mode: 'insert', magnet: true, ...LINK })!;+ assert.deepEqual(after(m, plan), [[['tb', 1, 2]], [['b', 0, 3], ['a', 3, 5], ['c', 5, 7]], [['bed', 0, 7]]]);+ /* an insert at the very start pushes the shots and their titles, not the bed */+ const room = planRoom(m, [{ track: 1, startMs: 0, endMs: 1000 }], { mode: 'insert', ...LINK });+ assert.deepEqual(after(m, room), [[['tb', 4, 5]], [['a', 1, 3], ['b', 3, 6], ['c', 6, 8]], [['bed', 0, 7]]]);+});++test('with the magnet a clip taken off the main track closes it up, wherever it lands', () => {+ const m = film([], [['a', 0, 2], ['b', 2, 4], ['c', 4, 6]]);+ const plan = planMove(m, { ids: ['b'], deltaMs: 0, pointerMs: 3000, to: new Map([['b', 0]]), mode: 'overwrite', magnet: true, ...LINK })!;+ assert.deepEqual(after(m, plan), [[['b', 2, 4]], [['a', 0, 2], ['c', 2, 4]]]);+ /* moved along a title track it closes nothing there */+ const t = film([['t1', 0, 1], ['t2', 2, 3]], [['a', 0, 4]]);+ const moved = planMove(t, { ids: ['t1'], deltaMs: 3000, pointerMs: 3500, mode: 'overwrite', magnet: true, ...LINK })!;+ assert.deepEqual(after(t, moved), [[['t2', 2, 3], ['t1', 3, 4]], [['a', 0, 4]]]);+});++test('with the magnet a clip let go on another off the main track covers nothing: it goes to a free track', () => {+ /* two title tracks; t3 dragged onto t1's time on the lower one goes up to the free one */+ const m = model({ role: 'mg', clips: [['t2', 4, 5]] }, { role: 'mg', clips: [['t1', 0, 2], ['t3', 3, 4]] }, { role: 'video', clips: [['a', 0, 6]] });+ const plan = planMove(m, { ids: ['t3'], deltaMs: -2000, pointerMs: 1500, mode: 'overwrite', magnet: true, ...LINK })!;+ assert.deepEqual(after(m, plan), [[['t3', 1, 2], ['t2', 4, 5]], [['t1', 0, 2]], [['a', 0, 6]]]);+ /* no room anywhere: a new track above */+ const full = model({ role: 'mg', clips: [['t1', 0, 2], ['t3', 3, 4]] }, { role: 'video', clips: [['a', 0, 6]] });+ const opened = planMove(full, { ids: ['t3'], deltaMs: -2000, pointerMs: 1500, mode: 'overwrite', magnet: true, ...LINK })!;+ assert.deepEqual(after(full, opened), [[['t3', 1, 2]], [['t1', 0, 2]], [['a', 0, 6]]]);+ /* moved onto another track at the same time, onto a clip there: it is the one that goes, not the one there */+ const across = model({ role: 'mg', clips: [['x', 1, 3]] }, { role: 'mg', clips: [['y', 0.5, 1.5]] }, { role: 'video', clips: [['a', 0, 6]] });+ const moved = planMove(across, { ids: ['y'], deltaMs: 0, pointerMs: 1000, to: new Map([['y', 0]]), mode: 'overwrite', magnet: true, ...LINK })!;+ assert.deepEqual(after(across, moved).flat().find(([id]) => id === 'x'), ['x', 1, 3]);+ assert.deepEqual(after(across, moved)[0], [['x', 1, 3]]);+});++test('with linkage closing a gap on the main track always closes it whole', () => {+ const m = film([['t', 3, 4]], [['a', 0, 2], ['b', 3, 5]], [['bed', 0, 9]]);+ const gap = gapAt(m, 1, 2500)!;+ const plan = planCloseGap(m, 1, gap, LINK);+ assert.equal(plan.alone, undefined);+ assert.deepEqual(after(m, plan), [[['t', 2, 3]], [['a', 0, 2], ['b', 2, 4]], [['bed', 0, 9]]]);+ /* a gap on a title track closes on that track alone */+ const g2 = gapAt(m, 0, 1000)!;+ assert.deepEqual(after(m, planCloseGap(m, 0, g2, LINK)), [[['t', 0, 1]], [['a', 0, 2], ['b', 3, 5]], [['bed', 0, 9]]]);+});++test('turning the magnet on closes up the main track, before its first clip too, carrying what rides on it', () => {+ const m = film([['t', 6, 7]], [['a', 1, 3], ['b', 5, 8]], [['bed', 0, 9]]);+ const plan = planCloseMainGaps(m, LINK);+ assert.deepEqual(after(m, plan), [[['t', 3, 4]], [['a', 0, 2], ['b', 2, 5]], [['bed', 0, 9]]]);+ assert.deepEqual(planCloseMainGaps(film([], [['a', 0, 2], ['b', 2, 4]]), LINK).ops, [], 'closed up already');+ assert.deepEqual(planCloseMainGaps(model({ role: 'video', locked: true, clips: [['a', 1, 2]] }), LINK).ops, [], 'locked');+});++test('with linkage a slower main-track clip pushes what comes after on every track', () => {+ const m = film([['tb', 3, 4]], [['a', 0, 2], ['b', 2, 5]], [['bed', 0, 9]]);+ const plan = planSpeed(m, ['a'], 0.5, { ripple: true, ...LINK });+ assert.deepEqual(after(m, plan), [[['tb', 5, 6]], [['a', 0, 4], ['b', 4, 7]], [['bed', 0, 9]]]);+});+/* ── insert and overwrite ── */test('an insert goes before or after the clip under the hand, in a gap where it is put, past the end flush', () => {diff --git a/packages/openfilm/studio/ui/src/lib/timeline-edit.ts b/packages/openfilm/studio/ui/src/lib/timeline-edit.tsindex 3944c87..ef9f67a 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-edit.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-edit.ts@@ -8,7 +8,11 @@* · clips on one track never overlap;* · a ripple moves what comes after the edit point on the tracks it reaches: the clips' own tracks and, with sync* lock, every unlocked track, so a voice-over or B-roll stays with the picture it belongs to. Time is closed only- * as far as every one of those tracks has room (`shortMs` says how much could not be), so they never come apart.+ * as far as every one of those tracks has room (`shortMs` says how much could not be), so they never come apart;+ * · with linkage (CapCut's 联动) an edit of the main track (the lowest picture track) carries the clips on the+ * other tracks with the main-track clips they start over (rides). A long clip crossing more than one cut there (a+ * music bed) stays where it is. The main track alone limits it; a clip carried into another on its track goes to+ * a free track nearby (settle).** Pure: the timeline draws a plan's `placed` while the hand is still on a clip, and sends its `ops` on release.*/@@ -52,6 +56,48 @@ export interface EditTrack {export type EditModel = readonly EditTrack[];+/**+ * What a ripple carries besides the tracks edited. `sync` (sync lock, as Premiere): every unlocked track, as far as+ * all of them have room. `linkage` (as CapCut): an edit of the main track carries the clips on every other unlocked+ * track. Sync lock wins when both are on.+ */+export interface Follow { sync: boolean; linkage?: boolean }++/** The main track: the lowest picture track (V1), film.html's last track that is not a sound track. */+export function mainTrackOf(model: readonly Pick<EditTrack, 'index' | 'role'>[]): number | null {+ const pictures = model.filter((t) => t.index >= 0 && t.role !== 'audio');+ return pictures.length ? Math.max(...pictures.map((t) => t.index)) : null;+}++/** Whether the magnet acts on a track: it is CapCut's main-track magnet, so only on the main track. */+export function magnetOn(model: EditModel, track: number | null | undefined, magnet: boolean): boolean {+ return magnet && track != null && track === mainTrackOf(model);+}++/**+ * The main-track clip a clip rides on with linkage: the one its start falls in, or the last when it starts after the+ * main track ends. None in a gap of the main track.+ */+export function hostOf(main: Pick<EditTrack, 'clips'>, clip: { startMs: number }): EditClip | null {+ const on = main.clips.find((c) => clip.startMs >= c.startMs - TOUCH_MS && clip.startMs < c.endMs - TOUCH_MS);+ if (on) return on;+ const last = [...main.clips].sort((a, b) => b.endMs - a.endMs)[0];+ return last && clip.startMs >= last.endMs - TOUCH_MS ? last : null;+}++/**+ * Whether a clip rides on the main track with linkage: it has a host (hostOf) and crosses at most one cut of the main+ * track — a title, a sticker, a sound effect, B-roll over a shot or two. A clip crossing more (a music bed under+ * several shots) belongs to the film's time, not to a shot, and stays where it is.+ */+export function ridesOn(main: Pick<EditTrack, 'clips'>, clip: { startMs: number; endMs: number }): boolean {+ if (!hostOf(main, clip)) return false;+ const cuts = new Set(main.clips.flatMap((c) => [c.startMs, c.endMs]));+ let crossed = 0;+ for (const cut of cuts) if (cut > clip.startMs + TOUCH_MS && cut < clip.endMs - TOUCH_MS) crossed += 1;+ return crossed <= 1;+}+/** Where a track goes: one in film.html, or a new one opened at that place. */export type TrackDest = number | { insert: number };@@ -115,6 +161,10 @@ export interface Draft {/** The right half cut off a clip, by the clip's id. */cut: Map<string, EditClip>;shortMs: number;+ /** Linkage carried clips without asking their tracks for room: some may now run into another (see settle). */+ settle?: boolean;+ /** With linkage, the clips on other tracks that do not ride on the main track (ridesOn, as the film was). */+ anchored?: Set<string>;}function draftOf(model: EditModel): Draft {@@ -133,6 +183,16 @@ const tailRoomOf = (c: EditClip): number => (c.still || !Number.isFinite(c.sourceMs) ? Infinity : Math.max(0, (c.sourceMs - srcEndOf(c)) / c.speed));+/**+ * How much more of its source a clip can show at one edge, in film ms: how far that edge can still be pulled out.+ * Infinity for a still or a source with no end; undefined for a clip not in the model.+ */+export function sourceLeftMs(model: EditModel, id: string, edge: 'start' | 'end'): number | undefined {+ const c = model.flatMap((t) => t.clips).find((x) => x.id === id);+ if (!c) return undefined;+ return edge === 'start' ? headRoomOf(c) : tailRoomOf(c);+}+function trackAt(d: Draft, index: number): EditTrack | undefined {return d.tracks.find((t) => t.index === index);}@@ -162,6 +222,32 @@ function reach(d: Draft, edited: Iterable<number>, sync: boolean): number[] {return d.tracks.filter((t) => set.has(t.index) && !t.locked).map((t) => t.index);}+/**+ * The tracks a ripple moves (`tracks`) and those whose room limits it (`bound`): with sync lock every unlocked track+ * both moves and limits; with linkage an edit of the main track moves every unlocked track, limited by the tracks+ * edited alone; else just the tracks edited.+ */+function follow(d: Draft, edited: Iterable<number>, opts: Follow): { tracks: number[]; bound: number[] } {+ const own = reach(d, edited, false);+ if (opts.sync) {+ const all = reach(d, [], true);+ return { tracks: all, bound: all };+ }+ const main = mainTrackOf(d.tracks);+ if (opts.linkage && main != null && own.includes(main)) {+ d.anchored ??= anchoredOf(d, main);+ return { tracks: reach(d, [], true), bound: own };+ }+ return { tracks: own, bound: own };+}++/** The clips on other tracks that stay put with linkage (they do not ride on the main track as it was). */+function anchoredOf(d: Draft, main: number): Set<string> {+ const was = [...d.before.values()];+ const mainWas = { clips: was.filter((x) => x.track === main).map((x) => x.clip) };+ return new Set(was.filter((x) => x.track !== main && !ridesOn(mainWas, x.clip)).map((x) => x.clip.id));+}+/*** How far left what starts at or after `point` on a track can go before it meets what stays (what starts before it).* Infinity when nothing starts after it.@@ -181,38 +267,57 @@ function roomBefore(track: EditTrack, point: number, skip?: ReadonlySet<string>)* Move what starts at or after `point` by `deltaMs` on these tracks. Leftwards only as far as every track has room;* the time that could not be closed is added to `shortMs`. Returns the shift made.*/-function rippleAt(d: Draft, point: number, deltaMs: number, tracks: readonly number[], skip?: ReadonlySet<string>): number {+function rippleAt(+ d: Draft,+ point: number,+ deltaMs: number,+ tracks: readonly number[],+ skip?: ReadonlySet<string>,+ bound: readonly number[] = tracks,+): number {const rows = tracks.map((i) => trackAt(d, i)).filter((t): t is EditTrack => Boolean(t && !t.locked));+ const limits = rows.filter((t) => bound.includes(t.index));let amount = deltaMs;if (amount < 0) {- const room = Math.min(...rows.map((t) => roomBefore(t, point, skip)));+ const room = Math.min(...limits.map((t) => roomBefore(t, point, skip)));if (-amount > room) {d.shortMs += -amount - room;amount = -room;}}if (!amount) return 0;+ if (limits.length < rows.length) d.settle = true;for (const t of rows) {- for (const c of t.clips) if (!skip?.has(c.id) && c.startMs >= point - TOUCH_MS) shiftClip(c, amount);+ /* the tracks carried along (linkage): what does not ride on the main track stays */+ const still = limits.includes(t) ? undefined : d.anchored;+ for (const c of t.clips) {+ if (!skip?.has(c.id) && !still?.has(c.id) && c.startMs >= point - TOUCH_MS) shiftClip(c, amount);+ }}return amount;}/**- * Close spans of time: per track its own (`byTrack`), or with sync lock all of them merged, on every track. From the- * last span back, so closing one does not move the ones before it. Returns the shifts made, for mapping a time from- * before to after (see mapThrough).+ * Close spans of time: per track its own (`byTrack`), or with sync lock all of them merged, on every track; with+ * linkage, when the main track has spans, those, carrying every unlocked track. From the last span back, so closing+ * one does not move the ones before it. Returns the shifts made, for mapping a time from before to after (see+ * mapThrough).*/interface Shift { point: number; amount: number; tracks: readonly number[] }-function closeSpans(d: Draft, byTrack: ReadonlyMap<number, { startMs: number; endMs: number }[]>, sync: boolean): Shift[] {+function closeSpans(d: Draft, byTrack: ReadonlyMap<number, { startMs: number; endMs: number }[]>, opts: Follow): Shift[] {const shifts: Shift[] = [];- const groups: { spans: { startMs: number; endMs: number }[]; tracks: number[] }[] = sync- ? [{ spans: [...byTrack.values()].flat(), tracks: reach(d, [], true) }]- : [...byTrack.entries()].map(([t, spans]) => ({ spans, tracks: reach(d, [t], false) }));+ const main = mainTrackOf(d.tracks);+ const onMain = main != null ? byTrack.get(main) : undefined;+ type Group = { spans: { startMs: number; endMs: number }[]; tracks: number[]; bound: number[] };+ const groups: Group[] = opts.sync+ ? [{ spans: [...byTrack.values()].flat(), ...follow(d, [], opts) }]+ : opts.linkage && onMain && !trackAt(d, main!)?.locked+ ? [{ spans: onMain, ...follow(d, [main!], opts) }]+ : [...byTrack.entries()].map(([t, spans]) => ({ spans, ...follow(d, [t], { sync: false }) }));for (const group of groups) {if (!group.tracks.length) continue;for (const span of mergeSpans(group.spans).reverse()) {- const amount = rippleAt(d, span.endMs, -(span.endMs - span.startMs), group.tracks);+ const amount = rippleAt(d, span.endMs, -(span.endMs - span.startMs), group.tracks, undefined, group.bound);if (amount) shifts.push({ point: span.endMs, amount, tracks: group.tracks });}}@@ -344,7 +449,96 @@ function changedFields(was: EditClip, now: EditClip): Record<string, PropValue>return out;}+const overlap = (a: { startMs: number; endMs: number }, b: { startMs: number; endMs: number }): boolean => (+ a.startMs < b.endMs - TOUCH_MS && a.endMs > b.startMs + TOUCH_MS+);++/**+ * Clips carried (linkage) or put (the magnet, off the main track) into another clip on their track go to another+ * track: the one that moved goes, the one that stayed stays. Where: the nearest unlocked track of their kind with room+ * (above for a picture, below for a sound), not the main track; else a new track opened beside theirs.+ */+function settle(d: Draft): void {+ const main = mainTrackOf(d.tracks);+ const moved = (c: EditClip, on: EditTrack): boolean => {+ const was = d.before.get(c.id);+ return !was || was.track !== on.index || Math.abs(was.clip.startMs - c.startMs) >= 0.5;+ };+ const relocate = (from: EditTrack, c: EditClip): void => {+ const free = nearestFree(d.tracks, from, c);+ if (free) {+ free.clips.push(c);+ return;+ }+ const insert = newTrackBeside(from);+ d.opened.set(c.id, insert);+ let opened = d.tracks.find((t) => t.index === -1 - insert);+ if (!opened) {+ opened = { index: -1 - insert, clips: [], ...(from.role ? { role: from.role } : {}) };+ d.tracks.push(opened);+ }+ opened.clips.push(c);+ };+ for (const t of [...d.tracks]) {+ if (t.index < 0 || t.index === main || t.locked) continue;+ const kept: EditClip[] = [];+ for (const c of [...t.clips].sort((a, b) => a.startMs - b.startMs)) {+ const hits = kept.filter((k) => overlap(k, c));+ if (!hits.length) {+ kept.push(c);+ continue;+ }+ const go = moved(c, t) || hits.some((h) => !moved(h, t)) ? [c] : hits;+ for (const x of go) {+ t.clips.splice(t.clips.indexOf(x), 1);+ if (kept.includes(x)) kept.splice(kept.indexOf(x), 1);+ relocate(t, x);+ }+ if (!go.includes(c)) kept.push(c);+ }+ }+}++/**+ * The nearest unlocked track of the same kind as `from` (sound or picture) with `span` free, not the main track and+ * not `from`: above for a picture, below for a sound at the same distance. Undefined when none has room.+ */+type Lane = Pick<EditTrack, 'index' | 'role' | 'locked'> & { clips: readonly { startMs: number; endMs: number }[] };+function nearestFree<T extends Lane>(tracks: readonly T[], from: Lane, span: { startMs: number; endMs: number }): T | undefined {+ const main = mainTrackOf(tracks);+ const sound = (t: Lane) => t.role === 'audio';+ return tracks+ .filter((t) => t !== from && t.index >= 0 && t.index !== main && !t.locked && sound(t) === sound(from))+ .filter((t) => !t.clips.some((x) => overlap(x, span)))+ .sort((a, b) => {+ const away = Math.abs(a.index - from.index) - Math.abs(b.index - from.index);+ return away || (sound(from) ? b.index - a.index : a.index - b.index);+ })[0];+}++/** Where a track opened for a clip that found no room goes: above a picture track, below a sound track. */+const newTrackBeside = (from: Lane): number => (from.role === 'audio' ? from.index + 1 : from.index);++/**+ * Where a clip put on a track off the main track goes with the magnet, as CapCut's: covering nothing. That track+ * when the time is free there, else the nearest free track of its kind (nearestFree), else a new track beside it.+ * `taken`: what has been put already in the same edit (on existing tracks).+ */+export function freeTrackFor(+ model: EditModel,+ track: number,+ span: { startMs: number; endMs: number },+ taken: readonly { track: number; startMs: number; endMs: number }[] = [],+): TrackDest {+ const tracks: Lane[] = model.map((t) => ({ ...t, clips: [...t.clips, ...taken.filter((x) => x.track === t.index)] }));+ const own = tracks.find((t) => t.index === track);+ if (!own) return track;+ if (!own.clips.some((c) => overlap(c, span))) return track;+ return nearestFree(tracks, own, span)?.index ?? { insert: newTrackBeside(own) };+}+function planOf(d: Draft): EditPlan {+ if (d.settle) settle(d);relinkCuts(d);const ops: Op[] = [];const edits: { clip: string; prop: string; value: PropValue }[] = [];@@ -385,7 +579,7 @@ function planOf(d: Draft): EditPlan {}/* the draft's own steps, for edits planned elsewhere (lib/transitions) */-export { draftOf, find as findInDraft, planOf, reach, rippleAt, trackAt };+export { draftOf, find as findInDraft, follow, planOf, reach, rippleAt, trackAt };/** An edit that changes nothing. */export function emptyPlan(): EditPlan {@@ -452,11 +646,43 @@ export function gapAt(model: EditModel, track: number, ms: number): { startMs: nreturn endMs - startMs > TOUCH_MS ? { startMs, endMs } : null;}-/** Close a gap: what comes after it moves back, on its track and, with sync lock, every unlocked track. */-export function planCloseGap(model: EditModel, track: number, gap: { startMs: number; endMs: number }, opts: { sync: boolean }): EditPlan {+/**+ * Close a gap: what comes after it moves back, on its track and, with sync lock, every unlocked track. A gap picked+ * is closed whole: when a synced track has no room for it (a clip there spans the gap's end), it closes on its own+ * track alone, and `alone` says so.+ */+export function planCloseGap(+ model: EditModel,+ track: number,+ gap: { startMs: number; endMs: number },+ opts: Follow,+): EditPlan & { alone?: boolean } {const d = draftOf(model);if (trackAt(d, track)?.locked) return emptyPlan();- closeSpans(d, new Map([[track, [gap]]]), opts.sync);+ closeSpans(d, new Map([[track, [gap]]]), opts);+ if (!opts.sync || d.shortMs <= 0) return planOf(d);+ const alone = draftOf(model);+ closeSpans(alone, new Map([[track, [gap]]]), { sync: false });+ return { ...planOf(alone), alone: true };+}++/**+ * The main track closed up, as CapCut does when its magnet is turned on: every gap on it, before its first clip too,+ * closes, carrying what follows as a ripple does (sync lock, linkage). Nothing on a locked main track.+ */+export function planCloseMainGaps(model: EditModel, opts: Follow): EditPlan {+ const main = mainTrackOf(model);+ const track = model.find((t) => t.index === main);+ if (main == null || !track || track.locked) return emptyPlan();+ const spans: { startMs: number; endMs: number }[] = [];+ let end = 0;+ for (const c of [...track.clips].sort((a, b) => a.startMs - b.startMs)) {+ if (c.startMs - end > TOUCH_MS) spans.push({ startMs: end, endMs: c.startMs });+ end = Math.max(end, c.endMs);+ }+ if (!spans.length) return emptyPlan();+ const d = draftOf(model);+ closeSpans(d, new Map([[main, spans]]), opts);return planOf(d);}@@ -464,19 +690,23 @@ export function planCloseGap(model: EditModel, track: number, gap: { startMs: nu/*** Delete clips. With `ripple` the time they took closes after them (each track its own, or with sync lock all the- * deleted time on every unlocked track); without, they leave a gap. Clips on locked tracks stay.+ * deleted time on every unlocked track, or with linkage the main track's, carrying the other tracks); `'main'` closes+ * only the main track's (the magnet), the others leave a gap; without, they all leave a gap. Clips on locked tracks+ * stay.*/-export function planRemove(model: EditModel, ids: readonly string[], opts: { ripple: boolean; sync: boolean }): EditPlan {+export function planRemove(model: EditModel, ids: readonly string[], opts: Follow & { ripple: boolean | 'main' }): EditPlan {const d = draftOf(model);+ const main = mainTrackOf(model);const spans = new Map<number, { startMs: number; endMs: number }[]>();for (const t of d.tracks) {if (t.locked) continue;const gone = t.clips.filter((c) => ids.includes(c.id));if (!gone.length) continue;t.clips = t.clips.filter((c) => !ids.includes(c.id));+ if (opts.ripple === 'main' && t.index !== main) continue;spans.set(t.index, gone.map((c) => ({ startMs: c.startMs, endMs: c.endMs })));}- if (opts.ripple && spans.size) closeSpans(d, spans, opts.sync);+ if (opts.ripple && spans.size) closeSpans(d, spans, opts);return planOf(d);}@@ -509,7 +739,7 @@ export function insertPointOn(model: EditModel, track: number, pointerMs: numberexport function planRoom(model: EditModel,spans: readonly { track: number; startMs: number; endMs: number }[],- opts: { mode: EditMode; sync: boolean },+ opts: Follow & { mode: EditMode },): EditPlan {const d = draftOf(model);if (spans.some((s) => trackAt(d, s.track)?.locked)) return emptyPlan();@@ -531,7 +761,8 @@ export function planRoom(if (!track) continue;for (const c of [...track.clips]) cutAt(d, track, c, at);}- rippleAt(d, at, durMs, reach(d, dests, opts.sync));+ const f = follow(d, dests, opts);+ rippleAt(d, at, durMs, f.tracks, undefined, f.bound);return planOf(d);}@@ -548,12 +779,21 @@ export interface MoveSpec {to?: ReadonlyMap<string, TrackDest>;mode: EditMode;sync: boolean;+ linkage?: boolean;+ /**+ * The main-track magnet. Given, the time clips leave on the main track closes up when it is on (wherever they land),+ * and the time they leave on other tracks stays open; an overwrite off the main track covers nothing then: a clip+ * landing on another goes to a free track (settle), as CapCut's. Not given, an insert closes the time they leave+ * everywhere and an overwrite covers what is there.+ */+ magnet?: boolean;}/*** Clips moved. Overwrite: they land where they were let go and take that time off the tracks they land on. Insert:* they are lifted out (the time they took closes, as a ripple delete) and go in at the insert point of the track the- * grabbed one lands on, pushing what comes after on (as an insert). A new track takes them as they are.+ * grabbed one lands on, pushing what comes after on (as an insert). A new track takes them as they are. With linkage,+ * main-track clips moved along the main track take the clips riding on them (hostOf) along.* Null when a track it would change is locked.*/export function planMove(model: EditModel, spec: MoveSpec): (EditPlan & { landMs: number }) | null {@@ -568,6 +808,21 @@ export function planMove(model: EditModel, spec: MoveSpec): (EditPlan & { landMsif (trackAt(d, d.before.get(id)!.track)?.locked) return null;if (typeof dest === 'number' && (!trackAt(d, dest) || trackAt(d, dest)!.locked)) return null;}+ /* with linkage, what rides on main-track clips that stay on the main track goes with them: taken off too */+ const mainIndex = mainTrackOf(model);+ const mainTrack = mainIndex != null ? trackAt(d, mainIndex) : undefined;+ const riders = new Map<EditClip, { track: EditTrack; host: string }>();+ if (spec.linkage && !spec.sync && mainTrack && !mainTrack.locked) {+ const hosts = new Set(mainTrack.clips.filter((c) => hand.has(c.id) && destOf(c.id) === mainIndex).map((c) => c.id));+ for (const t of d.tracks) {+ if (t === mainTrack || t.locked || !hosts.size) continue;+ for (const c of t.clips) {+ const host = hand.has(c.id) || !ridesOn(mainTrack, c) ? null : hostOf(mainTrack, c);+ if (host && hosts.has(host.id)) riders.set(c, { track: t, host: host.id });+ }+ }+ for (const [c, r] of riders) r.track.clips.splice(r.track.clips.indexOf(c), 1);+ }/* take them off their tracks */const lifted = new Map<string, EditClip>();const spans = new Map<number, { startMs: number; endMs: number }[]>();@@ -586,8 +841,12 @@ export function planMove(model: EditModel, spec: MoveSpec): (EditPlan & { landMsconst minOffset = Math.min(...[...lifted.values()].map(offset));landMs = Math.max(landMs, -minOffset);- /* an insert lifts them out: the time they took closes, as a ripple delete */- const shifts = spec.mode === 'insert' ? closeSpans(d, spans, spec.sync) : [];+ /* an insert lifts them out: the time they took closes, as a ripple delete (with the magnet given: on the main+ track, when it is on) */+ const closing = spec.magnet === undefined+ ? (spec.mode === 'insert' ? spans : null)+ : spec.magnet && mainIndex != null && spans.has(mainIndex) ? new Map([[mainIndex, spans.get(mainIndex)!]]) : null;+ const shifts = closing ? closeSpans(d, closing, spec) : [];if (spec.mode === 'insert' && typeof mainDest === 'number') {/* the insert point, worked out on the track as it was (where the hand is), then carried through the lift */const point = insertPointOn(model, mainDest, spec.pointerMs, landMs, hand);@@ -600,7 +859,8 @@ export function planMove(model: EditModel, spec: MoveSpec): (EditPlan & { landMsconst track = trackAt(d, index);if (track) for (const c of [...track.clips]) cutAt(d, track, c, at);}- rippleAt(d, at, durMs, reach(d, dests, spec.sync));+ const f = follow(d, dests, spec);+ rippleAt(d, at, durMs, f.tracks, undefined, f.bound);}/* put them down */@@ -620,12 +880,21 @@ export function planMove(model: EditModel, spec: MoveSpec): (EditPlan & { landMscontinue;}const track = trackAt(d, dest)!;- if (spec.mode === 'overwrite') {+ if (spec.mode === 'overwrite' && spec.magnet && dest !== mainIndex) {+ d.settle = true;+ } else if (spec.mode === 'overwrite') {clearLinked(d, [dest], c.startMs, c.endMs, hand);clearRange(d, track, c.startMs, c.endMs, hand);}track.clips.push(c);}+ /* the riders, where their clip went */+ for (const [c, r] of riders) {+ const host = lifted.get(r.host)!;+ shiftClip(c, host.startMs - d.before.get(r.host)!.clip.startMs);+ r.track.clips.push(c);+ d.settle = true;+ }const plan = planOf(d);return { ...plan, landMs };}@@ -708,7 +977,7 @@ export function planRippleTrim(ids: readonly string[],edge: 'start' | 'end',deltaMs: number,- opts: { sync: boolean },+ opts: Follow,): EditPlan & { deltaMs: number } {const d = draftOf(model);const parts = ids.map((id) => find(d, id)).filter((x): x is { track: EditTrack; clip: EditClip } => Boolean(x && !x.track.locked));@@ -721,10 +990,10 @@ export function planRippleTrim(grow = Math.min(grow, edge === 'end' ? tailRoomOf(clip) : headRoomOf(clip));}const point = main.clip.endMs;- const tracks = reach(d, parts.map((p) => p.track.index), opts.sync);+ const { tracks, bound } = follow(d, parts.map((p) => p.track.index), opts);const skip = new Set(parts.map((p) => p.clip.id));if (grow < 0) {- const room = Math.min(...tracks.map((i) => roomBefore(trackAt(d, i)!, point, skip)));+ const room = Math.min(...bound.map((i) => roomBefore(trackAt(d, i)!, point, skip)));grow = Math.max(grow, -room);}if (!grow) return { ...planOf(d), deltaMs: 0 };@@ -732,7 +1001,7 @@ export function planRippleTrim(if (edge === 'start' && !clip.still) clip.inMs = Math.max(0, clip.inMs - grow * clip.speed);clip.endMs += grow;}- rippleAt(d, point, grow, tracks, skip);+ rippleAt(d, point, grow, tracks, skip, bound);return { ...planOf(d), deltaMs: edge === 'end' ? grow : -grow };}@@ -740,7 +1009,7 @@ export function planRippleTrim(* Ripple trim to the playhead (Q and W): `start` takes off the head up to `atMs`, `end` the tail from it, and what* comes after closes up. Null when `atMs` is not inside the first clip.*/-export function planRippleTrimTo(model: EditModel, ids: readonly string[], edge: 'start' | 'end', atMs: number, opts: { sync: boolean }): EditPlan | null {+export function planRippleTrimTo(model: EditModel, ids: readonly string[], edge: 'start' | 'end', atMs: number, opts: Follow): EditPlan | null {const main = model.flatMap((t) => t.clips).find((c) => c.id === ids[0]);if (!main || !(atMs > main.startMs + TOUCH_MS && atMs < main.endMs - TOUCH_MS)) return null;const plan = planRippleTrim(model, ids, edge, edge === 'start' ? atMs - main.startMs : atMs - main.endMs, opts);@@ -804,7 +1073,7 @@ export function planSpeed(model: EditModel,ids: readonly string[],speed: number,- opts: { ripple: boolean; sync: boolean },+ opts: Follow & { ripple: boolean },): EditPlan & { slowest?: number } {const d = draftOf(model);const parts = ids.map((id) => find(d, id)).filter((x): x is { track: EditTrack; clip: EditClip } => Boolean(x && !x.track.locked && !x.clip.still));@@ -829,13 +1098,13 @@ export function planSpeed(}const point = main.clip.endMs;const by = grow(main.clip);- const tracks = reach(d, parts.map((p) => p.track.index), opts.sync);+ const { tracks, bound } = follow(d, parts.map((p) => p.track.index), opts);const skip = new Set(parts.map((p) => p.clip.id));for (const { clip } of parts) {clip.endMs += grow(clip);clip.speed = speed;}- rippleAt(d, point, by, tracks, skip);+ rippleAt(d, point, by, tracks, skip, bound);return planOf(d);}diff --git a/packages/openfilm/studio/ui/src/lib/timeline-nav.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-nav.test.tsindex aa847bb..138535c 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-nav.test.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-nav.test.ts@@ -30,7 +30,7 @@ test('the cuts ↑ / ↓ go to: every clip edge on tracks seen and not locked, oassert.equal(nextCut(points, 0, -1), null);});-test('⌘B splits the selected clips under the playhead, else the targeted track\'s, else the top one seen', () => {+test('⌘B splits the selected clips under the playhead, else the main track\'s, else the targeted track\'s, else the top one seen', () => {const tracks = [row(0, [['top', 0, 4]], { hidden: true }),row(1, [['v', 0, 4]]),@@ -40,9 +40,12 @@ test('⌘B splits the selected clips under the playhead, else the targeted trackconst ids = (bs: TimelineBlock[]) => bs.map((b) => b.clipId);assert.deepEqual(ids(splitTargets(tracks, ['b-s', 'b-s2', 'b-locked'], 2000, null)), ['s'], 'selected and under it, not locked');assert.deepEqual(ids(splitTargets(tracks, ['b-s2'], 2000, null)), [], 'a selection the playhead is not over: nothing');- assert.deepEqual(ids(splitTargets(tracks, [], 2000, 'doc-3')), ['s']);- assert.deepEqual(ids(splitTargets(tracks, [], 2000, 'doc-2')), [], 'a locked target: nothing');- assert.deepEqual(ids(splitTargets(tracks, [], 2000, null)), ['v'], 'hidden tracks are passed over');+ assert.deepEqual(ids(splitTargets(tracks, [], 2000, 'doc-1')), ['s'], 'the main track before the targeted one');+ /* no main-track clip to split (its track locked): the targeted track's, and a locked target splits nothing */+ assert.deepEqual(ids(splitTargets(tracks.slice(0, 3), [], 2000, 'doc-1')), ['v']);+ assert.deepEqual(ids(splitTargets(tracks.slice(0, 3), [], 2000, 'doc-2')), [], 'a locked target: nothing');+ assert.deepEqual(ids(splitTargets(tracks, [], 2000, null)), ['s'], 'the main track: the lowest picture track');+ assert.deepEqual(ids(splitTargets(tracks.slice(0, 3), [], 2000, null)), ['v'], 'a locked main track: the top one seen, not a hidden one');assert.deepEqual(ids(splitTargets(tracks, [], 4000, null)), [], 'on a cut there is nothing to split');assert.deepEqual(ids(splitAllTargets(tracks, 2000)), ['top', 'v', 's']);});diff --git a/packages/openfilm/studio/ui/src/lib/timeline-nav.ts b/packages/openfilm/studio/ui/src/lib/timeline-nav.tsindex e9ab74e..29d1450 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-nav.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-nav.ts@@ -42,8 +42,9 @@ const lockedRows = (tracks: readonly TimelineTrack[]) => new Set(tracks.filter((/*** What ⌘B splits at the playhead: the selected clips it is inside; with nothing selected, the clip it is inside on the- * targeted track (`targetLane`), else on the topmost track that is seen and has one. Never a clip on a locked track.- * The clips linked to them are the caller's to add (the Linked switch).+ * main track (the lowest picture track), as CapCut; else on the targeted track (`targetLane`), else on the topmost+ * track that is seen and has one. Never a clip on a locked track. The clips linked to them are the caller's to add+ * (the Linked switch).*/export function splitTargets(tracks: readonly TimelineTrack[],@@ -54,6 +55,10 @@ export function splitTargets(const locked = lockedRows(tracks);const can = (b: TimelineBlock) => Boolean(b.loc && b.clipId) && !locked.has(b.id) && splitsAt(b, atMs);if (selectedIds.length) return tracks.flatMap((tr) => tr.blocks).filter((b) => selectedIds.includes(b.id) && can(b));+ const pictures = tracks.filter((tr) => tr.docIndex != null && tr.role !== 'audio');+ const mainIndex = pictures.length ? Math.max(...pictures.map((tr) => tr.docIndex!)) : null;+ const main = tracks.filter((tr) => tr.docIndex === mainIndex && !tr.hidden).flatMap((tr) => tr.blocks).find(can);+ if (main) return [main];const target = targetLane ? tracks.find((tr) => tr.lane === targetLane) : undefined;if (target) {const hit = target.blocks.find(can);diff --git a/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts b/packages/openfilm/studio/ui/src/lib/timeline-prefs.tsindex 3dcb404..6377d6b 100644--- a/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts+++ b/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts@@ -2,10 +2,14 @@* The timeline's switches, kept on this machine across projects:* · `snap` (on by default, as in CapCut, Premiere and OpenCut): drags line up with edges and the playhead; off means* "it lands exactly where I let go";- * · `magnet` (off by default, as Premiere's overwrite): on, a track behaves like CapCut's main track — a clip put- * down inserts and pushes what follows, a delete closes the gap, a trim ripples; off, a clip put down over others- * overwrites them;- * · `sync` (sync lock, on): a ripple moves every unlocked track along, so sound and B-roll stay with their picture;+ * · `magnet` (on by default, as CapCut's main-track magnet): the main track (the lowest picture track) stays closed+ * up — a clip put down on it inserts and pushes what follows, a delete or a clip taken off it closes the gap, a+ * trim ripples. Other tracks never: a clip put down there overwrites, a delete leaves a gap. Off, the main track+ * is like the others;+ * · `linkage` (on, as CapCut's 联动): an edit of the main track carries the clips on the other tracks along with+ * the main-track clips they start over, so titles, B-roll and sound stay with their picture;+ * · `sync` (sync lock, off; as Premiere): a ripple on any track moves every unlocked track along, as far as all of+ * them have room. It wins over linkage when both are on;* · `linked` (on): clips sharing a `data-link` (a video and its detached sound) are selected and edited together.** The inspector reads them too (a slower speed pushes the next clip only with the magnet on), so a change is told to@@ -13,14 +17,17 @@*/import { useSyncExternalStore } from 'react';-export type TimelinePrefs = { snap: boolean; magnet: boolean; sync: boolean; linked: boolean };+export type TimelinePrefs = { snap: boolean; magnet: boolean; linkage: boolean; sync: boolean; linked: boolean };type Pref = keyof TimelinePrefs;-const DEFAULTS: TimelinePrefs = { snap: true, magnet: false, sync: true, linked: true };+const DEFAULTS: TimelinePrefs = { snap: true, magnet: true, linkage: true, sync: false, linked: true };const KEY: Record<Pref, string> = {snap: 'openfilm.timeline.snap',- magnet: 'openfilm.timeline.magnet',- sync: 'openfilm.timeline.sync',+ /* new keys: the magnet now acts on the main track alone, and sync lock gave way to linkage, so the choices made+ for the old switches do not carry over */+ magnet: 'openfilm.timeline.mainMagnet',+ linkage: 'openfilm.timeline.linkage',+ sync: 'openfilm.timeline.syncLock',linked: 'openfilm.timeline.linked',};@@ -38,7 +45,7 @@ function read(pref: Pref): boolean {}export function readTimelinePrefs(): TimelinePrefs {- current ??= { snap: read('snap'), magnet: read('magnet'), sync: read('sync'), linked: read('linked') };+ current ??= { snap: read('snap'), magnet: read('magnet'), linkage: read('linkage'), sync: read('sync'), linked: read('linked') };return current;}@@ -60,3 +67,8 @@ function subscribe(fn: () => void): () => void {export function useTimelinePrefs(): TimelinePrefs {return useSyncExternalStore(subscribe, readTimelinePrefs, () => DEFAULTS);}++/** What a ripple carries along (timeline-edit Follow), from the switches. */+export function followOf(prefs: Pick<TimelinePrefs, 'sync' | 'linkage'>): { sync: boolean; linkage: boolean } {+ return { sync: prefs.sync, linkage: prefs.linkage };+}diff --git a/packages/openfilm/studio/ui/src/lib/transitions.ts b/packages/openfilm/studio/ui/src/lib/transitions.tsindex 524d930..e076e7d 100644--- a/packages/openfilm/studio/ui/src/lib/transitions.ts+++ b/packages/openfilm/studio/ui/src/lib/transitions.ts@@ -30,7 +30,7 @@*/import type { Op, PropValue } from '../api.ts';import {- TOUCH_MS, draftOf, findInDraft, linkedIds, planOf, reach, rippleAt, trackAt,+ TOUCH_MS, draftOf, findInDraft, follow, linkedIds, planOf, rippleAt, trackAt,type Draft, type EditClip, type EditModel, type EditTrack, type TrackDest,} from './timeline-edit.ts';@@ -84,9 +84,11 @@ export function transitionSpan(tr: FilmTransition, durationMs: number): { startM}export interface TransitionOpts {- /** The magnet: an overlap closes up what follows, removing one opens it again. */+ /** The magnet on the cut's track: an overlap closes up what follows, removing one opens it again. */ripple: boolean;sync: boolean;+ /** Linkage (timeline-edit Follow): a ripple on the main track carries the other tracks. */+ linkage?: boolean;/** Linked clips go with each other (the Linked switch, unless ⌥). */linked: boolean;/** The white page's path (dip to white). */@@ -190,6 +192,19 @@ const free = (track: EditTrack, startMs: number, endMs: number, skip: ReadonlySe(c) => !skip.has(c.id) && c.startMs < endMs - TOUCH_MS && c.endMs > startMs + TOUCH_MS,);+/** A ripple from a transition's edit, carrying what sync lock or linkage carries (timeline-edit follow). */+function rippleThrough(+ d: Draft,+ point: number,+ deltaMs: number,+ edited: Iterable<number>,+ opts: TransitionOpts,+ skip?: ReadonlySet<string>,+): void {+ const f = follow(d, edited, opts);+ rippleAt(d, point, deltaMs, f.tracks, skip, f.bound);+}+function fadeOf(fades: Fades, facts: FactsOf, id: string): [number, number] {const had = fades.get(id) ?? facts(id)?.fade ?? [0, 0];return [had[0], had[1]];@@ -318,7 +333,7 @@ export function planTransition(model: EditModel, facts: FactsOf, kind: Transitiothen put down d earlier where there is room (see landing) */const against = new Map(moving.map((m) => [m.clip.id, partnerTrack(d, facts, m.clip, m.clip.startMs, skip) ?? m.track.index]));for (const m of moving) m.track.clips = m.track.clips.filter((c) => c.id !== m.clip.id);- if (opts.ripple) rippleAt(d, cutMs, -overlap, reach(d, homes, opts.sync));+ if (opts.ripple) rippleThrough(d, cutMs, -overlap, homes, opts);for (const m of moving) {m.clip.startMs -= overlap;m.clip.endMs -= overlap;@@ -369,7 +384,7 @@ export function planRemoveTransition(model: EditModel, facts: FactsOf, tr: FilmT/* where each goes back to: against the clip it overlaps, on that one's track */const homes = moving.map((m) => ({ m, home: partnerTrack(d, facts, m.clip, m.clip.startMs + back, skip) }));const reached = new Set([a.track.index, ...homes.flatMap((h) => (h.home != null ? [h.home] : []))]);- if (opts.ripple) rippleAt(d, a.clip.endMs, back, reach(d, reached, opts.sync), skip);+ if (opts.ripple) rippleThrough(d, a.clip.endMs, back, reached, opts, skip);for (const { m, home } of homes) {m.clip.startMs += back;m.clip.endMs += back;@@ -425,7 +440,7 @@ export function planResizeTransition(model: EditModel, facts: FactsOf, tr: FilmTconst delta = want - now;if (Math.abs(delta) < 0.5) return { ops: [], shortMs: 0 };for (const m of moving) { m.clip.startMs -= delta; m.clip.endMs -= delta; }- if (opts.ripple) rippleAt(d, a.clip.endMs, -delta, reach(d, [a.track.index], opts.sync), skip);+ if (opts.ripple) rippleThrough(d, a.clip.endMs, -delta, [a.track.index], opts, skip);for (const c of outgoing) setFade(fades, facts, c, 'out', holds(d, facts, c.id, tr.b) ? 0 : want);for (const c of incoming) setFade(fades, facts, c, 'in', want);return opsOf(d, fades);diff --git a/packages/openfilm/studio/ui/src/lib/workspace-resources.test.ts b/packages/openfilm/studio/ui/src/lib/workspace-resources.test.tsindex b9db46b..88eddfc 100644--- a/packages/openfilm/studio/ui/src/lib/workspace-resources.test.ts+++ b/packages/openfilm/studio/ui/src/lib/workspace-resources.test.ts@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { formatClipDuration, mediaNameMatches, renameChangesKind, renamedPath, safeName } from './workspace-resources.ts';+import { formatClipDuration, mediaListingOf, mediaNameMatches, renameChangesKind, renamedPath, safeName } from './workspace-resources.ts';test('names keep spaces and every script; only what file systems refuse goes (the server’s rule, files.mjs)', () => {assert.equal(safeName('镜头 01.mp4'), '镜头 01.mp4');@@ -42,3 +42,26 @@ test('the media search ignores case and runs of spaces', () => {assert.equal(mediaNameMatches('longtone.mp3', 'long tone'), false);assert.equal(mediaNameMatches('anything', ' '), true);});++test('a page put in a folder of the media pane is a page still, named as pages are; another file is "other"', () => {+ const listing = mediaListingOf({+ files: [+ { path: 'assets/test/02-cards.html', kind: 'page', size: 1100, mtime: 1 },+ { path: 'assets/test/brief.pdf', kind: 'other', size: 9, mtime: 1 },+ ],+ folders: ['assets/test'],+ pages: [],+ });+ assert.deepEqual(listing.files.map((f) => [f.name, f.kind, f.dir]), [['02-cards', 'mg', 'test'], ['brief.pdf', 'other', 'test']]);+});++test('links to media kept elsewhere ride on their files and folders', () => {+ const listing = mediaListingOf({+ files: [{ path: 'assets/nas/take.mp4', kind: 'video', size: 9, mtime: 1 }, { path: 'assets/off.png', kind: 'image', size: 0, mtime: 1 }],+ folders: ['assets/nas'],+ pages: [],+ links: { 'assets/nas': { to: '/Volumes/NAS/shoot' }, 'assets/off.png': { to: '/Volumes/NAS/off.png', missing: true } },+ });+ assert.deepEqual(listing.linkedDirs, { nas: { to: '/Volumes/NAS/shoot' } });+ assert.deepEqual(listing.files.map((f) => f.link ?? null), [null, { to: '/Volumes/NAS/off.png', missing: true }]);+});diff --git a/packages/openfilm/studio/ui/src/lib/workspace-resources.ts b/packages/openfilm/studio/ui/src/lib/workspace-resources.tsindex 8ebad8f..30a6102 100644--- a/packages/openfilm/studio/ui/src/lib/workspace-resources.ts+++ b/packages/openfilm/studio/ui/src/lib/workspace-resources.ts@@ -29,12 +29,23 @@ export interface WorkspaceResource {durationMs?: number;/** A web page without a duration: it has no end, so on the timeline it takes a length of its own, as a still. */endless?: boolean;+ /** A web page that sets no size of its own: `w` × `h` is the size it is shown at alone (1920 × 1080). */+ reflows?: boolean;w?: number;h?: number;/** Source frame rate: shown, because 25 and 30 fps footage mixed in one film repeats frames after export. */fps?: number;+ /** A link to media kept elsewhere (a NAS, another disk): where it leads, and whether it can be reached now. */+ link?: MediaLink;+ /** Heavy footage's proxy for the preview (studio/server/proxies.mjs): waiting, being made (`ratio`), ready, failed. */+ proxy?: MediaProxy;}+export interface MediaProxy { state: 'waiting' | 'making' | 'ready' | 'failed'; ratio?: number }++/** Where a linked file or folder is kept (`to`, a full path); `missing`: it cannot be reached (a NAS that is off). */+export interface MediaLink { to: string; missing?: boolean }+export interface MediaListing {/** The media root's own name (`assets`), so folder paths relative to it can be made project paths. */dir: string;@@ -49,6 +60,8 @@ export interface MediaListing {made?: readonly string[];/** The film's pages, as `kind: 'mg'` resources. */pages: readonly WorkspaceResource[];+ /** Folders that are links to media kept elsewhere (relative to the media root). */+ linkedDirs?: Readonly<Record<string, MediaLink>>;}/** Where the pane's pictures, sounds and pages come from. Addresses should carry the file's version (its mtime). */@@ -75,6 +88,8 @@ export type MediaResult = 'ok' | 'taken' | 'failed';export interface MediaFacts {durationMs?: number;endless?: boolean;+ proxy?: MediaProxy;+ reflows?: boolean;w?: number;h?: number;fps?: number;@@ -85,6 +100,8 @@ export interface FilesListing {files: readonly { path: string; kind: string; size: number; mtime: number }[];folders: readonly string[];pages: readonly { path: string; size: number; mtime: number }[];+ /** Links to media kept elsewhere, by project path (files and folders). */+ links?: Readonly<Record<string, MediaLink>>;}const MEDIA_KINDS: readonly string[] = ['video', 'image', 'audio'];@@ -125,16 +142,19 @@ export function mediaListingOf(const dirOf = (path: string) => { const r = rel(path); return r.includes('/') ? r.slice(0, r.lastIndexOf('/')) : ''; };return {dir: root,+ /* a page put in a folder here is a page still: its poster, its preview, an mg clip */files: raw.files.map((f) => ({path: f.path,- name: f.path.slice(f.path.lastIndexOf('/') + 1),+ name: f.kind === 'page' ? pageName(f.path) : f.path.slice(f.path.lastIndexOf('/') + 1),dir: dirOf(f.path),size: f.size,- kind: (MEDIA_KINDS.includes(f.kind) ? f.kind : 'other') as WorkspaceResourceKind,+ kind: (f.kind === 'page' ? 'mg' : MEDIA_KINDS.includes(f.kind) ? f.kind : 'other') as WorkspaceResourceKind,mtimeMs: f.mtime,...facts?.(f.path),+ ...(raw.links?.[f.path] ? { link: raw.links[f.path]! } : {}),})),dirs: raw.folders.filter((d) => d.startsWith(`${root}/`)).map(rel),+ linkedDirs: Object.fromEntries(Object.entries(raw.links ?? {}).filter(([path]) => raw.folders.includes(path)).map(([path, link]) => [rel(path), link])),...(made ? { made: made.filter((d) => d.startsWith(`${root}/`)).map(rel) } : {}),pages: raw.pages.map((p) => ({path: p.path,@@ -284,6 +304,25 @@ export function srcHitsAsset(src: string, path: string): boolean {return src === path || path.endsWith(`/${src}`) || src.endsWith(`/${path}`);}+const SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];++/** "12.3 MB": the order of magnitude is what a person reads, not the exact byte count. */+export function formatFileSize(bytes: number): string {+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';+ let value = bytes;+ let unit = 0;+ while (value >= 1024 && unit < SIZE_UNITS.length - 1) {+ value /= 1024;+ unit += 1;+ }+ /* no decimals for bytes or past three digits ("248 MB" reads better than "248.3 MB") */+ const text = value.toFixed(unit === 0 || value >= 100 ? 0 : 1);+ /* 1023.97 KB rounds to 1024.0, which is 1 MB */+ return Number(text) >= 1024 && unit < SIZE_UNITS.length - 1+ ? `1.0 ${SIZE_UNITS[unit + 1]}`+ : `${text} ${SIZE_UNITS[unit]}`;+}+/*** A clip length as the pane shows it, one way for every length: minutes and seconds ("0:05", "1:25"), hours when* there are any ("1:02:03"), as the Projects window shows a film's. Rounded to the second, never "0:00" for a clip