Skip to content

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

Studio: layers in a page are copied and pasted as new, independent elements (#298)

riverisbuilding71d732ad241d
diff --git a/.changeset/copy-paste-layers.md b/.changeset/copy-paste-layers.md
new file mode 100644
index 0000000..8964b8b
--- /dev/null
+++ b/.changeset/copy-paste-layers.md
@@ -0,0 +1,9 @@
+---
+"openfilm": patch
+---
+
+Studio: layers inside a page can be copied and pasted, as in a design tool. Select one or more on the picture or in the Layers panel, then press ⌘C / Ctrl+C or choose Copy in the layer's menu (a Layers row now has a right-click menu with Copy, Paste and Delete). Paste with ⌘V / Ctrl+V or Paste in a menu.
+
+The copy is a new, independent element written into the page's HTML right after the original, or last in its parent when the page's CSS would restyle what is next to it. It gets new ids (`<id>-copy`). The page's CSS for the old ids is repeated for the new ones in the page's head, and the clip's changes to the original (styles, moves, words) are written into it. Scripts and `on…` handlers inside it are left out, so the page's code runs once. It is placed 24 px lower and to the right, each paste at the same spot on top of the one before, and selected so it can be moved at once. From then on it is an ordinary layer: it shows in the Layers panel, moves, exports and is deleted like any other. When other clips also show that page, this clip first gets its own copy of the page (`<name> 2.html`), so the other clips stay as they were.
+
+Pasted while another page is in hand or under the playhead (also from another project), the layer is written into that page as it looks now, with its look written in. Files it uses from another project are copied into `pasted/<project name>/`. With no page under the playhead, it goes back into its own page. One undo removes a paste, the page and film.html together, even after the agent edited the page meanwhile. A page that is not UTF-8 keeps its encoding. A paste pastes whatever was copied last: layers, or clips on the timeline. The Layers panel also reads the page again when a page file changes.
diff --git a/packages/openfilm/studio/server/page-text.mjs b/packages/openfilm/studio/server/page-text.mjs
new file mode 100644
index 0000000..75401c5
--- /dev/null
+++ b/packages/openfilm/studio/server/page-text.mjs
@@ -0,0 +1,80 @@
+// @ts-check
+/**
+ * A page of a project read and written as text, for what Studio writes into a page (layers pasted, the editor's
+ * lib/layer-paste). Each read says the page's `rev`; a write names the rev it was made from and is refused when the
+ * page changed since (the agent wrote it meanwhile), so nothing written by someone else is written over. A page
+ * written where there was none (`expect: null`) is a new one; `text: null` takes a page away (to the trash). A page is
+ * written back in the encoding it has.
+ */
+import { createHash } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { dirname } from 'node:path';
+import { FileError, inside, trashFile } from './files.mjs';
+
+const PAGE = /\.html?$/i;
+
+/** A page's rev: what a write names to say which page it was made from (its bytes, whatever they say). */
+export const revOf = (/** @type {string | Buffer} */ bytes) => createHash('sha1').update(bytes).digest('hex');
+
+const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
+
+/**
+ * A page's text: UTF-8 (a mark at its start kept), else one byte a character (an older page's own encoding, read and
+ * written back byte for byte, so what is not changed stays what it was).
+ * @param {Buffer} bytes
+ */
+function decode(bytes) {
+ try { return { text: UTF8.decode(bytes), bytewise: false }; } catch { return { text: bytes.toString('latin1'), bytewise: true }; }
+}
+
+/** @param {string} text @param {boolean} bytewise @param {string} rel */
+function encode(text, bytewise, rel) {
+ if (!bytewise) return Buffer.from(text, 'utf8');
+ if (/[^\u0000-\u00ff]/.test(text)) {
+ throw new FileError(`${rel} is not written in UTF-8, and what goes in it has characters its encoding cannot hold`, 415);
+ }
+ return Buffer.from(text, 'latin1');
+}
+
+/** @param {string} root @param {unknown} rel */
+function pagePath(root, rel) {
+ if (typeof rel !== 'string' || !PAGE.test(rel)) throw new FileError('a page of the project (.html), please');
+ return inside(root, rel);
+}
+
+/**
+ * The page `rel` of the project at `root`, as text, with its rev.
+ * @param {string} root @param {unknown} rel
+ */
+export async function readPage(root, rel) {
+ const abs = pagePath(root, rel);
+ if (!existsSync(abs)) throw new FileError(`${rel} is not there`, 404);
+ const bytes = await readFile(abs);
+ return { text: decode(bytes).text, rev: revOf(bytes) };
+}
+
+/**
+ * The page `rel` written as `text` (null: taken away), when it is still the page of rev `expect` (null: when there is
+ * no page there yet), in the encoding it has. Its new rev (null once taken away). `undo`: the write takes back one of
+ * Studio's own (a paste undone), for what keeps track of Studio's writes.
+ * @param {string} root @param {unknown} rel @param {string | null} text @param {string | null} expect
+ * @param {{ undo?: boolean }} [_how]
+ */
+export async function writePage(root, rel, text, expect, _how = {}) {
+ const abs = pagePath(root, rel);
+ const bytes = existsSync(abs) ? await readFile(abs) : null;
+ const now = bytes ? revOf(bytes) : null;
+ if (now !== expect) {
+ throw new FileError(expect == null ? `${rel} is there already` : `${rel} was changed since (by the agent, or in another window)`, 409);
+ }
+ if (text == null) {
+ if (bytes) await trashFile(root, /** @type {string} */ (rel));
+ return { rev: null };
+ }
+ if (typeof text !== 'string') throw new FileError('the page\'s text, please');
+ const out = encode(text, bytes ? decode(bytes).bytewise : false, /** @type {string} */ (rel));
+ await mkdir(dirname(abs), { recursive: true });
+ await writeFile(abs, out);
+ return { rev: revOf(out) };
+}
diff --git a/packages/openfilm/studio/server/page-text.test.mjs b/packages/openfilm/studio/server/page-text.test.mjs
new file mode 100644
index 0000000..b2aa0f2
--- /dev/null
+++ b/packages/openfilm/studio/server/page-text.test.mjs
@@ -0,0 +1,38 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { readPage, revOf, writePage } from './page-text.mjs';
+
+test('a page is written only over the text it was made from, a new one only where there is none, and taken away only as it was', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'of-page-text-'));
+ writeFileSync(join(root, 'title.html'), '<h1>Hi</h1>');
+ const { text, rev } = await readPage(root, 'title.html');
+ assert.deepEqual([text, rev], ['<h1>Hi</h1>', revOf(Buffer.from('<h1>Hi</h1>'))]);
+ const made = await writePage(root, 'title.html', '<h1>Hi</h1><h1>Hi</h1>', rev);
+ assert.equal(made.rev, revOf(Buffer.from('<h1>Hi</h1><h1>Hi</h1>')));
+ await assert.rejects(writePage(root, 'title.html', '<p>late</p>', rev), /changed since/, 'written meanwhile: refused');
+ assert.equal(readFileSync(join(root, 'title.html'), 'utf8'), '<h1>Hi</h1><h1>Hi</h1>');
+ await assert.rejects(writePage(root, 'title.html', 'x', null), /there already/);
+ await writePage(root, 'scenes/title-2.html', '<p>own</p>', null);
+ assert.equal(readFileSync(join(root, 'scenes/title-2.html'), 'utf8'), '<p>own</p>');
+ await assert.rejects(readPage(root, 'notes.txt'), /a page of the project/);
+ await assert.rejects(readPage(root, '../title.html'), /not a path inside/);
+ await assert.rejects(writePage(root, 'scenes/title-2.html', null, revOf(Buffer.from('<p>other</p>'))), /changed since/, 'taken away only as it was written');
+ assert.ok(existsSync(join(root, 'scenes/title-2.html')));
+});
+
+test('a page not in UTF-8 is written back byte for byte, its own bytes kept; a mark at the start of one in UTF-8 too', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'of-page-bytes-'));
+ writeFileSync(join(root, 'p.html'), Buffer.from('<meta charset="windows-1252"><h1 id="t">Caf\xe9 \x93q\x94</h1>', 'latin1'));
+ const { text, rev } = await readPage(root, 'p.html');
+ await writePage(root, 'p.html', text.replace('</h1>', '</h1><h1 id="t-copy">x</h1>'), rev);
+ assert.deepEqual(readFileSync(join(root, 'p.html')), Buffer.from('<meta charset="windows-1252"><h1 id="t">Caf\xe9 \x93q\x94</h1><h1 id="t-copy">x</h1>', 'latin1'));
+ const again = await readPage(root, 'p.html');
+ await assert.rejects(writePage(root, 'p.html', `${again.text}<p>\u2713</p>`, again.rev), /not written in UTF-8/);
+ writeFileSync(join(root, 'u.html'), Buffer.from('\ufeff<h1>é</h1>', 'utf8'));
+ const u = await readPage(root, 'u.html');
+ await writePage(root, 'u.html', `${u.text}<p>✓</p>`, u.rev);
+ assert.deepEqual(readFileSync(join(root, 'u.html')), Buffer.from('\ufeff<h1>é</h1><p>✓</p>', 'utf8'));
+});
diff --git a/packages/openfilm/studio/server/saved.mjs b/packages/openfilm/studio/server/saved.mjs
index da12711..3520e5f 100644
--- a/packages/openfilm/studio/server/saved.mjs
+++ b/packages/openfilm/studio/server/saved.mjs
@@ -290,6 +290,23 @@ export async function saveFile(root, rel, o = {}) {
return libraryPath(path);
}
+/** A place made a name a page's address takes as it is, part by part. */
+const placeName = (/** @type {string} */ rel) => rel.split('/').map((part) => part.normalize('NFKC').replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^-+|-+$/g, '') || 'saved').join('/');
+
+/**
+ * `files` (places in folder `from`) copied to the same places in folder `to`. A file there already (copied before,
+ * maybe changed since in that project) stays as it is.
+ * @param {string} from @param {string[]} files @param {string} to
+ */
+async function copyIn(from, files, to) {
+ for (const rel of files) {
+ const dest = join(to, rel);
+ if ((await stat(dest).catch(() => null))?.isFile()) continue;
+ await mkdir(dirname(dest), { recursive: true });
+ await copyFile(join(from, rel), dest);
+ }
+}
+
/**
* What a project needs to use a thing of the library (`path`, a `saved/` path): a file imported into its assets/ (as
* one from the computer is), or a bundle's files copied to `saved/<its place>/` there (a file there already is kept as
@@ -308,18 +325,30 @@ export async function takeSaved(root, path) {
const item = await readBundle(at);
if (!item) throw new SavedError('That is a folder: open it and pick what is in it.', 400);
/* its place in the project: the library's, made a name a page's address takes as it is */
- const base = `saved/${rel.split('/').map((part) => part.normalize('NFKC').replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^-+|-+$/g, '') || 'saved').join('/')}`;
+ const base = `saved/${placeName(rel)}`;
const from = join(at, 'files');
+ const files = [];
for (const entry of await readdir(from, { recursive: true, withFileTypes: true }).catch(() => [])) {
- if (!entry.isFile()) continue;
- const src = join(entry.parentPath ?? entry.path, entry.name);
- const to = join(root, base, src.slice(from.length + 1));
- /* there already (taken before, maybe changed since in this project): it stays as it is */
- if ((await stat(to).catch(() => null))?.isFile()) continue;
- await mkdir(dirname(to), { recursive: true });
- await copyFile(src, to);
+ if (entry.isFile()) files.push(join(entry.parentPath ?? entry.path, entry.name).slice(from.length + 1));
}
+ await copyIn(from, files, join(root, base));
if (item.kind === 'page') return { path: `${base}/${item.path}` };
if (item.kind === 'group') return { clips: item.clips.map((/** @type {any} */ c) => ({ track: c.track, at: c.at, clip: { ...c.clip, src: `${base}/${c.clip.src}` } })) };
return { clip: { ...item.clip, src: `${base}/${item.clip.src}` } };
}
+
+/**
+ * A clip of the project at `fromRoot` brought into the project at `root` (layers pasted from there, lib/layer-clipboard):
+ * its file and what it loads copied to `pasted/<name>/` here (`name`: that project's), at the places they had there,
+ * so a page's own references still find what they name; copied before, what is there is used. The clip, with its
+ * file's place here.
+ * @param {string} root @param {string} fromRoot @param {Record<string, unknown> & { src: string }} clip @param {string} name
+ */
+export async function bringClip(root, fromRoot, clip, name) {
+ if (typeof clip?.src !== 'string' || !clip.src) throw new SavedError('a clip with its file, please', 400);
+ const files = await clipFiles(fromRoot, clip);
+ if (!files.includes(clip.src)) throw new SavedError('That clip’s file is not in its project any more.', 404);
+ const base = `pasted/${placeName(cleanName(name) || 'project')}`;
+ await copyIn(fromRoot, files, join(root, base));
+ return { clip: { ...clip, src: `${base}/${clip.src}` } };
+}
diff --git a/packages/openfilm/studio/server/saved.test.mjs b/packages/openfilm/studio/server/saved.test.mjs
index d07f432..cb8dfcb 100644
--- a/packages/openfilm/studio/server/saved.test.mjs
+++ b/packages/openfilm/studio/server/saved.test.mjs
@@ -4,7 +4,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { makeFolder, moveFile } from './files.mjs';
-import { libraryRel, listLibrary, saveClip, saveFile, saveGroup, takeSaved } from './saved.mjs';
+import { bringClip, libraryRel, listLibrary, saveClip, saveFile, saveGroup, takeSaved } from './saved.mjs';
let saved;
let before;
@@ -139,3 +139,28 @@ test('a place in the library is named from saved/', () => {
assert.throws(() => libraryRel('assets/a.png'), /a place in Saved/);
assert.throws(() => libraryRel(7), /a place in Saved/);
});
+
+test('a clip brought from another project: its page and what it loads copied in under its project\'s name, once', async () => {
+ const from = project();
+ const root = mkdtempSync(join(tmpdir(), 'of-saved-into-'));
+ const clip = { src: 'pages/title.html', overrides: [{ at: '#t', t: [24, 24] }] };
+ const { clip: brought } = await bringClip(root, from, clip, 'Launch: v2');
+ assert.deepEqual(brought, { ...clip, src: 'pasted/Launch-v2/pages/title.html' });
+ for (const f of ['pages/title.html', 'pages/title.css', 'pages/inset.html', 'assets/logo.png']) assert.ok(existsSync(join(root, 'pasted/Launch-v2', f)), f);
+ for (const f of ['pages/other.html', 'assets/unused.png', 'film.html']) assert.ok(!existsSync(join(root, 'pasted/Launch-v2', f)), `${f} is not the clip's`);
+ /* changed here since: brought again, it is used as it is */
+ writeFileSync(join(root, 'pasted/Launch-v2/pages/title.css'), 'h1 { color: red }');
+ await bringClip(root, from, clip, 'Launch: v2');
+ assert.equal(readFileSync(join(root, 'pasted/Launch-v2/pages/title.css'), 'utf8'), 'h1 { color: red }');
+ await assert.rejects(bringClip(root, from, { src: 'pages/gone.html' }, 'Launch'), /not in its project/);
+});
+
+test('the clips of two pages brought from one project: the files of each, under one place for that project', async () => {
+ const from = project();
+ writeFileSync(join(from, 'pages', 'other.html'), '<!doctype html><img src="../assets/v.mp4"><p>Another clip</p>');
+ const root = mkdtempSync(join(tmpdir(), 'of-saved-two-'));
+ const one = await bringClip(root, from, { src: 'pages/title.html' }, 'Launch');
+ const two = await bringClip(root, from, { src: 'pages/other.html' }, 'Launch');
+ assert.deepEqual([one.clip.src, two.clip.src], ['pasted/Launch/pages/title.html', 'pasted/Launch/pages/other.html']);
+ for (const f of ['assets/logo.png', 'assets/v.mp4', 'pages/other.html']) assert.ok(existsSync(join(root, 'pasted/Launch', f)), f);
+});
diff --git a/packages/openfilm/studio/server/server.mjs b/packages/openfilm/studio/server/server.mjs
index 8ca2784..0944bd0 100644
--- a/packages/openfilm/studio/server/server.mjs
+++ b/packages/openfilm/studio/server/server.mjs
@@ -22,6 +22,7 @@ import { mkdir, readFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { EditError, editProjectFilm, pageClipLook, readProjectFilm } from './film.mjs';
+import { readPage, writePage } from './page-text.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';
@@ -49,7 +50,7 @@ import { installedFonts } from './fonts.mjs';
import { projectFonts, resolveIn } from './project-fonts.mjs';
import { FILM_PAGE, PageFrameError, closePageFrames, filmPoster, pageFacts, pageFrame, warmFilmPoster } from './pageframes.mjs';
import { COVER_FRAME_W, CoverError, clearCover, readCover, readCoverBody, setCover, setCoverFromFile } from './cover.mjs';
-import { SavedError, bundlePoster, libraryPath, libraryRel, libraryRoot as savedLibrary, listLibrary, saveClip, saveFile, saveGroup, takeSaved } from './saved.mjs';
+import { SavedError, bundlePoster, libraryPath, libraryRel, libraryRoot as savedLibrary, listLibrary, bringClip, saveClip, saveFile, saveGroup, takeSaved } from './saved.mjs';
import { FILM_FILE, clipKind, isPage } from '../../src/film-doc.mjs';
import { moveToTrash } from './trash.mjs';
import { listSkills, removeSkill, setSkillCover, setSkillInstalled, setSkillOn, skillOrigins, skillsInstalled, skillsOff } from '../../src/skills.mjs';
@@ -822,6 +823,20 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
const { path: from } = /** @type {{ path?: unknown }} */ (await readJson(req) ?? {});
return json(res, 200, await savedCall(() => takeSaved(project.path, from)));
}
+ /* a page as text, read and written by what Studio writes into a page (layers pasted, page-text.mjs) */
+ if (rest === 'page' && req.method === 'GET') return json(res, 200, await readPage(project.path, url.searchParams.get('path')));
+ if (rest === 'page' && req.method === 'PUT') {
+ const { path: at, text, expect, undo } = /** @type {{ path?: unknown, text?: unknown, expect?: unknown, undo?: unknown }} */ (await readJson(req) ?? {});
+ if (text !== null && typeof text !== 'string') throw new HttpError(400, 'the page\'s text, please');
+ return json(res, 200, await writePage(project.path, at, text, typeof expect === 'string' ? expect : null, { undo: undo === true }));
+ }
+ /* a clip of another project brought into this one, with the files it needs (layers pasted from there) */
+ if (rest === 'bring' && req.method === 'POST') {
+ const { from, clip } = /** @type {{ from?: unknown, clip?: any }} */ (await readJson(req) ?? {});
+ const source = typeof from === 'string' ? await projectById(from).catch(() => null) : null;
+ if (!source || source.missing) throw new HttpError(404, 'The project it was copied from is not there any more.');
+ return json(res, 200, await savedCall(() => bringClip(project.path, source.path, clip, source.name)));
+ }
/* what Studio works out from a media file: its length and size, a poster, a frame, a waveform (see derived.mjs) */
if (rest === 'media' && req.method === 'GET') {
const at = url.searchParams.get('path') ?? '';
diff --git a/packages/openfilm/studio/server/stage.js b/packages/openfilm/studio/server/stage.js
index d641dd9..47a6af1 100644
--- a/packages/openfilm/studio/server/stage.js
+++ b/packages/openfilm/studio/server/stage.js
@@ -1324,6 +1324,267 @@
return collect(doc.body);
};
+ /* ── a layer as it looks now, to be written into another page (the editor's lib/layer-paste pastedElsewhere) ── */
+ /** What of an element's computed style is its look: where it is, its box, its type, its paint. */
+ const LOOK = [
+ 'display', 'position', 'left', 'top', 'right', 'bottom', 'width', 'height', 'box-sizing', 'margin', 'padding',
+ 'flex-direction', 'flex-wrap', 'justify-content', 'align-items', 'align-content', 'align-self', 'flex', 'gap', 'order',
+ 'grid-template-columns', 'grid-template-rows', 'grid-column', 'grid-row',
+ 'color', 'background-color', 'background-image', 'background-size', 'background-position', 'background-repeat',
+ 'border', 'border-radius', 'outline', 'box-shadow', 'opacity', 'visibility', 'overflow', 'z-index',
+ 'transform', 'transform-origin', 'translate', 'scale', 'rotate', 'filter', 'backdrop-filter', 'mix-blend-mode',
+ 'clip-path', 'mask-image', 'object-fit', 'object-position',
+ 'font-family', 'font-size', 'font-weight', 'font-style', 'line-height', 'letter-spacing', 'word-spacing', 'text-align',
+ 'text-transform', 'text-decoration', 'text-shadow', 'white-space', '-webkit-text-stroke', 'text-indent', 'vertical-align',
+ 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-dasharray', 'stroke-dashoffset',
+ ];
+ const DEFAULT_LOOK = new Map();
+ /** A property's value an element of this tag has with no CSS of the page's: not written. */
+ const defaultLook = (doc, tag) => {
+ if (DEFAULT_LOOK.has(tag)) return DEFAULT_LOOK.get(tag);
+ const probe = doc.createElement(tag);
+ let out = new Map();
+ try {
+ probe.style.all = 'initial';
+ doc.body.append(probe);
+ const cs = doc.defaultView.getComputedStyle(probe);
+ out = new Map(LOOK.map((p) => [p, cs.getPropertyValue(p)]));
+ } finally { probe.remove(); }
+ DEFAULT_LOOK.set(tag, out);
+ return out;
+ };
+ /**
+ * `el` as it looks now, as markup that holds its look itself: each element's computed look written in its style (no
+ * class: another page's CSS does not reach it; its ids are made new ones where it goes), what it loads as full
+ * addresses, no scripts or handlers; the root placed where it is in its page (`position: absolute`, page px). With
+ * the page's @font-face rules of the fonts in it.
+ */
+ const snapshotOf = (el) => {
+ const doc = el.ownerDocument;
+ const view = doc.defaultView;
+ const copy = el.cloneNode(true);
+ const from = [el, ...el.querySelectorAll('*')];
+ const to = [copy, ...copy.querySelectorAll('*')];
+ const families = new Set();
+ from.forEach((src, i) => {
+ const out = to[i];
+ if (!out) return;
+ const cs = view.getComputedStyle(src);
+ const plain = defaultLook(doc, src.localName);
+ const turned = ['transform', 'scale', 'rotate'].some((p) => cs.getPropertyValue(p) !== 'none');
+ const decls = LOOK.filter((p) => {
+ const v = cs.getPropertyValue(p);
+ if (v === plain.get(p)) return false;
+ /* a border or outline not drawn, a turning point of nothing turned: not its look */
+ if ((p === 'border' || p === 'outline') && (/(^|\s)0px(\s|$)/.test(v) || /\bnone\b/.test(v))) return false;
+ return p !== 'transform-origin' || turned;
+ }).map((p) => `${p}: ${cs.getPropertyValue(p)}`);
+ for (const f of cs.fontFamily.split(',')) families.add(f.trim().replace(/^["']|["']$/g, ''));
+ out.removeAttribute('class');
+ for (const a of [...out.attributes]) if (/^on/i.test(a.name)) out.removeAttribute(a.name);
+ out.setAttribute('style', decls.join('; '));
+ for (const a of ['src', 'href', 'poster']) if (src[a] && typeof src[a] === 'string' && out.hasAttribute(a)) out.setAttribute(a, src[a]);
+ });
+ for (const n of copy.querySelectorAll('script')) n.remove();
+ /* the root where it is in its page, its own box: not the flow it was in */
+ let left = 0;
+ let top = 0;
+ let [w, h] = [el.offsetWidth, el.offsetHeight];
+ if (el.offsetParent !== undefined) for (let n = el; n; n = n.offsetParent) { left += n.offsetLeft; top += n.offsetTop; }
+ else {
+ /* an SVG element has no offset*: where it is drawn in its page */
+ const r = el.getBoundingClientRect();
+ [left, top, w, h] = [r.left, r.top, r.width, r.height];
+ }
+ copy.style.setProperty('position', 'absolute');
+ copy.style.setProperty('left', `${left}px`);
+ copy.style.setProperty('top', `${top}px`);
+ copy.style.setProperty('width', `${w}px`);
+ copy.style.setProperty('height', `${h}px`);
+ copy.style.setProperty('margin', '0');
+ copy.style.setProperty('box-sizing', 'border-box');
+ copy.style.removeProperty('right');
+ copy.style.removeProperty('bottom');
+ const fonts = [];
+ for (const sheet of doc.styleSheets) {
+ let list = [];
+ try { list = [...sheet.cssRules]; } catch { continue; }
+ for (const r of list) {
+ if (r.type !== 5) continue;
+ const family = r.style.getPropertyValue('font-family').trim().replace(/^["']|["']$/g, '');
+ if (!families.has(family)) continue;
+ /* its files as full addresses */
+ const base = sheet.href ?? doc.baseURI;
+ fonts.push(r.cssText.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (m, q, u) => { try { return `url("${new URL(u, base).href}")`; } catch { return m; } }));
+ }
+ }
+ return { html: copy.outerHTML, fonts, base: new URL('.', location.href).href };
+ };
+
+ /* ── a layer to be written into its page (the editor's lib/layer-paste) ── */
+ /** Where `el` is in `root`: element after element, from it. */
+ const pathIn = (root, el) => {
+ const path = [];
+ for (let n = el; n !== root; n = n.parentElement) path.unshift([...n.parentElement.children].indexOf(n));
+ return path;
+ };
+ /** A selector list's parts: split at its own commas, not those in :is(…) or [a="b, c"]. */
+ const selectorParts = (list) => {
+ const got = [];
+ let depth = 0;
+ let quote = null;
+ let from = 0;
+ for (let i = 0; i < list.length; i++) {
+ const ch = list[i];
+ if (quote) { if (ch === quote && list[i - 1] !== '\\') quote = null; continue; }
+ if (ch === '"' || ch === "'") quote = ch;
+ else if (ch === '(' || ch === '[') depth++;
+ else if (ch === ')' || ch === ']') depth--;
+ else if (ch === ',' && depth === 0) { got.push(list.slice(from, i).trim()); from = i + 1; }
+ }
+ got.push(list.slice(from).trim());
+ return got;
+ };
+ /** A selector's weight [ids, classes and the like, types] (CSS Selectors 4: :is() / :not() / :has() their heaviest). */
+ const specificityOf = (sel) => {
+ const w = [0, 0, 0];
+ const add = (x) => { w[0] += x[0]; w[1] += x[1]; w[2] += x[2]; };
+ const heavier = (x, y) => (x[0] - y[0] || x[1] - y[1] || x[2] - y[2]) > 0;
+ const heaviest = (list) => selectorParts(list).map(specificityOf).reduce((m, x) => (heavier(x, m) ? x : m), [0, 0, 0]);
+ const name = (i) => { let k = i; while (k < sel.length && (/[\w-]/.test(sel[k]) || sel.charCodeAt(k) > 127 || sel[k] === '\\')) k += sel[k] === '\\' ? 2 : 1; return k; };
+ const inner = (i) => {
+ let depth = 0;
+ for (let k = i; k < sel.length; k++) {
+ if (sel[k] === '(') depth++;
+ else if (sel[k] === ')' && --depth === 0) return [sel.slice(i + 1, k), k + 1];
+ }
+ return [sel.slice(i + 1), sel.length];
+ };
+ for (let i = 0; i < sel.length;) {
+ const ch = sel[i];
+ if (ch === '#') { w[0]++; i = name(i + 1); } else if (ch === '.') { w[1]++; i = name(i + 1); } else if (ch === '[') {
+ w[1]++;
+ i = sel.indexOf(']', i) + 1 || sel.length;
+ } else if (ch === ':' && sel[i + 1] === ':') {
+ w[2]++;
+ i = name(i + 2);
+ if (sel[i] === '(') i = inner(i)[1];
+ } else if (ch === ':') {
+ const end = name(i + 1);
+ const pseudo = sel.slice(i + 1, end).toLowerCase();
+ i = end;
+ if (['before', 'after', 'first-line', 'first-letter'].includes(pseudo)) { w[2]++; continue; }
+ if (sel[i] !== '(') { w[1]++; continue; }
+ const [arg, next] = inner(i);
+ i = next;
+ if (pseudo === 'where') continue;
+ if (['is', 'not', 'has', 'matches', '-webkit-any'].includes(pseudo)) { add(heaviest(arg)); continue; }
+ w[1]++;
+ const of = /\sof\s([^]*)$/.exec(arg);
+ if ((pseudo === 'nth-child' || pseudo === 'nth-last-child') && of) add(heaviest(of[1]));
+ } else if (/[A-Za-z_-]/.test(ch) || sel.charCodeAt(i) > 127) { w[2]++; i = name(i); } else i++;
+ }
+ return w;
+ };
+ /**
+ * The page's style rules in their order: each one's selector list in parts (a nested rule's, as it reads where it
+ * is: `&` its parent, `:is(…)`), its declarations as written, the at-rules it is in (`@media …`, `@supports …`,
+ * `@layer …`, `@container …`, outermost first), and the stylesheet it is in (its `<style>` or `<link>`, by place among
+ * them).
+ */
+ const styleRules = (doc) => {
+ const out = [];
+ const nest = (parts, parent) => (parent == null ? parts : parts.map((p) => (p.includes('&') ? p.replaceAll('&', `:is(${parent})`) : `:is(${parent}) ${p}`)));
+ const walk = (rules, within, sheet, parent) => {
+ for (const r of rules) {
+ if (r.selectorText != null) {
+ const parts = nest(selectorParts(r.selectorText), parent);
+ out.push({ parts, style: r.style, within, sheet });
+ if (r.cssRules?.length) walk(r.cssRules, within, sheet, parts.join(', '));
+ } else if (r.styleSheet) {
+ let list = [];
+ try { list = [...r.styleSheet.cssRules]; } catch { /* another origin's */ }
+ walk(list, within, sheet, parent);
+ } else if (r.cssRules) walk(r.cssRules, [...within, r.cssText.slice(0, r.cssText.indexOf('{')).trim()], sheet, parent);
+ }
+ };
+ const owners = [...doc.querySelectorAll('style, link[rel~="stylesheet" i]')];
+ for (const sheet of doc.styleSheets) {
+ let list = [];
+ try { list = [...sheet.cssRules]; } catch { continue; }
+ walk(list, [], owners.indexOf(sheet.ownerNode), null);
+ }
+ return out;
+ };
+ const matchesAny = (el, parts) => parts.some((part) => { try { return el.matches(part); } catch { return false; } });
+ /**
+ * A rule's declarations as it writes them, shorthands and `var()` kept (its longhands read one by one lose a
+ * shorthand written with a `var()`): [property, value] in its order.
+ */
+ const declsOf = (style) => {
+ const out = [];
+ let depth = 0;
+ let quote = null;
+ let from = 0;
+ const text = style.cssText;
+ const take = (part) => {
+ const at = part.indexOf(':');
+ if (at > 0) out.push([part.slice(0, at).trim(), part.slice(at + 1).trim()]);
+ };
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i];
+ if (quote) { if (ch === quote && text[i - 1] !== '\\') quote = null; continue; }
+ if (ch === '"' || ch === "'") quote = ch;
+ else if (ch === '(') depth++;
+ else if (ch === ')') depth--;
+ else if (ch === ';' && depth === 0) { take(text.slice(from, i)); from = i + 1; }
+ }
+ take(text.slice(from));
+ return out;
+ };
+ /** An element's words as its page draws them, without what the clip's changes of words wrote (src/overrides.mjs). */
+ const pageWords = (c, el) => {
+ const texts = new Map();
+ for (const saved of c.touched?.values?.() ?? []) for (const [node, data] of saved.texts ?? []) texts.set(node, data);
+ const of = (n) => {
+ if (n.nodeType === 3) return texts.has(n) ? texts.get(n) : n.data;
+ if (n.nodeType !== 1) return '';
+ const saved = c.touched?.get?.(n);
+ if (saved?.nodes) return saved.nodes.map((x) => x.textContent ?? '').join('');
+ return [...n.childNodes].map(of).join('');
+ };
+ return of(el);
+ };
+ /**
+ * Where an element is laid out: its `position`, and its box (px) in what places it, as `position: absolute` would
+ * place it there. An SVG's own shapes are placed by it: null.
+ */
+ const layoutOf = (el) => {
+ const view = el.ownerDocument.defaultView;
+ const position = view.getComputedStyle(el).position;
+ if (el.offsetParent !== undefined) {
+ /* from what places it absolutely (its nearest positioned parent, else the page), through the offset parents
+ between (a table cell is one, and places nothing) */
+ let box = el.parentElement;
+ while (box && view.getComputedStyle(box).position === 'static') box = box.parentElement;
+ let [left, top] = [0, 0];
+ for (let n = el; n && n !== box;) {
+ left += n.offsetLeft;
+ top += n.offsetTop;
+ n = n.offsetParent;
+ if (n && n !== box) { left += n.clientLeft; top += n.clientTop; }
+ }
+ return { position, left, top, width: el.offsetWidth, height: el.offsetHeight };
+ }
+ if (el.localName !== 'svg' || el.ownerSVGElement) return null;
+ /* an <svg> in the page: no offset*; its box from where it is drawn, in what places it (its offset parent's) */
+ let box = el.parentElement;
+ while (box && box !== el.ownerDocument.body && view.getComputedStyle(box).position === 'static') box = box.parentElement;
+ const r = el.getBoundingClientRect();
+ const b = box?.getBoundingClientRect() ?? { left: 0, top: 0 };
+ const k = localScale(el);
+ return { position, left: (r.left - b.left - (box?.clientLeft ?? 0)) / k, top: (r.top - b.top - (box?.clientTop ?? 0)) / k, width: r.width / k, height: r.height / k };
+ };
/* ── the ops ── */
const ops = {
/** The layer under a point: the smallest (Alt: the next one under `cycleFrom`); groups stand for their layers. */
@@ -1504,6 +1765,187 @@
return found.length > 0 && found.every((el) => gone.some((g) => g.contains(el)));
});
},
+ /**
+ * What writing a copy of the layers `of` of clip `clip` into their page needs (the editor's lib/layer-paste), per
+ * layer: a selector naming it alone, its tag, id, classes and words as its page has them (the clip's changes of
+ * words undone: to find it in the page's file), where it is laid out, the clip's changes of it and of the layers
+ * in it, in order, each with where it is in the layer (element by element, from it), and how it looks now
+ * (snapshotOf). Null for a layer not found. (The page's rules of its ids are afterCopy's `looks`, as any rule it
+ * gets and its copy does not.)
+ */
+ layerSource({ clip, of }) {
+ const c = clipById(clip);
+ const doc = c?.kind === 'page' ? c.win?.document : null;
+ if (!doc) return null;
+ return (of ?? []).map((o) => {
+ const el = matches(doc, o)[0];
+ if (!el) return null;
+ const at = selectorOf(el);
+ const tweaks = [];
+ for (const t of c.overrides ?? []) {
+ if (t.at === undefined) continue;
+ const { at: _at, n: _n, lock: _lock, ...tweak } = t;
+ if (!Object.keys(tweak).length) continue;
+ for (const m of matches(doc, t)) if (el.contains(m)) tweaks.push({ path: pathIn(el, m), tag: m.localName, ...tweak });
+ }
+ return {
+ at: matches(doc, { at }).length === 1 ? at : null,
+ tag: el.localName,
+ id: el.id || null,
+ classes: [...el.classList],
+ text: pageWords(c, el).replace(/\s+/g, ' ').trim().slice(0, 200),
+ place: layoutOf(el),
+ tweaks,
+ snapshot: snapshotOf(el),
+ };
+ });
+ },
+ /**
+ * Copies of the layers `of` of clip `clip` written into its page as lib/layer-paste writes them, tried there and
+ * taken away again. Per layer, where its copy goes among the elements beside it (`after`: the index of the one it
+ * goes after, -1 first; `siblings`: their tags): right after it, unless the page's CSS would then draw what is
+ * beside it otherwise (`:nth-child`, `:last-child`, `+` …), else the nearest place where it draws nothing
+ * otherwise (after it first, then before it). Per override of the clip, the selector naming what it finds now
+ * when it would find other elements once they are there (null: the same). Per layer, what the page's rules give
+ * it and not its copy there, and the copy and not it (`looks`: element by element, from it, rules for the copy,
+ * each with the weight, at-rules and stylesheet of the page's rule it answers), so the copy looks as it does.
+ */
+ afterCopy({ clip, of }) {
+ const c = clipById(clip);
+ const doc = c?.kind === 'page' ? c.win?.document : null;
+ const els = doc ? (of ?? []).map((o) => matches(doc, o)[0] ?? null) : [];
+ if (!doc || !els.length || els.some((el) => !el)) return null;
+ const list = c.overrides ?? [];
+ const before = list.map((o) => (o.at === undefined ? null : matches(doc, o)));
+ const view = doc.defaultView;
+ const LOOKED = ['color', 'background-color', 'display', 'position', 'width', 'height', 'margin', 'font-size', 'opacity', 'transform', 'visibility', 'order', 'border-color'];
+ const COPY = 'data-openfilm-copy';
+ const looks = (parent) => [...parent.querySelectorAll(`:scope > :not([${COPY}]), :scope > :not([${COPY}]) *`)]
+ .filter((x) => !x.closest(`[${COPY}]`))
+ .map((x) => [...LOOKED.map((p) => view.getComputedStyle(x).getPropertyValue(p)), ...['::before', '::after'].map((pe) => view.getComputedStyle(x, pe).getPropertyValue('content'))].join('|')).join('\n');
+ /* a copy as lib/layer-paste writes it: its ids new ones, and what in it names them too (`for`, `href="#…"`,
+ `aria-*`, `url(#…)`) */
+ const NAMES_IDS = ['for', 'aria-labelledby', 'aria-describedby', 'aria-controls', 'aria-owns', 'list', 'form', 'headers'];
+ const copyOf = (el) => {
+ const copy = el.cloneNode(true);
+ copy.setAttribute(COPY, '');
+ const all = [copy, ...copy.querySelectorAll('*')];
+ const ids = new Set(all.map((n) => n.id).filter(Boolean));
+ const renamed = (id) => (ids.has(id) ? `${id}-openfilm-copy` : id);
+ for (const n of all) {
+ if (n.id) n.id = renamed(n.id);
+ for (const a of [...n.attributes]) {
+ let v = a.value;
+ if (NAMES_IDS.includes(a.name)) v = v.split(/\s+/).map(renamed).join(' ');
+ else if ((a.name === 'href' || a.name === 'xlink:href') && v.startsWith('#')) v = `#${renamed(v.slice(1))}`;
+ else v = v.replace(/url\((["']?)#([^"')]+)\1\)/g, (m, q, id) => `url(${q}#${renamed(id)}${q})`);
+ if (v !== a.value) n.setAttribute(a.name, v);
+ }
+ }
+ return copy;
+ };
+ const put = (copy, parent, after) => {
+ const kids = [...parent.children].filter((x) => !x.hasAttribute(COPY));
+ if (after < 0) parent.prepend(copy); else kids[after].after(copy);
+ };
+ const places = els.map((el) => {
+ const parent = el.parentElement;
+ const kids = [...parent.children].filter((x) => !x.hasAttribute(COPY));
+ const own = kids.indexOf(el);
+ const was = looks(parent);
+ const tries = [own];
+ for (let k = own + 1; k < kids.length && tries.length < 40; k++) tries.push(k);
+ for (let k = own - 1; k >= -1 && tries.length < 80; k--) tries.push(k);
+ const copy = copyOf(el);
+ let after = own;
+ for (const k of tries) {
+ put(copy, parent, k);
+ const same = looks(parent) === was;
+ copy.remove();
+ if (same) { after = k; break; }
+ }
+ return { after, siblings: kids.map((x) => x.localName) };
+ });
+ const copies = els.map((el, i) => {
+ const copy = copyOf(el);
+ put(copy, el.parentElement, places[i].after);
+ return copy;
+ });
+ /* what the page's CSS draws otherwise on a copy where it goes (a :first-child, a p + p): its original's, element
+ by element, to be written on it. Not where it is and how big (the paste places it), nor what its new ids lose
+ (their rules are said again of them) */
+ /* what the page's rules give an element where it is and not its copy where it goes (a :first-child), and what
+ they give the copy there and not it (a p + p), element by element. The first said again of the copy as the rule
+ says it (`var()`, `currentColor`, an animation stay what they are); the second answered, property by property,
+ by what the element's own rules say (none: `unset`, so it inherits). Each with its rule's weight, at-rules and
+ stylesheet, for a rule of the copy's that the cascade weighs as that one */
+ /* each rule's parts with the pseudo-element they end in apart (`::before`, `::marker` …: what an element's own
+ match cannot say), so a rule of an element's pseudo-element is weighed as the element's, and said again of
+ the copy's same pseudo-element */
+ const PSEUDO = /(?:::[\w-]+(?:\([^)]*\))?|:(?:before|after|first-line|first-letter)(?![\w-]))+$/i;
+ const rules = styleRules(doc).map((r, order) => ({
+ ...r,
+ order,
+ split: r.parts.map((part) => {
+ const m = PSEUDO.exec(part);
+ return m ? { part, base: part.slice(0, m.index).trim() || '*', pseudo: m[0] } : { part, base: part, pseudo: '' };
+ }),
+ }));
+ const pseudosOf = (r) => [...new Set(r.split.map((x) => x.pseudo))];
+ const found = (r, el, pseudo) => r.split.filter((x) => x.pseudo === pseudo && matchesAny(el, [x.base]));
+ /* the element part's weight: the pseudo-element is written again after the copy's selector, and weighs there */
+ const weightOf = (r, el, pseudo) => found(r, el, pseudo).map((x) => specificityOf(x.base))
+ .reduce((m, x) => ((x[0] - m[0] || x[1] - m[1] || x[2] - m[2]) > 0 ? x : m), [0, 0, 0]);
+ const heavier = (x, y) => (x[0] - y[0] || x[1] - y[1] || x[2] - y[2]);
+ const looksOf = (el, copy) => {
+ const from = [el, ...el.querySelectorAll('*')];
+ const to = [copy, ...copy.querySelectorAll('*')];
+ return from.flatMap((src, k) => {
+ const out = to[k];
+ if (!out || out.localName !== src.localName) return [];
+ const said = [];
+ for (const r of rules) {
+ for (const pseudo of pseudosOf(r)) {
+ const mine = found(r, src, pseudo).length > 0;
+ const its = found(r, out, pseudo).length > 0;
+ if (mine && !its) said.push({ sheet: r.sheet, within: r.within, pseudo, weight: weightOf(r, src, pseudo), decls: declsOf(r.style) });
+ if (its && !mine) {
+ const own = rules.filter((x) => found(x, src, pseudo).length);
+ const decls = [];
+ for (let i = 0; i < r.style.length; i++) {
+ const p = r.style[i];
+ /* its own winning rule for it: !important first, then the heavier, then the later */
+ const by = own.filter((x) => x.style.getPropertyValue(p)).sort((x, y) => (
+ (x.style.getPropertyPriority(p) === 'important') - (y.style.getPropertyPriority(p) === 'important')
+ || heavier(weightOf(x, src, pseudo), weightOf(y, src, pseudo)) || x.order - y.order
+ )).at(-1);
+ const priority = by?.style.getPropertyPriority(p) === 'important' ? ' !important' : '';
+ decls.push([p, by ? `${by.style.getPropertyValue(p)}${priority}` : 'unset']);
+ }
+ said.push({ sheet: r.sheet, within: r.within, pseudo, weight: weightOf(r, out, pseudo), decls });
+ }
+ }
+ }
+ return said.length ? [{ path: pathIn(el, src), rules: said }] : [];
+ });
+ };
+ try {
+ /* read with the copies' own new ids: a rule naming an original's id (`#a`, `:not(#a)`) is one more rule it
+ gets and the copy not, or the other way */
+ const looks = els.map((el, i) => looksOf(el, copies[i]));
+ const moved = list.map((o, i) => {
+ const was = before[i];
+ if (!was) return null;
+ /* the copies are elements of the page once written: what finds them too finds others */
+ const now = matches(doc, o);
+ if (now.length === was.length && now.every((n, k) => n === was[k])) return null;
+ return was.length ? was.map((n) => selectorOf(n)).join(', ') : null;
+ });
+ return { places, moved, looks };
+ } finally {
+ for (const copy of copies) copy.remove();
+ }
+ },
/** Stop showing what was not kept on a clip (a refused edit, a cancelled drag). */
release({ clip }) { release(clip); return true; },
/**
diff --git a/packages/openfilm/studio/server/stage.test.mjs b/packages/openfilm/studio/server/stage.test.mjs
index e9aa472..1aeba28 100644
--- a/packages/openfilm/studio/server/stage.test.mjs
+++ b/packages/openfilm/studio/server/stage.test.mjs
@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { HOST_FLAG, folderFiles, launch } from '../../src/host.mjs';
import { filmHtml } from '../../src/film-doc.mjs';
+import { cssEscape, pastedPage } from '../ui/src/lib/layer-paste.ts';
const STAGE = readFileSync(new URL('./stage.js', import.meta.url), 'utf8');
@@ -49,7 +50,7 @@ async function stageOf(dir, query = '') {
window.addEventListener('message', hear);
window.postMessage({ source: 'openfilm-studio', type: 'stage', seq, op, ...args }, '*');
}), { op, args, seq: ++seq });
- return { ask, page, close };
+ return { ask, page, close, browser };
}
test('a click on a page\'s backdrop (a box filling the page) takes the clip, not the box; a smaller box is taken', { timeout: 60_000 }, async () => {
@@ -495,3 +496,225 @@ test('a deleted layer has no row in the Layers tree; what points only at it or i
await stage.close();
}
});
+
+test('a layer to be written into its page or another: where it is laid out, the changes in it, and how it looks', { timeout: 60_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-source-'));
+ writeFileSync(join(dir, 'card.html'), `<!doctype html><head><style>
+#title, p { letter-spacing: 1px } @supports (display: grid) { @layer base { #title b { color: rgb(255, 0, 0) } } }
+#col > p:nth-child(3) { color: rgb(0, 128, 0) }
+</style></head><body style="margin:0">
+<div id="col" style="position:absolute;left:10px;top:10px;width:200px">
+ <h1 id="title" style="margin:0 0 4px;font:700 20px sans-serif" onclick="go()">Every <b>parcel</b></h1>
+ <p class="note" style="margin:0">On time</p>
+ <p class="note" style="margin:0">Late</p>
+ <svg id="logo" width="20" height="10"><linearGradient id="g"/><rect fill="url(#g)" width="20" height="10"/></svg>
+</div>
+<script>window.film={duration:2,frame(){}}</script></body>`);
+ const overrides = [{ at: '#title b', style: { color: 'blue' } }, { at: '#col > p:nth-of-type(2)', t: [4, 0] }, { at: '.note', n: 2, text: 'Very late' }];
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'card', src: 'card.html', overrides }] }] }));
+ const stage = await stageOf(dir);
+ try {
+ const [title, late, logo] = await stage.ask('layerSource', { clip: 'card', of: [{ at: '#title' }, { at: '.note', n: 2 }, { at: '#logo' }] });
+ assert.deepEqual([title.at, title.tag, title.id, title.text], ['#title', 'h1', 'title', 'Every parcel']);
+ assert.deepEqual([title.place.position, title.place.left, title.place.top], ['static', 0, 0]);
+ assert.deepEqual(title.tweaks, [{ path: [0], tag: 'b', style: { color: 'blue' } }]);
+ assert.equal(late.text, 'Late', 'its words as the page has them, not as the clip changed them');
+ assert.ok(logo.place && logo.place.width === 20 && logo.place.height === 10 && Number.isFinite(logo.place.left), `an <svg> is measured too (${JSON.stringify(logo.place)})`);
+ assert.match(title.snapshot.html, /^<h1 id="title" style="[^"]*position: absolute; left: 10px; top: 10px;[^"]*">Every <b style="[^"]*color: rgb\(0, 0, 255\)/);
+ assert.ok(!/ class=|onclick/.test(title.snapshot.html), 'no class (another page\'s CSS does not reach it), no handler');
+ assert.match(logo.snapshot.html, /id="g"/, 'its ids kept, to be made new ones where it goes');
+ /* copies of both notes: the first's goes after the second (right after it, the page's :nth-child(3) would color
+ the other), and nothing the clip points at is another element then */
+ const after = await stage.ask('afterCopy', { clip: 'card', of: [{ at: '#col > p:nth-of-type(1)' }, { at: '#col > p:nth-of-type(2)' }] });
+ const kids = ['h1', 'p', 'p', 'svg'];
+ assert.deepEqual([after.places, after.moved], [[{ after: 2, siblings: kids }, { after: 2, siblings: kids }], [null, null, null]]);
+ } finally {
+ await stage.close();
+ }
+});
+
+test('a layer the page\'s code moved in it: known by its words as the page has them', { timeout: 60_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-moved-'));
+ writeFileSync(join(dir, 'card.html'), `<!doctype html><body style="margin:0"><div id="col"><p class="note">First in file</p><p class="note">Second in file</p></div>
+<script>document.getElementById('col').prepend(Object.assign(document.createElement('p'), { className: 'note', textContent: 'made by script' }));
+window.film={duration:2,frame(){}}</script></body>`);
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'card', src: 'card.html' }] }] }));
+ const stage = await stageOf(dir);
+ try {
+ const [layer] = await stage.ask('layerSource', { clip: 'card', of: [{ at: '#col > p.note:nth-of-type(2)' }] });
+ assert.equal(layer.text, 'First in file');
+ } finally {
+ await stage.close();
+ }
+});
+
+test('a copy written right after a layer: what the clip counted after it points at what it found', { timeout: 60_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-after-'));
+ writeFileSync(join(dir, 'card.html'), `<!doctype html><body style="margin:0"><div id="col"><p id="a">A</p><p id="b">B</p><p>C</p></div>
+<script>window.film={duration:2,frame(){}}</script></body>`);
+ const overrides = [{ at: '#col > p:nth-of-type(3)', style: { color: 'red' } }, { at: 'p', n: 2, t: [4, 0] }];
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'card', src: 'card.html', overrides }] }] }));
+ const stage = await stageOf(dir);
+ try {
+ const after = await stage.ask('afterCopy', { clip: 'card', of: [{ at: '#a' }, { at: '#b' }] });
+ assert.deepEqual([after.places, after.moved], [[{ after: 0, siblings: ['p', 'p', 'p'] }, { after: 1, siblings: ['p', 'p', 'p'] }], ['#col > p:nth-of-type(5)', '#b']], 'both copies counted at once');
+ } finally {
+ await stage.close();
+ }
+});
+
+test('a copy goes where the page\'s CSS draws nothing beside it otherwise: not where a :last-child or :nth-child would move', { timeout: 60_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-place-'));
+ writeFileSync(join(dir, 'card.html'), `<!doctype html><head><style>#col p:nth-child(2) { color: rgb(255, 0, 0) } #col p:last-child { color: rgb(0, 128, 0) }</style></head>
+<body style="margin:0"><div id="col"><p id="a">A</p><p id="b">B</p><p id="c">C</p></div><script>window.film={duration:2,frame(){}}</script></body>`);
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'card', src: 'card.html' }] }] }));
+ const stage = await stageOf(dir);
+ try {
+ const siblings = ['p', 'p', 'p'];
+ assert.deepEqual((await stage.ask('afterCopy', { clip: 'card', of: [{ at: '#a' }] })).places, [{ after: 1, siblings }], 'A: after B');
+ assert.deepEqual((await stage.ask('afterCopy', { clip: 'card', of: [{ at: '#c' }] })).places, [{ after: 1, siblings }], 'C: before it');
+ assert.deepEqual((await stage.ask('afterCopy', { clip: 'card', of: [{ at: '#b' }] })).places, [{ after: 1, siblings }], 'B: right after it');
+ /* and so drawn: B red, C green, with a copy of A written there */
+ const colors = await stage.page.evaluate(() => {
+ const doc = document.querySelector('iframe').contentDocument;
+ const copy = doc.getElementById('a').cloneNode(true);
+ copy.id = 'a-copy';
+ doc.getElementById('b').after(copy);
+ const out = ['b', 'c'].map((id) => getComputedStyle(doc.getElementById(id)).color);
+ copy.remove();
+ return out;
+ });
+ assert.deepEqual(colors, ['rgb(255, 0, 0)', 'rgb(0, 128, 0)']);
+ } finally {
+ await stage.close();
+ }
+});
+
+/**
+ * A paste into its own page, as the editor makes it (layerSource, afterCopy, lib/layer-paste pastedPage), the page
+ * then drawn as written: per element asked, `props` of it and of its copy, and the color of every other element.
+ */
+async function pastedLook(css, body, id, props, at = 0.5, pseudos = []) {
+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-look-'));
+ const page = `<!doctype html><head><style>${css}</style></head><body style="margin:0">${body}<script>window.film={duration:2,frame(){}}</script></body>`;
+ writeFileSync(join(dir, 'card.html'), page);
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'card', src: 'card.html' }] }] }));
+ const stage = await stageOf(dir);
+ try {
+ const [layer] = await stage.ask('layerSource', { clip: 'card', of: [{ at: `#${cssEscape(id)}` }] });
+ const after = await stage.ask('afterCopy', { clip: 'card', of: [{ at: `#${cssEscape(id)}` }] });
+ const target = await stage.page.evaluate((id) => {
+ const doc = document.querySelector('iframe').contentDocument;
+ const shapeOf = (el) => ({ tag: el.localName, children: [...el.children].map(shapeOf) });
+ const el = doc.getElementById(id);
+ const path = [];
+ const tags = [];
+ for (let n = el; n !== doc.body; n = n.parentElement) { path.unshift([...n.parentElement.children].indexOf(n)); tags.unshift(n.localName); }
+ return { path, tags, shape: shapeOf(el) };
+ }, id);
+ const out = pastedPage(page, [{ layer, target, place: after.places[0], look: after.looks[0] }], 0);
+ const drawn = await stage.browser.newPage();
+ try {
+ await drawn.setContent(out.text);
+ return await drawn.evaluate(({ id, props, at, pseudos }) => {
+ for (const a of document.getAnimations()) { a.pause(); a.currentTime = at * 1000; }
+ const look = (el) => [
+ ...props.map((p) => getComputedStyle(el).getPropertyValue(p)),
+ ...pseudos.map((pe) => { const cs = getComputedStyle(el, pe); return `${pe} ${cs.content} ${cs.color} ${cs.fontSize}`; }),
+ ];
+ const deep = (el) => [...el.querySelectorAll('*')].map((n) => look(n).join(' '));
+ const copy = document.getElementById(`${id}-copy`);
+ const others = [...document.querySelectorAll('body *:not(script)')].filter((e) => !e.closest('[id$="-copy"]')).map((e) => `${e.id || e.localName}:${getComputedStyle(e).color}`);
+ return { el: look(document.getElementById(id)), copy: look(copy), inside: [deep(document.getElementById(id)), deep(copy)], others };
+ }, { id, props, at, pseudos });
+ } finally { await drawn.close(); }
+ } finally {
+ await stage.close();
+ }
+}
+
+test('a copy looks as its original where the page\'s rules give it a look by its place, and the others stay as they were', { timeout: 120_000 }, async () => {
+ const col = '<div id="col"><p id="a">A<b>!</b></p><p id="b">B</p><p id="c">C</p></div>';
+ const cases = [
+ ['first-child, last-child, p + p', '#col p:first-child{color:red} #col p:last-child{color:green} #col > p + p{border-top:2px solid blue}', ['a', 'c'], ['color', 'border-top-width']],
+ ['a heavier rule still wins', '#col p:first-child{color:red} #col #a{color:blue}', ['a'], ['color']],
+ ['a rule only the copy gets: what it would inherit', '#col{color:rgb(200, 100, 0)} #col p + p{color:blue}', ['a'], ['color']],
+ ['a rule only the copy gets, against a shorthand', '#col p{border:2px solid red} #col p + p{border-top-color:blue}', ['a'], ['border-top-color', 'border-top-width']],
+ ['in a @media, weighed as written', '@media (min-width: 1px){ #col p:first-child{color:red} } #col p{color:blue}', ['a'], ['color']],
+ ['in a @layer', '@layer base { #col p:first-child{color:red} } #col p{color:blue}', ['a'], ['color']],
+ ['nested', '#col { & p:first-child{color:red} }', ['a'], ['color']],
+ ['nested id rule', '#col { & #a{color:red} }', ['a'], ['color']],
+ ['!important', '#col p:first-child{color:red !important} #col #a{color:blue}', ['a'], ['color']],
+ ['a rule of its id, a rule naming it in :not()', '#a{font-weight:700} #col p:not(#a){color:blue}', ['a'], ['color', 'font-weight']],
+ ['an id rule of what is in it, in its at-rules', '@supports (display: grid) { @layer base { #a b{color:red} } } #col b{color:blue}', ['a'], ['color']],
+ ];
+ for (const [name, css, ids, props] of cases) {
+ for (const id of ids) {
+ const before = await pastedLook(css, col, 'b', ['color']).then((x) => x.others);
+ const seen = await pastedLook(css, col, id, props);
+ assert.deepEqual(seen.copy, seen.el, `${name}: the copy of ${id} looks as ${id}`);
+ assert.deepEqual(seen.inside[1], seen.inside[0], `${name}: and what is in it`);
+ assert.deepEqual(seen.others, before, `${name}: the others as they were`);
+ }
+ }
+});
+
+test('an id starting with a digit: the copy\'s rules find it, its id rules are said again of it', { timeout: 60_000 }, async () => {
+ const seen = await pastedLook('#col p:first-child{color:red} #\\31 st{font-weight:700}', '<div id="col"><p id="1st">A</p><p id="b">B</p></div>', '1st', ['color', 'font-weight']);
+ assert.deepEqual(seen.copy, seen.el);
+ assert.deepEqual(seen.el, ['rgb(255, 0, 0)', '700']);
+});
+
+test('a one-digit id, and an id with a dot: the copy keeps its id rules, and only its own', { timeout: 60_000 }, async () => {
+ const one = await pastedLook('#\\31 {font-weight:700} #col p:first-child{color:red}', '<div id="col"><p id="1">A</p><p id="b">B</p></div>', '1', ['color', 'font-weight']);
+ assert.deepEqual(one.copy, one.el);
+ assert.deepEqual(one.el, ['rgb(255, 0, 0)', '700']);
+ const dot = await pastedLook('#a\\.b{color:blue} #a{font-weight:700}', '<div id="col"><p id="a">A</p><p id="a.b">B</p></div>', 'a', ['color', 'font-weight']);
+ assert.deepEqual(dot.copy, dot.el);
+ assert.ok(dot.others.includes('a.b:rgb(0, 0, 255)'), 'the other one as it was');
+});
+
+test('a copy keeps the rules of its pseudo-elements: ::before, ::after, ::first-letter, ::marker, ::placeholder, ::selection', { timeout: 120_000 }, async () => {
+ const pseudos = ['::before', '::after', '::first-letter', '::marker', '::placeholder', '::selection'];
+ const cases = [
+ ['of its id', '#a::before{content:"\\2605";color:red} #a::after{content:"!"} #a::first-letter{font-size:30px} #a::selection{color:green}', '<div id="col"><p id="a">A</p><p id="b">B</p></div>', 'a'],
+ ['by its place', '#col p:first-child::before{content:"1. "} #col p + p::after{content:" (more)"}', '<div id="col"><p id="a">A</p><p id="b">B</p></div>', 'a'],
+ ['a list\'s marker', '#lst li:first-child::marker{color:red}', '<ul id="lst"><li id="a">A</li><li id="b">B</li></ul>', 'a'],
+ ['a field\'s placeholder', '#in::placeholder{color:red}', '<div id="col"><input id="in" placeholder="Name"></div>', 'in'],
+ ];
+ for (const [name, css, body, id] of cases) {
+ const seen = await pastedLook(css, body, id, ['color'], 0.5, pseudos);
+ assert.deepEqual(seen.copy, seen.el, `${name}: the copy's pseudo-elements as its original's`);
+ }
+});
+
+test('a rule of what names an id in the copy (a label\'s for) finds the copy\'s, renamed as it is', { timeout: 60_000 }, async () => {
+ const seen = await pastedLook('label[for="x"]{color:purple} a[href="#x"]{font-weight:700}', '<div id="col"><div id="f"><label for="x">Name</label><a href="#x">go</a><input id="x"></div></div>', 'f', ['color', 'font-weight']);
+ assert.deepEqual(seen.inside[1], seen.inside[0]);
+ assert.ok(seen.inside[0][0].startsWith('rgb(128, 0, 128)'), seen.inside[0][0]);
+});
+
+test('what a copy keeps from its original\'s place stays live: var(), currentColor and an animation', { timeout: 60_000 }, async () => {
+ const css = ':root{--accent: rgb(255, 0, 0)} @keyframes in { from { opacity: 0 } to { opacity: 1 } } #col p:first-child { color: var(--accent); border: 2px solid currentColor; animation: in 1s linear both }';
+ const col = '<div id="col"><p id="a">A</p><p id="b">B</p></div>';
+ for (const at of [0.25, 0.75]) {
+ const seen = await pastedLook(css, col, 'a', ['color', 'border-top-color', 'opacity'], at);
+ assert.deepEqual(seen.copy, seen.el, `at ${at}s`);
+ assert.equal(seen.el[2], String(at));
+ }
+});
+
+test('a copy whose id needs escaping is found by the selector a paste says (to be selected)', { timeout: 60_000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-select-'));
+ writeFileSync(join(dir, 'card.html'), '<!doctype html><body style="margin:0"><p id="1st-copy">A</p><p id="a:b-copy">B</p><script>window.film={duration:2,frame(){}}</script></body>');
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'card', src: 'card.html' }] }] }));
+ const stage = await stageOf(dir);
+ try {
+ for (const id of ['1st-copy', 'a:b-copy']) {
+ const layer = await stage.ask('layer', { clip: 'card', loc: `#${cssEscape(id)}`, any: true });
+ assert.equal(layer?.label, id === '1st-copy' ? 'A' : 'B', id);
+ }
+ } finally {
+ await stage.close();
+ }
+});
diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.ts
index 8404ed3..12d2581 100644
--- a/packages/openfilm/studio/ui/src/api.ts
+++ b/packages/openfilm/studio/ui/src/api.ts
@@ -183,6 +183,17 @@ export const api = {
takeSaved: (id: string, path: string) => call<{ clip: Record<string, unknown> & { src: string } } | { clips: SavedGroupClip[] } | { path: string }>(
`${p(id)}/saved/take`, { method: 'POST', json: { path } },
),
+ /** a page of the project as text, with its rev (studio/server/page-text.mjs) */
+ readPage: (id: string, path: string) => call<{ text: string; rev: string }>(`${p(id)}/page?path=${encodeURIComponent(path)}`),
+ /** a page written (text null: taken away) when it is still the page of rev `expect` (null: none there yet); its new
+ rev. `undo`: the write takes back one of Studio's (a paste undone) */
+ writePage: (id: string, path: string, text: string | null, expect: string | null, undo = false) => (
+ call<{ rev: string | null }>(`${p(id)}/page`, { method: 'PUT', json: { path, text, expect, ...(undo ? { undo: true } : {}) } }).then((r) => r.rev)
+ ),
+ /** a clip of project `from` brought into this one with the files it needs (layers pasted from there): its src here */
+ bringClip: (id: string, from: string, clip: Record<string, unknown> & { src: string }) => (
+ call<{ clip: Record<string, unknown> & { src: string } }>(`${p(id)}/bring`, { method: 'POST', json: { from, clip } }).then((r) => r.clip)
+ ),
};
/** A clip of a saved group: its track counted from the group's top one, its time in seconds from the group's start. */
diff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
index 8736e57..c6ad52f 100644
--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx
@@ -873,8 +873,17 @@ function FilmStageSelectImpl({
syncGeomSoon();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [stale, syncGeomSoon]);
- /* film.html changed (an edit, an undo, the agent): the picture follows it a moment later */
+ /* film.html changed (an edit, an undo, the agent): the picture follows it a moment later. A layer whose clip is not
+ in the film any more (pasted layers undone) lets go */
React.useEffect(() => {
+ const held = pickedRef.current;
+ const ids = new Set(doc.tracks.flatMap((t) => t.clips.map((c) => c.id)));
+ const clips = multiRef.current ? multiRef.current.map((i) => i.layer.clip) : [held?.element?.kind !== 'clip' ? held?.layer?.clip : undefined];
+ if (held && clips.some((clip) => clip && !ids.has(clip))) {
+ dropPick();
+ onSelectElement?.(null);
+ return undefined;
+ }
syncGeomSoon();
const later = window.setTimeout(syncGeomSoon, 150);
return () => window.clearTimeout(later);
@@ -1151,16 +1160,20 @@ function FilmStageSelectImpl({
return;
}
/* the shortcuts are the menu's items: ⇧⌘H hide, ⇧⌘L lock, ] / [ to the front / back, Delete (the timeline's
- keys for it) deletes; grayed ones do nothing. A whole clip's delete / copy / paste are the timeline's keys. */
+ keys for it) deletes, Copy (⌘C, the keymap's) copies the layers, not their clip, unless words are selected
+ somewhere; grayed ones do nothing. A whole clip's delete / copy / paste are the timeline's keys, and so is
+ Paste: it pastes what was copied last, layers or clips. */
const mod = e.metaKey || e.ctrlKey;
const k = e.key.toLowerCase();
const action = keyAction(e);
+ const wordsSelected = () => Boolean(window.getSelection()?.toString());
const menuId = mod && e.shiftKey && k === 'h' ? 'hide'
: mod && e.shiftKey && k === 'l' ? 'lock'
: !mod && !e.altKey && e.key === ']' ? 'front'
: !mod && !e.altKey && e.key === '[' ? 'back'
: action === 'remove' || action === 'ripple-delete' ? 'delete'
- : null;
+ : action === 'copy' && !wordsSelected() ? 'copy-layers'
+ : null;
/* C crops the video or still in hand */
if (!mod && !e.altKey && !e.shiftKey && k === 'c' && !textEdit.current && !typingNow()) {
if (startCrop()) e.preventDefault();
diff --git a/packages/openfilm/studio/ui/src/components/LayersPanel.tsx b/packages/openfilm/studio/ui/src/components/LayersPanel.tsx
index 8517e01..fae0617 100644
--- a/packages/openfilm/studio/ui/src/components/LayersPanel.tsx
+++ b/packages/openfilm/studio/ui/src/components/LayersPanel.tsx
@@ -3,7 +3,7 @@
* a row; a page clip opens into its layers, each level in the order the page draws it. A row selects its layer on
* the picture (and the picture's selection opens the rows down to it); its eye hides it, its lock keeps it from
* being moved and its bin deletes it (lib/layer-delete; Delete or Backspace does too, for the layer in hand on the
- * picture, which a row's click makes it); dragged up or down its own level, or into the level of a row around it
+ * picture, which a row's click makes it); its right-click menu copies, pastes (lib/layer-clipboard) and deletes; dragged up or down its own level, or into the level of a row around it
* (which then moves, with all it holds: CSS restacks only within a level), it is restacked (z-index overrides,
* studio/server/stage.js `restack`). Nothing is kept here: the tree is read from the pages each time they may have
* changed, and every change is an override of the page clip in film.html.
@@ -17,6 +17,7 @@ import {
layerKey, layerLines, movedOrder, moverFor, openTo, sameTree, type LayerClip, type LayerLine, type LayerRow, type LayerRowKind,
} from '@/lib/layers-tree';
import type { StageArrangeResult } from './stage-menu';
+import { ContextMenu, type ContextMenuEntry } from './ContextMenu';
import { PANE_BAR, PANE_BTN, PANE_ICON, PANE_TITLE } from './dock-pane-bar';
import { Tooltip } from './Tooltip';
@@ -48,6 +49,8 @@ export interface LayersPanelProps {
onToggle: (clipId: string, row: LayerRow, what: 'hidden' | 'locked') => void;
/** A row's bin: its layer deleted. */
onDelete: (clipId: string, row: LayerRow) => void;
+ /** A row's right-click menu (its layer is selected first). */
+ rowMenu: (clipId: string, row: LayerRow) => readonly ContextMenuEntry[];
/** A level restacked: the overrides to write in the clip, or why nothing was (a message). */
onRestack: (clipId: string, edits: StageArrangeResult['edits']) => void;
onNotify: (message: string) => void;
@@ -64,6 +67,7 @@ export function LayersPanel(p: LayersPanelProps) {
const [toggled, setToggled] = React.useState<ReadonlySet<string>>(() => new Set());
const askRef = React.useRef(p.ask);
askRef.current = p.ask;
+ const [menu, setMenu] = React.useState<{ x: number; y: number; items: readonly ContextMenuEntry[] } | null>(null);
/* the tree, read again when the picture may have changed: a seek, the film edited, and while it plays */
const read = React.useCallback(async () => {
@@ -210,7 +214,14 @@ export function LayersPanel(p: LayersPanelProps) {
}}
onPoint={() => p.onPoint(line.row ? { clipId: line.clipId, loc: line.row.loc } : null)}
onToggle={(what) => { if (line.row) p.onToggle(line.clipId, line.row, what); }}
- onDelete={() => { if (line.row) p.onDelete(line.clipId, line.row); }} />
+ onDelete={() => { if (line.row) p.onDelete(line.clipId, line.row); }}
+ onMenu={(e) => {
+ if (!line.row) return;
+ e.preventDefault();
+ p.onSelectLayer(line.clipId, line.row.loc);
+ const items = p.rowMenu(line.clipId, line.row);
+ if (items.length) setMenu({ x: e.clientX, y: e.clientY, items });
+ }} />
))}
{drag ? (
<div aria-hidden className="pointer-events-none absolute right-2 h-0.5 rounded-full bg-[var(--accent)]"
@@ -224,11 +235,12 @@ export function LayersPanel(p: LayersPanelProps) {
) : null}
</div>
</div>
+ {menu ? <ContextMenu x={menu.x} y={menu.y} items={menu.items} onClose={() => setMenu(null)} /> : null}
</div>
);
}
-function LayerLineRow({ line, top, t, clipOf, selected, dragging, onToggleOpen, onPress, onClick, onPoint, onToggle, onDelete }: {
+function LayerLineRow({ line, top, t, clipOf, selected, dragging, onToggleOpen, onPress, onClick, onPoint, onToggle, onDelete, onMenu }: {
line: LayerLine;
top: number;
t: ReturnType<typeof useT>;
@@ -241,6 +253,7 @@ function LayerLineRow({ line, top, t, clipOf, selected, dragging, onToggleOpen,
onPoint: () => void;
onToggle: (what: 'hidden' | 'locked') => void;
onDelete: () => void;
+ onMenu: (e: React.MouseEvent) => void;
}) {
const row = line.row;
const clip = row ? null : clipOf(line.clipId);
@@ -264,7 +277,7 @@ function LayerLineRow({ line, top, t, clipOf, selected, dragging, onToggleOpen,
className={`group absolute inset-x-1 flex items-center gap-1 rounded-md pr-1 text-[12.5px] ${selected ? 'bg-[var(--bg-active)] text-[var(--text)]' : 'text-[var(--text-dim)] hover:bg-[var(--bg-hover)]'} ${dragging ? 'opacity-50' : ''}`}
style={{ top, height: ROW_H, paddingLeft: 4 + line.depth * INDENT }}
title={row?.off && !row.hidden ? t('layers.notNow') : undefined}
- onPointerDown={onPress} onClick={onClick} onPointerEnter={onPoint}>
+ onPointerDown={onPress} onClick={onClick} onPointerEnter={onPoint} onContextMenu={onMenu}>
{line.canOpen ? (
<button type="button" aria-label={t(line.open ? 'layers.collapse' : 'layers.expand')}
onPointerDown={(e) => e.stopPropagation()}
diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
index c5af0e3..92153b8 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
@@ -7,11 +7,11 @@
* are written one at a time (see editor/use-film.ts); the agent's writes come in through the folder's events.
*/
import * as React from 'react';
-import { BookmarkPlus, ClipboardCopy, ClipboardPaste, GalleryVerticalEnd, Layers, LibraryBig, MessageSquarePlus, MonitorDown, Settings2, TriangleAlert, Upload } from 'lucide-react';
+import { BookmarkPlus, ClipboardCopy, ClipboardPaste, GalleryVerticalEnd, Layers, LibraryBig, MessageSquarePlus, MonitorDown, Settings2, Trash2, TriangleAlert, Upload } from 'lucide-react';
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 { useFilm, type OutsideStep, type Step } from '@/editor/use-film';
import { Player } from '@/editor/player';
import { Preview, type FilmInfo, type PlayedReport, type PreviewHandle } from '@/editor/Preview';
import { usePreviewRenders } from '@/editor/use-preview-renders';
@@ -20,10 +20,10 @@ import { changesPicture } from '@/lib/picture-files';
import { SPEED_MAX } from '@/lib/playback-speed';
import type { ReplaceFamily } from '@/lib/clip-replace';
import { layoutTracks, type TimelineBlock, type TimelineTrack } from '@/lib/timeline-layout';
-import { filmClipKind, filmSrcIsPage, filmSrcKind, filmTrackBadges, parseFilmDocLoc, type FilmBox, type FilmDoc, type FilmOverride } from '@/lib/film';
+import { filmClipKind, filmDocLoc, filmSrcIsPage, filmSrcKind, filmTrackBadges, parseFilmDocLoc, type FilmBox, type FilmDoc, type FilmOverride } from '@/lib/film';
import { exactRate, footageFps, setTimecodeFps, snapToFrame, stepFrames } from '@/lib/timecode';
import { JUMP_FRAMES, loopBack, playStart, shuttleRate } from '@/lib/timeline-keys';
-import { comboOf, parseCombo } from '@/lib/keymap';
+import { comboOf, hintOf, parseCombo } from '@/lib/keymap';
import { currentKeymap, keyAction, useKeyHint } from '@/lib/keymap-store';
import { attrsOf, pasteAttrs, type AttrGroup, type CopiedAttrs } from '@/lib/clip-attrs';
import { cutPoints, namedTrack, nextCut, trackNamesOf } from '@/lib/timeline-nav';
@@ -31,7 +31,7 @@ import { anyLocked, lockedEdits } from '@/lib/track-lock';
import { placeMedia, type SourceRange } from '@/lib/media-place';
import { apartOnTracks, type ClipEdit } from '@/lib/film-clip-edits';
import { mediaFetch, useMediaImages } from '@/lib/media-queue';
-import { clipboardItemsOf, clipboardNow, pasteEdit, type TimelineClipboardItem } from '@/lib/timeline-clipboard';
+import { clipboardItemsOf, clipboardNow, laneOfBlock, pasteEdit, type TimelineClipboardItem } from '@/lib/timeline-clipboard';
import { editModelOf, freshLink, linkedIds, magnetOn, mainTrackOf, planMove, planRippleTrim, planRoom, planSpeed, soundTrackFor, type EditMode } from '@/lib/timeline-edit';
import { readTimelinePrefs, switchesOf } from '@/lib/timeline-prefs';
import { fadeMsOf, type FadeMs } from '@/lib/clip-fade';
@@ -101,12 +101,18 @@ import { ExportTray, type ExportTrayHandle } from './export/ExportTray';
import { FilmStageSelect, type FilmStageControl, type LayerGeometry, type StageClipEdit, type StagePick } from './FilmStageSelect';
import { openSection } from './inspector-fields';
import { FontScopeContext, type FontScope } from '@/lib/use-fonts';
-import { stageMenu, stageRecoveryMenu, type StageArrangeResult, type StageMenuContext, type StagePictureActions } from './stage-menu';
+import { copyPasteEntries, stageMenu, stageRecoveryMenu, type StageArrangeResult, type StageMenuContext, type StagePictureActions } from './stage-menu';
import type { StageEditFailure, StageTextEdit } from './FilmInspector';
import { layerTarget, pageClipOf, recoverLayer } from '@/lib/stage-layers';
import { pictureStyle, relativeTo, type TemplateControls } from '@/lib/template-controls';
import { propsAttr, propsOf, type ComponentProp } from '@/lib/component-props';
import { pointersOf, propsWithoutDeleted, withDeleted } from '@/lib/layer-delete';
+import {
+ isLayerClipboardKey, PASTE_OFFSET, pasteGoals, pasteOffset, readLayerClipboard, whyNowhere, writeLayerClipboard, type CopiedLayers,
+ type LayerClipboard,
+} from '@/lib/layer-clipboard';
+import { idsIn, pastedElsewhere, pastedPage, withoutPaste, withPaste, type PasteItem, type PasteLayer, type PastedPage } from '@/lib/layer-paste';
+import { pasteTargets, targetById } from '@/lib/layer-paste-target';
import type { PropsHost } from './PropertiesSection';
import type { LayerPropsActions } from './FilmInspector';
import { SAVED, refreshSaved, savedActions, savedSources, useSavedListing } from '@/lib/saved';
@@ -575,6 +581,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {
/* ── the timeline: film.html + where the preview placed each clip ── */
const spans = React.useMemo(() => info?.spans ?? [], [info]);
+ /* the Layers panel reads its tree again when film.html changes, and when the preview drew the film anew (a page
+ written: a layer pasted into it, or the agent's edit) */
+ const layersKey = React.useMemo(() => ({}), [film.film, info]); // eslint-disable-line react-hooks/exhaustive-deps
/* a file's length draws a clip that plays to its end before the preview places it (a split's second half, a drop) */
const mediaFacts = React.useMemo<MediaFacts>(() => new Map([...facts].map(([path, f]) => [path, { audio: f.audio, ...(f.durationMs ? { duration: f.durationMs / 1000 } : {}) }])), [facts]);
const [pendingDrops, setPendingDrops] = React.useState<PendingDrop[]>([]);
@@ -783,9 +792,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {
* it is a step of its own before this one (and is never written after an undo, over it).
*/
const filmEdit = film.edit;
- const edit = React.useCallback((ops: Op[], label?: string, quiet?: boolean) => {
+ const edit = React.useCallback((ops: Op[], label?: string, quiet?: boolean, outside?: OutsideStep) => {
stageControl.current?.flushPending();
- return filmEdit(ops, label, quiet);
+ return filmEdit(ops, label, quiet, outside);
}, [filmEdit]);
/** `quiet`: the caller shows why an edit was refused itself (the inspector does, beside its field) */
const editBlocks = React.useCallback((asked: ClipEdit[], quiet = false): Promise<string | null> => {
@@ -999,6 +1008,20 @@ export function ProjectView({ projectId, onProject, onLeave }: {
], clipStep('history.stepDetachAudio', [block.clipId]));
}, [edit, editModel, t]);
const [clipboard, setClipboard] = React.useState<readonly TimelineClipboardItem[]>([]);
+ /* layers copied (lib/layer-clipboard): kept in the browser, so another window or project pastes them too; the
+ timeline's clipboard and this one are emptied by a copy to the other, so a paste pastes what was copied last */
+ const [layerBoard, setLayerBoard] = React.useState<LayerClipboard | null>(readLayerClipboard);
+ const layerBoardRef = React.useRef(layerBoard);
+ layerBoardRef.current = layerBoard;
+ React.useEffect(() => {
+ const onStorage = (e: StorageEvent) => { if (isLayerClipboardKey(e.key)) setLayerBoard(readLayerClipboard()); };
+ window.addEventListener('storage', onStorage);
+ return () => window.removeEventListener('storage', onStorage);
+ }, []);
+ const keepLayerBoard = React.useCallback((board: LayerClipboard | null) => {
+ writeLayerClipboard(board);
+ setLayerBoard(board);
+ }, []);
/* the clips copied as film.html had them then: a clip cut (⌘X) is gone from the film, and is pasted from these */
const copiedClips = React.useRef(new Map<string, Clip>());
const copyBlocks = React.useCallback((blocks: readonly TimelineBlock[]) => {
@@ -1008,7 +1031,213 @@ export function ProjectView({ projectId, onProject, onLeave }: {
return clip ? [[clip.id, structuredClone(clip)] as const] : [];
}));
setClipboard(clipboardItemsOf(blocks, timelineTracks));
- }, [timelineTracks]);
+ keepLayerBoard(null);
+ }, [timelineTracks, keepLayerBoard]);
+ /**
+ * Layers copied (⌘C, the menus): per page clip, each as writing it into a page needs it (studio/server/stage.js
+ * `layerSource`). Null, or why not.
+ */
+ const copyLayers = React.useCallback(async (elements: readonly StageElement[]): Promise<string | null> => {
+ const doc = filmRef.current as unknown as FilmDoc | null;
+ if (!doc) return t('layers.copyFail');
+ const byClip = new Map<string, { clip: FilmDoc['tracks'][number]['clips'][number]; targets: OverrideTarget[] }>();
+ for (const element of elements) {
+ const found = pageClipOf(doc, element);
+ const target = layerTarget(element);
+ if (!found || !target) continue;
+ const entry = byClip.get(found.clip.id) ?? { clip: found.clip, targets: [] };
+ entry.targets.push(target);
+ byClip.set(found.clip.id, entry);
+ }
+ const clips: CopiedLayers[] = [];
+ for (const { clip, targets } of byClip.values()) {
+ const layers = await preview.current?.stage?.<(PasteLayer | null)[]>('layerSource', { clip: clip.id, of: targets });
+ if (!layers?.length || layers.some((l) => !l)) return t('layers.copyFail');
+ clips.push({ from: clip.id, src: clip.src, layers: layers as PasteLayer[] });
+ }
+ if (!clips.length) return t('layers.copyFail');
+ keepLayerBoard({ project: projectId, atMs: Math.round(timeRef.current), clips });
+ setClipboard([]);
+ return null;
+ }, [keepLayerBoard, projectId, t]);
+ /* one paste at a time: the next one reads the page the last one wrote, as the picture draws it */
+ const pasting = React.useRef<Promise<unknown>>(Promise.resolve());
+ /**
+ * The copied layers pasted (lib/layer-clipboard pasteGoals): each written into a page (lib/layer-paste), into its
+ * own page as itself, into another page as it looks, the files it loads brought in first from another project.
+ * Every page written and film.html's changes are one step: one undo takes them all back. The first pasted layer is
+ * selected, to be moved. Null, or why not.
+ */
+ const pasteLayers = React.useCallback((intoLoc: string | null): Promise<string | null> => {
+ const run = pasting.current.then(() => pasteNowRef.current(intoLoc));
+ pasting.current = run.catch(() => {});
+ return run;
+ }, []);
+ const pasteNowRef = React.useRef<(intoLoc: string | null) => Promise<string | null>>(async () => null);
+ pasteNowRef.current = async (intoLoc: string | null): Promise<string | null> => {
+ const board = layerBoardRef.current;
+ const doc = filmRef.current as unknown as FilmDoc | null;
+ if (!board || !doc) return t('timeline.menuPasteEmpty');
+ const pageClips = doc.tracks.flatMap((track) => track.clips.filter((c) => filmSrcIsPage(c.src)).map((c) => ({ id: c.id, src: c.src, locked: Boolean(track.locked), hidden: Boolean(track.hidden) })));
+ const heldLoc = intoLoc ?? stageElementRef.current?.clipLoc ?? null;
+ const heldAt = heldLoc ? parseFilmDocLoc(heldLoc) : null;
+ const heldId = heldAt ? doc.tracks[heldAt.track]?.clips[heldAt.clip]?.id : undefined;
+ const now = timeRef.current;
+ const under = pageClips.filter((c) => {
+ const b = blocksRef.current.find((x) => x.clipId === c.id);
+ return !c.hidden && b && now >= b.startMs && now < b.endMs;
+ });
+ const goals = pasteGoals(board, projectId, pageClips.find((c) => c.id === heldId) ?? null, under, pageClips);
+ if (!goals.length) return t(whyNowhere(board, projectId, pageClips) === 'locked' ? 'timeline.trackLocked' : 'layers.pasteNoPage');
+ const { spot, n } = pasteOffset(board, goals);
+ /* from another project: the files it loads brought in first (none: nothing to bring) */
+ let moved = (path: string) => path;
+ const loads = board.clips.some((c) => c.layers.some((l) => l.snapshot && [l.snapshot.html, ...l.snapshot.fonts].some((x) => x.includes(l.snapshot!.base))));
+ if (board.project !== projectId && loads) {
+ try {
+ /* each page's files (copied from several clips: each one's), all under the same place here */
+ let prefix = '';
+ for (const src of new Set(board.clips.map((c) => c.src))) {
+ const brought = (await api.bringClip(projectId, board.project, { src })).src;
+ prefix = brought.slice(0, brought.length - src.length);
+ }
+ moved = (path) => `${prefix}${path}`;
+ } catch (e) {
+ return e instanceof Error ? e.message : String(e);
+ }
+ }
+ const ops: Op[] = [];
+ const steps: OutsideStep[] = [];
+ const sources = new Map<string, string>();
+ let first: { clip: string; at: string } | null = null;
+ const made: string[] = [];
+ const undoAll = async () => { for (const st of [...steps].reverse()) await st.undo().catch(() => null); };
+ for (const goal of goals) {
+ const into = doc.tracks.flatMap((track) => track.clips).find((c) => c.id === goal.clip)!;
+ let page: { text: string; rev: string };
+ try { page = await api.readPage(projectId, into.src); } catch (e) { await undoAll(); return e instanceof Error ? e.message : String(e); }
+ let out: PastedPage | null = null;
+ if (goal.kind === 'own') {
+ const targets = pasteTargets(page.text, goal.layers);
+ const after = targets ? await preview.current?.stage?.<{
+ places: { after: number; siblings: string[] }[];
+ moved: (string | null)[];
+ looks: NonNullable<PasteItem['look']>[];
+ }>('afterCopy', { clip: into.id, of: goal.layers.map((l) => ({ at: l.at })) }) : null;
+ /* pasted at this spot before: over the last copy */
+ const lastAts = board.pasted?.spot === spot ? board.pasted.ats ?? [] : [];
+ out = targets && after ? pastedPage(page.text, goal.layers.map((layer, i) => {
+ const lastId = lastAts[i] ? idsIn(lastAts[i]!)[0]?.id : undefined;
+ const last = lastId ? targetById(page.text, lastId) : null;
+ return { layer, target: targets[i]!, place: after.places[i], look: after.looks[i], ...(last ? { over: last } : {}) };
+ }), PASTE_OFFSET * n) : null;
+ /* the clip's changes that would find others once the copies are there point at what they found */
+ if (out && after && into.overrides) {
+ const overrides = structuredClone(into.overrides);
+ after.moved.forEach((at, i) => { const o = overrides[i]; if (at && o?.at) { o.at = at; delete o.n; } });
+ if (JSON.stringify(overrides) !== JSON.stringify(into.overrides)) ops.push({ op: 'set', clip: into.id, field: 'overrides', value: overrides });
+ }
+ }
+ /* another page, or a layer its page's code makes as it plays (it is not in the file): as it looks */
+ out ??= pastedElsewhere(page.text, into.src, goal.layers, PASTE_OFFSET * n, board.project === projectId ? undefined : moved);
+ if (!out) { await undoAll(); return t('layers.copyFail'); }
+ const written = await writeIntoPage(into, page, out, ops);
+ if (typeof written === 'string') { await undoAll(); return written; }
+ steps.push(written.step);
+ if (written.src !== into.src) sources.set(into.src, written.src);
+ const at = out.ats.find(Boolean);
+ if (!first && at) first = { clip: into.id, at };
+ made.push(...out.ats);
+ }
+ const outside: OutsideStep = {
+ undo: async () => { for (const st of [...steps].reverse()) { const why = await st.undo(); if (why) return why; } return null; },
+ redo: async () => { for (const st of steps) { const why = await st.redo(); if (why) return why; } return null; },
+ };
+ if (ops.length) {
+ const failed = await edit(ops, 'history.stepPaste', false, outside);
+ if (failed) { await undoAll(); return failed; }
+ } else film.record('history.stepPaste', outside);
+ /* a clip given a page of its own: the layers copied from it are of that page now */
+ const clips = board.clips.map((c) => (sources.has(c.src) ? { ...c, src: sources.get(c.src)! } : c));
+ keepLayerBoard({ ...board, clips, pasted: { spot, n, ats: made } });
+ if (first) await selectPasted(first.clip, first.at, 40);
+ return null;
+ };
+ /**
+ * The page of clip `into` written as a paste made it (`out`, from the page read as `page`). A page other clips show
+ * too is not written: this clip gets a page of its own first (`<name> 2.html` beside it, its src in `ops`), the others
+ * keep theirs as it is. Its undo puts the page back, or, the page changed since (the agent wrote it), takes out what
+ * the paste wrote in. The step, and the page's place; or why it was not written.
+ */
+ const writeIntoPage = async (into: FilmDoc['tracks'][number]['clips'][number], page: { text: string; rev: string }, out: PastedPage, ops: Op[]): Promise<{ step: OutsideStep; src: string } | string> => {
+ const doc = filmRef.current as unknown as FilmDoc | null;
+ const shared = Boolean(doc?.tracks.some((track) => track.clips.some((x) => x.id !== into.id && x.src === into.src)));
+ const text = out.text;
+ try {
+ if (shared) {
+ const dot = into.src.lastIndexOf('.');
+ const [stem, ext] = dot > into.src.lastIndexOf('/') ? [into.src.slice(0, dot), into.src.slice(dot)] : [into.src, '.html'];
+ let path = '';
+ let rev: string | null = null;
+ for (let k = 2; rev == null; k++) {
+ path = `${stem} ${k}${ext}`;
+ rev = await api.writePage(projectId, path, text, null).catch((e: unknown) => {
+ if (e instanceof ApiError && e.status === 409 && k < 50) return null;
+ throw e;
+ });
+ }
+ const made = rev;
+ ops.unshift({ op: 'set', clip: into.id, field: 'src', value: path });
+ return {
+ src: path,
+ step: {
+ /* written since (the agent): kept, the clip goes back to the page it showed */
+ undo: () => api.writePage(projectId, path, null, made, true).then(() => null, () => null),
+ redo: () => api.writePage(projectId, path, text, null).then(() => null),
+ },
+ };
+ }
+ const path = into.src;
+ const made = await api.writePage(projectId, path, text, page.rev);
+ /* an undo of a page written since takes out what the paste wrote, and says where it was, for the redo */
+ let undone: { rev: string | null; at: number[]; text: string } | null = null;
+ return {
+ src: path,
+ step: {
+ undo: async () => {
+ try {
+ await api.writePage(projectId, path, page.text, made, true);
+ undone = null;
+ return null;
+ } catch (e) {
+ if (!(e instanceof ApiError && e.status === 409)) throw e;
+ const now = await api.readPage(projectId, path);
+ const back = withoutPaste(now.text, out.inserted);
+ if (back == null) return t('layers.pasteChanged');
+ undone = { rev: await api.writePage(projectId, path, back.text, now.rev, true), at: back.at, text: back.text };
+ return null;
+ }
+ },
+ redo: async () => {
+ if (!undone) await api.writePage(projectId, path, text, page.rev);
+ else await api.writePage(projectId, path, withPaste(undone.text, out.inserted, undone.at), undone.rev);
+ return null;
+ },
+ },
+ };
+ } catch (e) {
+ return e instanceof Error ? e.message : String(e);
+ }
+ };
+ /* what was pasted is selected once the picture draws it (a new page loads first) */
+ const selectPasted = async (clipId: string, layer: string, tries = 20) => {
+ for (let k = 0; k < tries; k++) {
+ const loc = (filmRef.current as unknown as FilmDoc | null)?.tracks.flatMap((tr, ti) => tr.clips.map((c, ci) => (c.id === clipId ? filmDocLoc(ti, ci) : null))).find(Boolean);
+ const there = loc ? await preview.current?.stage?.<object>('layer', { clip: clipId, loc: layer, any: true }) : null;
+ if (loc && there) { selectStageParent(layer, loc); return; }
+ await new Promise((done) => window.setTimeout(done, 150));
+ }
+ };
/**
* A paste (⌘V, the menu) at a time: onto the track pointed at (`lane`) or each copy's own, never cutting what is
* there: a taken spot opens a track beside it, and with the magnet a copy for the main track goes right above it
@@ -1016,6 +1245,12 @@ export function ProjectView({ projectId, onProject, onLeave }: {
* new id).
*/
const pasteAt = React.useCallback((lane: string | null, atMs: number): Promise<string | null> => {
+ /* layers copied last: pasted as layers, over a clip of that row when one is selected there */
+ if (layerBoardRef.current) {
+ const row = lane ? timelineTracks.find((tr) => tr.lane === lane) : null;
+ const picked = row?.blocks.find((b) => selectedBlocks.some((x) => x.id === b.id) && b.loc);
+ return pasteLayers(picked?.loc ?? row?.blocks.find((b) => b.loc)?.loc ?? null);
+ }
if (!clipboard.length) return Promise.resolve(t('timeline.menuPasteEmpty'));
const { items, missing } = clipboardNow(clipboard, timelineTracks);
const cut = clipboard.filter((item) => !items.some((i) => i.clipId === item.clipId) && copiedClips.current.has(item.clipId));
@@ -1033,7 +1268,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
return { ...rest, clip };
});
return edit(written, 'history.stepPaste');
- }, [clipboard, timelineTracks, editModel, edit, t, toast]);
+ }, [clipboard, timelineTracks, selectedBlocks, pasteLayers, editModel, edit, t, toast]);
/** Room for clips dropped onto a track (an insert pushes on, an overwrite cuts out): after the inserts, in one edit. */
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 }] : []));
@@ -1724,6 +1959,28 @@ export function ProjectView({ projectId, onProject, onLeave }: {
setPointedLayer(null);
void deleteLayers([layerElement(clipId, at, row.instance, row.label)]).then((f) => { if (f) toast.show(f); });
}, [deleteLayers, toast]); // eslint-disable-line react-hooks/exhaustive-deps
+ /* a Layers row's right-click menu: Copy and Paste as on the picture, and Delete as its bin */
+ const layerRowMenu = React.useCallback((clipId: string, row: LayerRow): readonly ContextMenuEntry[] => {
+ const at = row.instance ? row.loc.slice(0, -`#${row.instance}`.length) : row.loc;
+ const clipLoc = blocksRef.current.find((b) => b.clipId === clipId)?.loc;
+ const element = { ...layerElement(clipId, at, row.instance, row.label), ...(clipLoc ? { clipLoc } : {}) };
+ const isLocked = (loc: string) => Boolean(tracksRef.current.find((tr) => tr.blocks.some((b) => b.loc === loc))?.locked);
+ const paste = (loc: string) => {
+ const lane = tracksRef.current.find((tr) => tr.blocks.some((b) => b.loc === loc))?.lane ?? null;
+ void (layerBoardRef.current ? pasteLayers(loc) : pasteAt(lane, timeRef.current)).then((f) => { if (f) toast.show(f); });
+ };
+ return [
+ ...copyPasteEntries([element], {
+ copyLayers: (list) => { void copyLayers(list).then((f) => { if (f) toast.show(f); }); },
+ clip: { isLocked, canPaste: () => clipboard.length > 0 || layerBoardRef.current != null, paste },
+ }, t),
+ { id: 'delete-sep', separator: true },
+ {
+ id: 'delete', label: t('timeline.removeBlock'), icon: <Trash2 size={14} />, danger: true, shortcut: hintOf(currentKeymap(), 'remove', MAC),
+ disabled: row.locked, hint: t('stageMenu.lockedHint'), onSelect: () => deleteLayerRow(clipId, row),
+ },
+ ];
+ }, [copyLayers, pasteLayers, pasteAt, clipboard, deleteLayerRow, t, toast]); // eslint-disable-line react-hooks/exhaustive-deps
const restackLayers = React.useCallback((clipId: string, edits: StageArrangeResult['edits']) => {
void editStageOverrides(edits.map(({ target, style }) => ({ element: layerElement(clipId, target.at, target.n, target.at), patch: { style } as OverrideGeometry })))
.then((f) => { if (f) toast.show(f); });
@@ -1822,6 +2079,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
editOverride: (element, patch) => { void editStageOverrideRef.current(element, patch).then((f) => { if (f) toast.show(f); }); },
editOverrides: (list) => { void editStageOverrides(list).then((f) => { if (f) toast.show(f); }); },
deleteLayers: (list) => { void deleteLayers(list).then((f) => { if (f) toast.show(f); }); },
+ copyLayers: (list) => { void copyLayers(list).then((f) => { if (f) toast.show(f); }); },
selectParent: selectStageParent,
selectClip: selectStageClip,
notify: (message) => toast.show(message),
@@ -1836,8 +2094,9 @@ export function ProjectView({ projectId, onProject, onLeave }: {
if (under.length) void splitBlocks(under, now).then((f) => { if (f) toast.show(f); });
},
copy: (clipLoc) => { const b = blockAt(clipLoc); if (b) copyBlocks([b]); },
- canPaste: () => clipboard.length > 0,
+ canPaste: () => clipboard.length > 0 || layerBoardRef.current != null,
paste: (clipLoc) => {
+ if (layerBoardRef.current) { void pasteLayers(clipLoc).then((f) => { if (f) toast.show(f); }); return; }
const lane = timelineTracks.find((tr) => tr.blocks.some((b) => b.loc === clipLoc))?.lane ?? null;
void pasteAt(lane, timeRef.current).then((f) => { if (f) toast.show(f); });
},
@@ -1856,7 +2115,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
exportClip: (clipId) => openClipExportRef.current(clipId),
remove: (clipLoc) => { const b = blockAt(clipLoc); if (b) { void removeBlocks(withLinkedBlocks(b)); setStageElement(null); } },
},
- }, t), [editStageOverrides, selectStageParent, selectStageClip, splitBlocks, copyBlocks, clipboard, timelineTracks, pasteAt, editBlocks, removeBlocks, t, toast, pictureActions]); // eslint-disable-line react-hooks/exhaustive-deps
+ }, t), [editStageOverrides, selectStageParent, selectStageClip, splitBlocks, copyBlocks, copyLayers, pasteLayers, clipboard, timelineTracks, pasteAt, editBlocks, removeBlocks, t, toast, pictureActions]); // eslint-disable-line react-hooks/exhaustive-deps
/*
* "Reference in chat", first on the menus of a clip, a layer and a track, when the app around Studio has a chat.
* The references are made when it is chosen: a layer right-clicked is measured just after its menu opens. ⌘L does
@@ -2589,7 +2848,17 @@ export function ProjectView({ projectId, onProject, onLeave }: {
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []);
- const previewKey = React.useCallback((event: KeyboardEvent) => onKeyRef.current(event), []);
+ /* ⌘V with the picture's keyboard pastes what was copied last, as the timeline's does (which does not hear it) */
+ const pasteKeyRef = React.useRef<() => void>(() => {});
+ pasteKeyRef.current = () => {
+ if (!layerBoardRef.current && !clipboard.length) return;
+ const lane = selectedBlocks[0] ? laneOfBlock(timelineTracks, selectedBlocks[0].id) : null;
+ void pasteAt(lane, timeRef.current).then((f) => { if (f) toast.show(f); });
+ };
+ const previewKey = React.useCallback((event: KeyboardEvent) => {
+ if (keyAction(event) === 'paste' && !event.defaultPrevented) { event.preventDefault(); pasteKeyRef.current(); return; }
+ onKeyRef.current(event);
+ }, []);
/* ── top bar: title, menus, panels ── */
const [renaming, setRenaming] = React.useState(false);
@@ -2819,7 +3088,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
ask={askStage}
timeMs={timeMs}
playing={playing}
- filmKey={value}
+ filmKey={layersKey}
clipOf={layerClipOf}
selected={stageElement && stageElement.kind !== 'clip' ? { ...(stageElement.clipId ? { clipId: stageElement.clipId } : {}), loc: stageElement.loc } : null}
selectedClipLocs={selectedLocs}
@@ -2828,6 +3097,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onPoint={setPointedLayer}
onToggle={toggleLayerRow}
onDelete={deleteLayerRow}
+ rowMenu={layerRowMenu}
onRestack={restackLayers}
onNotify={toast.show}
width={layersShownWidth}
@@ -3171,7 +3441,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onDropAsset={dropAsset}
onDropFiles={dropFiles}
onExportBlock={openClipExport}
- hasClipboard={clipboard.length > 0}
+ hasClipboard={clipboard.length > 0 || layerBoard != null}
selected={selectedIds}
onSelectedChange={onTimelineSelected}
subtitles={{ on: subs.style.on, onToggle: subs.toggle, count: subs.count, untranscribed: subs.captions?.untranscribed.length ?? 0, onConfigure: configureSubtitles, configuring: inspectorShown && inspectorContent === 'subtitles', onMake: makeSubtitles, making: subs.transcribing, problem: subtitleProblem }}
diff --git a/packages/openfilm/studio/ui/src/components/stage-menu.tsx b/packages/openfilm/studio/ui/src/components/stage-menu.tsx
index 9256d6a..ea02116 100644
--- a/packages/openfilm/studio/ui/src/components/stage-menu.tsx
+++ b/packages/openfilm/studio/ui/src/components/stage-menu.tsx
@@ -4,8 +4,8 @@
* together; and after them on every menu, Show… / Unlock… for the layers that cannot be clicked any more. Items that
* cannot run stay, grayed, with the reason.
*
- * Layer changes are overrides (the editor writes film.html), a delete too (lib/layer-delete); the clip's actions are
- * the editor's, passed in.
+ * Layer changes are overrides (the editor writes film.html), a delete too (lib/layer-delete); a copy of layers is
+ * pasted as new elements of a page (lib/layer-clipboard); the clip's actions are the editor's, passed in.
*/
import type * as React from 'react';
import {
@@ -79,6 +79,8 @@ export interface StageMenuActions {
editOverrides(list: ReadonlyArray<{ element: StageElement; patch: OverrideGeometry | null }>): void;
/** Layers deleted from their clips (lib/layer-delete): one save, one undo step; without it a layer has no Delete. */
deleteLayers?(elements: readonly StageElement[]): void;
+ /** Layers copied (lib/layer-clipboard); without it a layer has no Copy. Paste is the clip's (it pastes what was copied). */
+ copyLayers?(elements: readonly StageElement[]): void;
/** Select the layer at `loc` in the clip at `clipLoc` (a parent). */
selectParent(loc: string, clipLoc?: string): void;
/** Select the whole clip (as on the timeline). */
@@ -143,6 +145,31 @@ function list() {
};
}
+/**
+ * Copy and Paste for layers: the layers copied, and what was copied last (layers or clips) pasted over their clip. The
+ * Layers panel's rows have them too.
+ */
+export function copyPasteEntries(
+ layers: readonly StageElement[],
+ actions: { copyLayers?: StageMenuActions['copyLayers']; clip?: Pick<StageClipActions, 'isLocked' | 'canPaste' | 'paste'> },
+ t: T,
+): ContextMenuEntry[] {
+ const copy = actions.copyLayers;
+ const clip = actions.clip;
+ const clipLoc = layers[0]?.clipLoc;
+ const out: ContextMenuEntry[] = [];
+ if (copy) out.push({ id: 'copy-layers', label: t('timeline.menuCopy'), icon: <CopyIcon size={14} />, shortcut: hintOf(currentKeymap(), 'copy', MAC), onSelect: () => copy(layers) });
+ if (clip && clipLoc) {
+ const trackLocked = clip.isLocked(clipLoc);
+ out.push({
+ id: 'paste-layers', label: t('timeline.menuPaste'), icon: <ClipboardPaste size={14} />, shortcut: hintOf(currentKeymap(), 'paste', MAC),
+ disabled: trackLocked || !clip.canPaste(), hint: trackLocked ? t('timeline.trackLocked') : t('timeline.menuPasteEmpty'),
+ onSelect: () => clip.paste(clipLoc),
+ });
+ }
+ return out;
+}
+
export function stageMenu(el: StageElement, ctx: StageMenuContext, actions: StageMenuActions, t: T): readonly ContextMenuEntry[] {
const m = list();
const lockKeys = shortcutHint('L', { mod: true, shift: true });
@@ -171,6 +198,8 @@ export function stageMenu(el: StageElement, ctx: StageMenuContext, actions: Stag
id: 'lock', label: allLocked ? t('stageMenu.unlock') : t('stageMenu.lock'), icon: allLocked ? <Unlock size={14} /> : <Lock size={14} />, shortcut: lockKeys,
onSelect: () => actions.editOverrides(many.map((x) => ({ element: x, patch: { lock: !allLocked } }))),
});
+ m.sep();
+ for (const entry of copyPasteEntries(many, actions, t)) m.push(entry);
const deleteLayers = actions.deleteLayers;
if (deleteLayers) {
m.sep();
@@ -269,6 +298,8 @@ export function stageMenu(el: StageElement, ctx: StageMenuContext, actions: Stag
const clipLoc = el.clipLoc;
if (clipLoc) m.push({ id: 'clip', label: t('stageMenu.selectClip'), icon: <Layers size={14} />, onSelect: () => actions.selectClip(clipLoc) });
const words = el.text?.value;
+ m.sep();
+ for (const entry of copyPasteEntries([el], actions, t)) m.push(entry);
if (words) m.push({ id: 'copy-text', label: t('stageMenu.copyText'), icon: <CopyIcon size={14} />, onSelect: () => { void navigator.clipboard?.writeText(words).catch(() => {}); } });
const deleteLayers = actions.deleteLayers;
if (deleteLayers) {
diff --git a/packages/openfilm/studio/ui/src/editor/steps.test.ts b/packages/openfilm/studio/ui/src/editor/steps.test.ts
index 4075e9f..28773fa 100644
--- a/packages/openfilm/studio/ui/src/editor/steps.test.ts
+++ b/packages/openfilm/studio/ui/src/editor/steps.test.ts
@@ -2,7 +2,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { applyOps, EditError } from '../../../server/ops.mjs';
import type { Film, Op } from '../api';
-import { dropStep, moveStep, nextStep, pushStep, type Steps } from './steps.ts';
+import { dropStep, inTurn, moveStep, nextStep, pushStep, type Steps } from './steps.ts';
import { inverse } from './undo.ts';
/* The edit history as the editor keeps it (use-film): ⌘Z pressed again and again goes back step by step and stops at
@@ -95,3 +95,24 @@ test('moving or dropping a step touches that step only', () => {
assert.equal(long.done.length, 100);
assert.equal(long.done[0].label, '20');
});
+
+test('two undos pressed at once: the second looks for its step once the first is taken, its writes done', async () => {
+ /* a move (film.html alone), then a paste (its page written first, its film.html part after) */
+ let s: Steps<string> = { done: ['move', 'paste'], undone: [] };
+ const turn = inTurn();
+ const written: string[] = [];
+ const undo = () => turn(async () => {
+ const one = nextStep(s, 'undo');
+ if (!one) return;
+ s = moveStep(s, one, 'undo');
+ if (one === 'paste') { await new Promise((done) => setTimeout(done, 20)); written.push('paste: page'); }
+ written.push(`${one}: film`);
+ });
+ await Promise.all([undo(), undo()]);
+ assert.deepEqual(written, ['paste: page', 'paste: film', 'move: film']);
+ assert.deepEqual(s, { done: [], undone: ['paste', 'move'] });
+ /* one that fails is done too: the next one is taken */
+ const order: string[] = [];
+ await Promise.all([turn(() => { throw new Error('refused'); }).catch(() => order.push('failed')), turn(() => { order.push('next'); })]);
+ assert.deepEqual(order, ['failed', 'next']);
+});
diff --git a/packages/openfilm/studio/ui/src/editor/steps.ts b/packages/openfilm/studio/ui/src/editor/steps.ts
index e33956b..4504b7d 100644
--- a/packages/openfilm/studio/ui/src/editor/steps.ts
+++ b/packages/openfilm/studio/ui/src/editor/steps.ts
@@ -34,3 +34,16 @@ export function nextStep<S>(s: Steps<S>, kind: 'undo' | 'redo'): S | null {
const list = kind === 'undo' ? s.done : s.undone;
return list.length ? list[list.length - 1] : null;
}
+
+/**
+ * Tasks taken one at a time, each once the one before it is done (failed: done too): undo, redo and the history's
+ * jumps, so a step whose writes wait (another file first) is taken before the next one is looked for.
+ */
+export function inTurn(): <T>(task: () => T | Promise<T>) => Promise<T> {
+ let last: Promise<unknown> = Promise.resolve();
+ return (task) => {
+ const run = last.then(task);
+ last = run.catch(() => {});
+ return run;
+ };
+}
diff --git a/packages/openfilm/studio/ui/src/editor/use-film.ts b/packages/openfilm/studio/ui/src/editor/use-film.ts
index b089221..ebd7b86 100644
--- a/packages/openfilm/studio/ui/src/editor/use-film.ts
+++ b/packages/openfilm/studio/ui/src/editor/use-film.ts
@@ -16,14 +16,16 @@ import { applyOps, EditError } from '../../../server/ops.mjs';
import { filmHead } from '../../../../src/film-doc.mjs';
import { api, ApiError, projectEvents, type Film, type Op } from '../api';
import { inverse } from './undo';
-import { dropStep, moveStep, nextStep, pushStep, type Steps } from './steps';
+import { dropStep, inTurn, moveStep, nextStep, pushStep, type Steps } from './steps';
export type FilmState = { value: Film; rev: string };
/**
* One edit a person made here, undoable: what undoes it, what makes it again, and what to call it in the history.
* `outside`: an edit of another file than film.html (a subtitle's times, in its transcript), undone and made again by
- * its own calls, which resolve to null or why they could not; its `undo` and `redo` are empty.
+ * its own calls, which resolve to null or why they could not; its `undo` and `redo` are empty, unless the edit changed
+ * film.html too (a layer pasted into a page of its own): then the other file is undone or made again first, and
+ * film.html only once it is.
*/
export type Step = { undo: Op[]; redo: Op[]; label: string; at: number; outside?: OutsideStep };
export type OutsideStep = { undo: () => Promise<string | null>; redo: () => Promise<string | null> };
@@ -99,7 +101,7 @@ export function useFilm(projectId: string, initial: FilmState | null, onChange:
*/
/* `quiet`: the caller says why it was refused itself (the inspector, beside its field), so `error` is not set.
`one`: the step an undo or redo takes, moved to the other list once applied here */
- const run = useCallback((ops: Op[], record: 'do' | 'undo' | 'redo' = 'do', label = 'history.stepEdit', quiet = false, one?: Step): Promise<string | null> => {
+ const run = useCallback((ops: Op[], record: 'do' | 'undo' | 'redo' = 'do', label = 'history.stepEdit', quiet = false, one?: Step, outside?: OutsideStep): Promise<string | null> => {
const current = ref.current;
if (!current || !ops.length) return Promise.resolve(null);
/* film.html cannot be read: the edit could not be written, and shown it would draw the picture again from the
@@ -119,7 +121,7 @@ export function useFilm(projectId: string, initial: FilmState | null, onChange:
setError(null);
changed.current(after, 'edit');
pending.current += 1;
- const step: Step = { undo: inverse(before, after, ops), redo: ops, label, at: Date.now() };
+ const step: Step = { undo: inverse(before, after, ops), redo: ops, label, at: Date.now(), ...(outside ? { outside } : {}) };
setSteps((s) => (record === 'do' ? pushStep(s, step) : one ? moveStep(s, one, record) : s));
const written = queue.current.then(async (): Promise<string | null> => {
try {
@@ -162,8 +164,9 @@ export function useFilm(projectId: string, initial: FilmState | null, onChange:
}, [projectId, fromServer, setSteps]);
/* a step of another file: moved between the lists at once, its call made in turn with the film's writes; one that
- cannot be undone (the file changed since, elsewhere) leaves both lists, and says why */
- const runOutside = useCallback((step: Step, kind: 'undo' | 'redo') => {
+ cannot be undone (the file changed since, elsewhere) leaves both lists, and says why. Resolves once made: true,
+ or false when it could not be */
+ const runOutside = useCallback((step: Step, kind: 'undo' | 'redo'): Promise<boolean> => {
setSteps((s) => moveStep(s, step, kind));
const written = queue.current.then(async () => {
const why = await step.outside![kind]().catch((e: unknown) => String(e instanceof Error ? e.message : e));
@@ -171,33 +174,48 @@ export function useFilm(projectId: string, initial: FilmState | null, onChange:
setError(why);
setSteps((s) => dropStep(s, step));
}
+ return !why;
});
- queue.current = written;
+ queue.current = written.then(() => {});
+ return written;
}, [setSteps]);
/* a step of the film: one whose ops cannot be applied or written now (the agent removed its clip since) leaves both
- lists, as one of another file does, so the next undo takes the step before it and the history ends at the oldest */
- const step = useCallback((one: Step, kind: 'undo' | 'redo') => {
- if (one.outside) { runOutside(one, kind); return; }
+ lists, as one of another file does, so the next undo takes the step before it and the history ends at the oldest.
+ Resolves once the next step can be taken: at once for film.html alone, once written for another file. */
+ const step = useCallback((one: Step, kind: 'undo' | 'redo'): Promise<void> => {
const ops = kind === 'undo' ? one.undo : one.redo;
+ const drop = (why: string | null) => { if (why) setSteps((s) => dropStep(s, one)); };
+ if (one.outside && !ops.length) return runOutside(one, kind).then(() => {});
+ /* film.html and another file: the other file first, both ways (it can be refused: written since), film.html only
+ once it is written, so the two never disagree */
+ if (one.outside) return runOutside(one, kind).then((ok) => (ok ? run(ops, kind).then(drop) : undefined));
/* nothing to apply (an edit that changed nothing): it only moves */
- if (!ops.length) { setSteps((s) => moveStep(s, one, kind)); return; }
- void run(ops, kind, undefined, false, one).then((why) => { if (why) setSteps((s) => dropStep(s, one)); });
+ if (!ops.length) { setSteps((s) => moveStep(s, one, kind)); return Promise.resolve(); }
+ /* applied here at once: the next step can be taken now, its write queued after this one's */
+ void run(ops, kind, undefined, false, one).then(drop);
+ return Promise.resolve();
}, [run, runOutside, setSteps]);
+ /* undo, redo and the history's jumps one at a time: the next step is looked for once the last one is taken */
+ const turn = useRef(inTurn());
const undo = useCallback(() => {
- const one = nextStep(stepsRef.current, 'undo');
- if (one) step(one, 'undo');
+ void turn.current(() => { const one = nextStep(stepsRef.current, 'undo'); return one ? step(one, 'undo') : undefined; });
}, [step]);
const redo = useCallback(() => {
- const one = nextStep(stepsRef.current, 'redo');
- if (one) step(one, 'redo');
+ void turn.current(() => { const one = nextStep(stepsRef.current, 'redo'); return one ? step(one, 'redo') : undefined; });
}, [step]);
- /** Undo or redo until `done` steps are done (the edit history's rows: click one to go back or forward to it). */
+ /** Undo or redo until `done` steps are done (the edit history's rows: click one to go back or forward to it), one
+ step after another, each once the one before is taken (a step of another file waits for its write) */
const rollbackTo = useCallback((done: number) => {
- let { done: d, undone: u } = stepsRef.current;
- while (d.length > done && d.length) { const one = d[d.length - 1]; step(one, 'undo'); u = [...u, one]; d = d.slice(0, -1); }
- while (d.length < done && u.length) { const one = u[u.length - 1]; step(one, 'redo'); d = [...d, one]; u = u.slice(0, -1); }
+ void turn.current(async () => {
+ let { done: d, undone: u } = stepsRef.current;
+ const order: Array<[Step, 'undo' | 'redo']> = [];
+ while (d.length > done && d.length) { const one = d[d.length - 1]!; order.push([one, 'undo']); u = [...u, one]; d = d.slice(0, -1); }
+ while (d.length < done && u.length) { const one = u[u.length - 1]!; order.push([one, 'redo']); d = [...d, one]; u = u.slice(0, -1); }
+ for (const [one, kind] of order) await step(one, kind);
+ });
}, [step]);
- const edit = useCallback((ops: Op[], label?: string, quiet?: boolean) => run(ops, 'do', label, quiet), [run]);
+ /** `outside`: another file this edit changed too, made already; one undo takes both back (see Step). */
+ const edit = useCallback((ops: Op[], label?: string, quiet?: boolean, outside?: OutsideStep) => run(ops, 'do', label, quiet, undefined, outside), [run]);
/** An edit of another file, made already: kept as a step, so ⌘Z undoes it in turn with the film's. */
const record = useCallback((label: string, outside: OutsideStep) => {
setSteps((s) => pushStep(s, { undo: [], redo: [], label, at: Date.now(), outside }));
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index 9c94c21..69d684e 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -997,6 +997,9 @@ export const en = {
lock: 'Lock',
unlock: 'Unlock',
delete: 'Delete',
+ copyFail: "That layer couldn't be copied. Move the playhead to where it shows and try again.",
+ pasteNoPage: "There's no page under the playhead to paste into. Move the playhead onto one.",
+ pasteChanged: "The page was changed since the paste, so the pasted layer couldn't be taken out of it.",
notNow: 'Not on the picture at this moment',
restackFailed: 'That layer couldn\'t be restacked. The picture may have changed; try again.',
},
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index ebd1d54..afc703a 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -996,6 +996,9 @@ export const es: Words = {
lock: 'Bloquear',
unlock: 'Desbloquear',
delete: 'Eliminar',
+ copyFail: 'No se pudo copiar esa capa. Mueve el cabezal a donde se ve y vuelve a intentarlo.',
+ pasteNoPage: 'No hay ninguna página bajo el cabezal donde pegar. Mueve el cabezal sobre una.',
+ pasteChanged: 'La página cambió después de pegar, así que no se pudo quitar la capa pegada.',
notNow: 'No está en la imagen en este momento',
restackFailed: 'No se pudo reordenar esa capa. Puede que la imagen haya cambiado; inténtalo de nuevo.',
},
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index a0923e2..7ee3244 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -996,6 +996,9 @@ export const ja: Words = {
lock: 'ロック',
unlock: 'ロック解除',
delete: '削除',
+ copyFail: 'このレイヤーをコピーできませんでした。表示される位置に再生ヘッドを移動して、もう一度お試しください。',
+ pasteNoPage: '再生ヘッドの位置に貼り付け先のページがありません。ページの上に再生ヘッドを移動してください。',
+ pasteChanged: '貼り付けの後にページが変更されたため、貼り付けたレイヤーを取り除けませんでした。',
notNow: 'この時点では画面にありません',
restackFailed: 'このレイヤーの重ね順を変更できませんでした。画面が変わった可能性があります。もう一度お試しください。',
},
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 0b51fe2..e7f11b9 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -993,6 +993,9 @@ export const ko: Words = {
lock: '잠금',
unlock: '잠금 해제',
delete: '삭제',
+ copyFail: '이 레이어를 복사할 수 없어요. 레이어가 보이는 곳으로 재생 헤드를 옮긴 뒤 다시 시도해 주세요.',
+ pasteNoPage: '재생 헤드 아래에 붙여 넣을 페이지가 없어요. 재생 헤드를 페이지 위로 옮겨 주세요.',
+ pasteChanged: '붙여 넣은 뒤 페이지가 바뀌어서 붙여 넣은 레이어를 빼낼 수 없었어요.',
notNow: '지금은 화면에 없습니다',
restackFailed: '이 레이어의 순서를 바꾸지 못했습니다. 화면이 바뀌었을 수 있으니 다시 시도하세요.',
},
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index 31545a2..2302cf4 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -997,6 +997,9 @@ export const zhCN: Words = {
lock: '锁定',
unlock: '解锁',
delete: '删除',
+ copyFail: '无法复制这个图层。请把播放头移到它出现的位置,再试一次。',
+ pasteNoPage: '播放头下没有可以粘贴进去的页面。请把播放头移到一个页面上。',
+ pasteChanged: '粘贴之后页面又被改过,所以无法从中移除粘贴的图层。',
notNow: '此刻不在画面上',
restackFailed: '这个图层没能调整顺序。画面可能刚变过,再试一次。',
},
diff --git a/packages/openfilm/studio/ui/src/lib/html-source.ts b/packages/openfilm/studio/ui/src/lib/html-source.ts
new file mode 100644
index 0000000..452d379
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/html-source.ts
@@ -0,0 +1,202 @@
+/**
+ * A page's HTML read as its file has it: each element with where it starts and ends in the text, its attributes and
+ * its words, so Studio can write into a page (lib/layer-paste) and leave every other character as it was. The
+ * browser's own reading (DOMParser) says which element is which; this says where it is.
+ *
+ * It reads what people and agents write: elements, attributes quoted or not, comments, raw text (`<script>`,
+ * `<style>`, `<textarea>`, `<title>`), elements that hold nothing (`<br>`, `<img>` …, or `/>` in SVG), the end tags a
+ * page may leave out (`</p>` before a block, `</li>`, `</td>` …) and the `<tbody>` rows written in a table are read in.
+ * What it cannot tell apart is caught by comparing its tree with the browser's (sameShape).
+ *
+ * Pure: no DOM, so `node --test` runs it.
+ */
+
+export interface SourceAttr {
+ name: string;
+ /** Null: written without a value (`hidden`). */
+ value: string | null;
+ /** Where the attribute is written, name to value's end. */
+ start: number;
+ end: number;
+}
+
+export interface SourceText { kind: 'text'; start: number; end: number }
+
+export interface SourceElement {
+ kind: 'element';
+ /** Lower case. */
+ tag: string;
+ /** Its `<`. */
+ start: number;
+ /** Not in the file: a `<tbody>` the browser reads around rows written without one. */
+ implied?: true;
+ /** Just after its start tag's name: where an attribute can be added. */
+ nameEnd: number;
+ /** Just after its start tag's `>`. */
+ openEnd: number;
+ /** Its end tag's `<` (openEnd when it has none). */
+ closeStart: number;
+ /** Just after its end tag (or start tag when it has none). */
+ end: number;
+ attrs: SourceAttr[];
+ children: (SourceElement | SourceText)[];
+}
+
+const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
+/* not `<noscript>`: a page read without its scripts (DOMParser, a render) reads what is in it as elements. A
+ `<template>`'s are not its elements either (they are its content): held as text, as the browser has none */
+const RAW = new Set(['script', 'style', 'textarea', 'title', 'xmp', 'template']);
+/** Where `/>` ends an element: inside SVG and MathML. In HTML it is ignored (`<div/>` is an open `<div>`). */
+const FOREIGN = new Set(['svg', 'math']);
+/** Elements a `<p>` left open ends before. */
+const ENDS_P = new Set([
+ 'address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form',
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'menu', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul',
+]);
+/** An element ended by the start of another of these, when it is the one open. */
+const ENDS_SELF: Record<string, readonly string[]> = {
+ li: ['li'], dt: ['dt', 'dd'], dd: ['dt', 'dd'], option: ['option', 'optgroup'], tr: ['tr'], td: ['td', 'th', 'tr'], th: ['td', 'th', 'tr'],
+};
+
+/** The page's elements as its file has them, in a root that holds the top ones. */
+export function readSource(text: string): SourceElement {
+ const root: SourceElement = { kind: 'element', tag: '#root', start: 0, nameEnd: 0, openEnd: 0, closeStart: text.length, end: text.length, attrs: [], children: [] };
+ const open: SourceElement[] = [root];
+ const top = () => open[open.length - 1]!;
+ const close = (el: SourceElement, at: number, end: number) => { el.closeStart = at; el.end = end; };
+ let i = 0;
+ let textFrom = 0;
+ const flushText = (to: number) => { if (to > textFrom) top().children.push({ kind: 'text', start: textFrom, end: to }); };
+ while (i < text.length) {
+ const lt = text.indexOf('<', i);
+ if (lt < 0) break;
+ if (text.startsWith('<!--', lt)) {
+ flushText(lt);
+ const endAt = text.indexOf('-->', lt + 4);
+ i = textFrom = endAt < 0 ? text.length : endAt + 3;
+ continue;
+ }
+ if (text[lt + 1] === '!' || text[lt + 1] === '?') {
+ flushText(lt);
+ const gt = text.indexOf('>', lt);
+ i = textFrom = gt < 0 ? text.length : gt + 1;
+ continue;
+ }
+ const endTag = /^<\/([A-Za-z][\w:-]*)[^>]*>/.exec(text.slice(lt, lt + 200));
+ if (endTag) {
+ flushText(lt);
+ const tag = endTag[1]!.toLowerCase();
+ const k = open.map((e) => e.tag).lastIndexOf(tag);
+ if (k > 0) {
+ /* the ones opened inside it and left open end here too */
+ for (let j = open.length - 1; j > k; j--) close(open[j]!, lt, lt);
+ close(open[k]!, lt, lt + endTag[0].length);
+ open.length = k;
+ }
+ i = textFrom = lt + endTag[0].length;
+ continue;
+ }
+ const name = /^<([A-Za-z][\w:-]*)/.exec(text.slice(lt, lt + 100));
+ if (!name) { i = lt + 1; continue; }
+ flushText(lt);
+ const tag = name[1]!.toLowerCase();
+ const nameEnd = lt + name[0].length;
+ const { attrs, end: openEnd, selfClosed } = readAttrs(text, nameEnd);
+ /* end tags a page may leave out */
+ if (ENDS_P.has(tag) && top().tag === 'p') { close(top(), lt, lt); open.pop(); }
+ const ends = ENDS_SELF[top().tag];
+ if (ends?.includes(tag)) { close(top(), lt, lt); open.pop(); }
+ /* rows written straight in a table are read inside a <tbody> */
+ if (tag === 'tr' && top().tag === 'table') {
+ const body: SourceElement = { kind: 'element', tag: 'tbody', implied: true, start: lt, nameEnd: lt, openEnd: lt, closeStart: lt, end: lt, attrs: [], children: [] };
+ top().children.push(body);
+ open.push(body);
+ }
+ const el: SourceElement = { kind: 'element', tag, start: lt, nameEnd, openEnd, closeStart: openEnd, end: openEnd, attrs, children: [] };
+ top().children.push(el);
+ i = textFrom = openEnd;
+ const foreign = FOREIGN.has(tag) || open.some((o) => FOREIGN.has(o.tag));
+ if (VOID.has(tag) || (selfClosed && foreign)) continue;
+ if (RAW.has(tag)) {
+ const m = new RegExp(`</${tag}[^>]*>`, 'i').exec(text.slice(openEnd));
+ const at = m ? openEnd + m.index : text.length;
+ if (at > openEnd) el.children.push({ kind: 'text', start: openEnd, end: at });
+ close(el, at, m ? at + m[0].length : text.length);
+ i = textFrom = el.end;
+ continue;
+ }
+ open.push(el);
+ }
+ flushText(text.length);
+ for (let j = open.length - 1; j > 0; j--) close(open[j]!, text.length, text.length);
+ return root;
+}
+
+function readAttrs(text: string, from: number): { attrs: SourceAttr[]; end: number; selfClosed: boolean } {
+ const attrs: SourceAttr[] = [];
+ let i = from;
+ for (;;) {
+ while (i < text.length && /\s/.test(text[i]!)) i++;
+ if (i >= text.length) return { attrs, end: i, selfClosed: false };
+ if (text[i] === '>') return { attrs, end: i + 1, selfClosed: false };
+ if (text.startsWith('/>', i)) return { attrs, end: i + 2, selfClosed: true };
+ if (text[i] === '/') { i++; continue; }
+ const start = i;
+ while (i < text.length && !/[\s=>]/.test(text[i]!) && !text.startsWith('/>', i)) i++;
+ const name = text.slice(start, i).toLowerCase();
+ while (i < text.length && /\s/.test(text[i]!)) i++;
+ if (text[i] !== '=') { attrs.push({ name, value: null, start, end: i }); continue; }
+ i++;
+ while (i < text.length && /\s/.test(text[i]!)) i++;
+ const q = text[i];
+ let value: string;
+ if (q === '"' || q === "'") {
+ const close = text.indexOf(q, i + 1);
+ const stop = close < 0 ? text.length : close;
+ value = text.slice(i + 1, stop);
+ i = Math.min(text.length, stop + 1);
+ } else {
+ const s = i;
+ while (i < text.length && !/[\s>]/.test(text[i]!)) i++;
+ value = text.slice(s, i);
+ }
+ attrs.push({ name, value: decodeAttr(value), start, end: i });
+ }
+}
+
+const decodeAttr = (v: string) => v.replace(/&(quot|amp|lt|gt|#39|apos);/g, (_, e: string) => ({ quot: '"', amp: '&', lt: '<', gt: '>', '#39': "'", apos: "'" })[e] ?? _);
+
+export const elementsOf = (el: SourceElement): SourceElement[] => el.children.filter((c): c is SourceElement => c.kind === 'element');
+
+/** The page's `<body>` as its file has it (a page without the tag: what is not its head). */
+export function sourceBody(root: SourceElement): SourceElement {
+ const find = (el: SourceElement): SourceElement | null => {
+ for (const c of elementsOf(el)) {
+ if (c.tag === 'body') return c;
+ if (c.tag === 'html') { const b = find(c); if (b) return b; }
+ }
+ return null;
+ };
+ const body = find(root);
+ if (body) return body;
+ const html = elementsOf(root).find((c) => c.tag === 'html') ?? root;
+ return { ...html, tag: 'body', children: html.children.filter((c) => c.kind !== 'element' || !['head', 'html'].includes(c.tag)) };
+}
+
+/** The element at `path` (element after element, from `from`), when every step is there with the tag `tags` says. */
+export function elementAt(from: SourceElement, path: readonly number[], tags: readonly string[]): SourceElement | null {
+ let at: SourceElement | undefined = from;
+ for (const [k, i] of path.entries()) {
+ at = at ? elementsOf(at)[i] : undefined;
+ if (!at || (tags[k] && at.tag !== tags[k]!.toLowerCase())) return null;
+ }
+ return at ?? null;
+}
+
+/** Whether `el` holds what the browser's reading of it holds, element for element (`shape`: tag and children). */
+export interface Shape { tag: string; children: Shape[] }
+export function sameShape(el: SourceElement, shape: Shape): boolean {
+ if (el.tag !== shape.tag.toLowerCase()) return false;
+ const kids = elementsOf(el);
+ return kids.length === shape.children.length && kids.every((k, i) => sameShape(k, shape.children[i]!));
+}
diff --git a/packages/openfilm/studio/ui/src/lib/layer-clipboard.test.ts b/packages/openfilm/studio/ui/src/lib/layer-clipboard.test.ts
new file mode 100644
index 0000000..3afaf9b
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/layer-clipboard.test.ts
@@ -0,0 +1,48 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { pasteGoals, pasteOffset, whyNowhere, type LayerClipboard, type PageClip } from './layer-clipboard.ts';
+import type { PasteLayer } from './layer-paste.ts';
+
+const L = (at: string): PasteLayer => ({ at, tag: 'h1', id: null, classes: [], text: '', place: null, idRules: [], tweaks: [] });
+const board = (over: Partial<LayerClipboard> = {}): LayerClipboard => ({ project: 'p1', atMs: 0, clips: [{ from: 'a', src: 'title.html', layers: [L('#t')] }], ...over });
+const a: PageClip = { id: 'a', src: 'title.html' };
+const b: PageClip = { id: 'b', src: 'title.html' };
+const c: PageClip = { id: 'c', src: 'scene.html' };
+const kinds = (goals: ReturnType<typeof pasteGoals>) => goals.map((g) => `${g.kind}:${g.clip}`);
+
+test('a paste goes into the page in hand: its own page as itself, another as it looks', () => {
+ assert.deepEqual(kinds(pasteGoals(board(), 'p1', b, [c], [a, b, c])), ['own:b']);
+ assert.deepEqual(kinds(pasteGoals(board(), 'p1', c, [a], [a, b, c])), ['other:c']);
+ const forked = board({ clips: [{ from: 'a', src: 'title 2.html', layers: [L('#t')] }] });
+ assert.deepEqual(kinds(pasteGoals(forked, 'p1', { id: 'a', src: 'title 2.html' }, [], [a])), ['own:a'], 'its clip given a page of its own: still its own page');
+});
+
+test('nothing in hand: its own page under the playhead, else the top page there, else back into its own page', () => {
+ assert.deepEqual(kinds(pasteGoals(board(), 'p1', null, [c, b, a], [a, b, c])), ['own:a'], 'the clip copied from first');
+ assert.deepEqual(kinds(pasteGoals(board(), 'p1', null, [c, b], [a, b, c])), ['own:b'], 'another clip of its page');
+ assert.deepEqual(kinds(pasteGoals(board(), 'p1', null, [c], [a, b, c])), ['other:c']);
+ assert.deepEqual(kinds(pasteGoals(board(), 'p1', null, [], [a, b, c])), ['own:a'], 'no page under the playhead: its own, at its own place');
+ assert.deepEqual(kinds(pasteGoals(board(), 'p1', null, [], [{ ...a, locked: true }])), [], 'a locked track: nowhere');
+});
+
+test('copied from several clips: each back into its own page; from another project: into the page there', () => {
+ const two = board({ clips: [{ from: 'a', src: 'title.html', layers: [L('#t')] }, { from: 'c', src: 'scene.html', layers: [L('#s')] }] });
+ assert.deepEqual(kinds(pasteGoals(two, 'p1', null, [], [a, c])), ['own:a', 'own:c']);
+ const away = board({ project: 'p0' });
+ assert.deepEqual(kinds(pasteGoals(away, 'p1', null, [c], [c])), ['other:c']);
+ assert.deepEqual(pasteGoals(away, 'p1', null, [], [c]), [], 'no page under the playhead there');
+});
+
+test('each paste at the same spot goes further; into its own page it starts off the copied one', () => {
+ const own = pasteGoals(board(), 'p1', a, [], [a]);
+ const first = pasteOffset(board(), own);
+ assert.equal(first.n, 1);
+ assert.equal(pasteOffset(board({ pasted: first }), own).n, 2);
+ assert.equal(pasteOffset(board({ pasted: first }), pasteGoals(board(), 'p1', c, [], [a, c])).n, 0, 'another spot, another page: where it was');
+});
+
+test('nowhere to paste: said as a locked track only when its own page is on one', () => {
+ assert.equal(whyNowhere(board(), 'p1', [{ ...a, locked: true }]), 'locked');
+ assert.equal(whyNowhere(board(), 'p1', [c]), 'no-page', 'the clip copied from removed, no page under the playhead');
+ assert.equal(whyNowhere(board({ project: 'p0' }), 'p1', [{ ...a, locked: true }]), 'no-page');
+});
diff --git a/packages/openfilm/studio/ui/src/lib/layer-clipboard.ts b/packages/openfilm/studio/ui/src/lib/layer-clipboard.ts
new file mode 100644
index 0000000..0c27542
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/layer-clipboard.ts
@@ -0,0 +1,110 @@
+/**
+ * Copy and paste of layers inside pages (⌘C / ⌘V and the menus, on the picture and in the Layers panel), as a design
+ * tool does it: a pasted layer is a new element written into a page (lib/layer-paste), independent of the one copied.
+ *
+ * Where it goes (pasteGoals): into the page in hand (the layer or clip selected), else into a page of the copied
+ * layer's under the playhead, else into the top page there; with no page under the playhead, into the page it was
+ * copied from, at its own place. Its own page gets the copied element itself, right after it; another page gets it as
+ * it looks (lib/layer-paste pastedElsewhere). Layers copied from several clips each go back into their own page. Each
+ * paste at the same spot goes a little lower and to the right of the one before.
+ *
+ * The clipboard is the timeline's or this one's, whichever was copied last; it is kept in the browser's storage, so
+ * another window and another project of the same Studio paste it too (lib: no React, no DOM, so `node --test` runs it).
+ */
+import type { PasteLayer } from './layer-paste.ts';
+
+/** The layers copied from one page clip. */
+export interface CopiedLayers {
+ /** The clip's id. */
+ from: string;
+ /** Its page (its src): a paste into a clip of it is a paste into its own page. */
+ src: string;
+ layers: PasteLayer[];
+}
+
+export interface LayerClipboard {
+ /** The project copied from: another one's files are brought in first. */
+ project: string;
+ /** The film's time copied at. */
+ atMs: number;
+ clips: CopiedLayers[];
+ /** The pastes made at one spot so far (each one further off), the spot, and the last one's copies (their ids). */
+ pasted?: { spot: string; n: number; ats?: string[] };
+}
+
+/** How far each paste at the same spot goes, right and down (px of the page). */
+export const PASTE_OFFSET = 24;
+
+/** A page clip as a paste sees it. */
+export interface PageClip { id: string; src: string; locked?: boolean }
+
+/** Where copied layers are written: into clip `clip`'s page, as themselves (`own`) or as they look (`other`). */
+export interface PasteGoal { kind: 'own' | 'other'; clip: string; layers: PasteLayer[] }
+
+/**
+ * Where a paste of `board` goes (see the top), in project `project`: `held` the page clip in hand, `under` the page
+ * clips under the playhead (the top one first), `clips` every page clip of the film. Empty when there is nowhere.
+ */
+export function pasteGoals(
+ board: LayerClipboard, project: string, held: PageClip | null, under: readonly PageClip[], clips: readonly PageClip[],
+): PasteGoal[] {
+ const open = (c: PageClip | null | undefined): c is PageClip => Boolean(c && !c.locked);
+ const all = board.clips.flatMap((c) => c.layers);
+ if (board.project !== project) {
+ const into = open(held) ? held : under.find(open);
+ return into ? [{ kind: 'other', clip: into.id, layers: all }] : [];
+ }
+ if (board.clips.length > 1) {
+ return board.clips.flatMap((c) => {
+ const own = clips.find((x) => x.id === c.from);
+ return open(own) ? [{ kind: 'own' as const, clip: own.id, layers: c.layers }] : [];
+ });
+ }
+ const c = board.clips[0];
+ if (!c) return [];
+ const mine = (x: PageClip) => x.id === c.from || x.src === c.src;
+ if (open(held)) return [{ kind: mine(held) ? 'own' : 'other', clip: held.id, layers: c.layers }];
+ const here = under.filter(open);
+ const ownHere = here.find((x) => x.id === c.from) ?? here.find(mine);
+ if (ownHere) return [{ kind: 'own', clip: ownHere.id, layers: c.layers }];
+ if (here[0]) return [{ kind: 'other', clip: here[0].id, layers: c.layers }];
+ const own = clips.find((x) => x.id === c.from);
+ return open(own) ? [{ kind: 'own', clip: own.id, layers: c.layers }] : [];
+}
+
+/** Why a paste of `board` goes nowhere (pasteGoals said so): its own page is on a locked track, or there is no page. */
+export function whyNowhere(board: LayerClipboard, project: string, clips: readonly PageClip[]): 'locked' | 'no-page' {
+ return board.project === project && board.clips.some((c) => clips.find((x) => x.id === c.from)?.locked) ? 'locked' : 'no-page';
+}
+
+/** How far a paste into these goals goes: further each time at the same spot; into its own page, off from the start. */
+export function pasteOffset(board: LayerClipboard, goals: readonly PasteGoal[]): { spot: string; n: number } {
+ const spot = goals.map((g) => `${g.kind}:${g.clip}:${g.layers.map((l) => l.at).join('|')}`).join(';');
+ const first = goals.some((g) => g.kind === 'own') ? 1 : 0;
+ return { spot, n: board.pasted?.spot === spot ? board.pasted.n + 1 : first };
+}
+
+/* ── kept in the browser, for every window and project of this Studio ── */
+
+const KEY = 'openfilm.layer-clipboard';
+
+export function readLayerClipboard(): LayerClipboard | null {
+ try {
+ const raw = globalThis.localStorage?.getItem(KEY);
+ const v = raw ? JSON.parse(raw) as LayerClipboard : null;
+ return v && typeof v.project === 'string' && Array.isArray(v.clips) && v.clips.length && v.clips.every((c) => Array.isArray(c.layers)) ? v : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Kept, or (null) emptied: the timeline's clipboard was copied to since. */
+export function writeLayerClipboard(board: LayerClipboard | null): void {
+ try {
+ if (board) globalThis.localStorage?.setItem(KEY, JSON.stringify(board));
+ else globalThis.localStorage?.removeItem(KEY);
+ } catch { /* storage refused (a private window): the clipboard lives in this window only */ }
+}
+
+/** Whether a storage event is this clipboard's (another window copied or emptied it). */
+export const isLayerClipboardKey = (key: string | null) => key === KEY || key === null;
diff --git a/packages/openfilm/studio/ui/src/lib/layer-paste-target.ts b/packages/openfilm/studio/ui/src/lib/layer-paste-target.ts
new file mode 100644
index 0000000..c4420a2
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/layer-paste-target.ts
@@ -0,0 +1,52 @@
+/**
+ * Where copied layers are in their page's file, as the browser reads the file (no script run): the elements the stage
+ * named, by their path from `<body>` and their shape (lib/layer-paste finds them there in the text). A layer is known
+ * by its tag, id and classes, then its words: an element the page's code put before it moves it in the page as drawn,
+ * so where the selector points in the file is the last thing to go by. Null when the file has no such element (the
+ * page's code makes it as it runs).
+ */
+import type { PasteLayer, PasteTarget } from './layer-paste';
+import type { Shape } from './html-source';
+
+const words = (el: Element) => (el.textContent ?? '').replace(/\s+/g, ' ').trim().slice(0, 200);
+const shapeOf = (el: Element): Shape => ({ tag: el.localName, children: [...el.children].map(shapeOf) });
+
+/** `el`'s path from `<body>`, its tags, its shape. */
+function targetOf(doc: Document, el: Element): PasteTarget {
+ const path: number[] = [];
+ const tags: string[] = [];
+ for (let n: Element = el; n !== doc.body; n = n.parentElement!) {
+ path.unshift([...n.parentElement!.children].indexOf(n));
+ tags.unshift(n.localName);
+ }
+ return { path, tags, shape: shapeOf(el) };
+}
+
+export function pasteTargets(text: string, layers: readonly PasteLayer[]): PasteTarget[] | null {
+ const doc = new DOMParser().parseFromString(text, 'text/html');
+ const out: PasteTarget[] = [];
+ for (const layer of layers) {
+ const alike = [...doc.body.querySelectorAll(layer.tag)].filter((x) => (
+ (x.id || null) === layer.id && layer.classes.every((c) => x.classList.contains(c))
+ ));
+ let pointed: Element[] = [];
+ try { pointed = layer.at ? [...doc.querySelectorAll(layer.at)] : []; } catch { /* a selector this reading cannot take */ }
+ const same = alike.filter((x) => words(x) === layer.text);
+ /* its words first (several alike: the one the selector points at, else the first); none with its words (the clip
+ changed them, or its code writes them): the one the selector points at, when it points at one alike */
+ const pointedAlike = alike.filter((x) => pointed.includes(x));
+ const el = same.length === 1 ? same[0]
+ : same.length > 1 ? same.find((x) => pointed.includes(x)) ?? same[0]
+ : pointedAlike.length === 1 ? pointedAlike[0] : null;
+ if (!el) return null;
+ out.push(targetOf(doc, el));
+ }
+ return out;
+}
+
+/** Where the element of id `id` is in the page's file (a copy pasted before), as pasteTargets says it. */
+export function targetById(text: string, id: string): PasteTarget | null {
+ const doc = new DOMParser().parseFromString(text, 'text/html');
+ const el = doc.getElementById(id);
+ return el && doc.body.contains(el) ? targetOf(doc, el) : null;
+}
diff --git a/packages/openfilm/studio/ui/src/lib/layer-paste.test.ts b/packages/openfilm/studio/ui/src/lib/layer-paste.test.ts
new file mode 100644
index 0000000..91a55b8
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/layer-paste.test.ts
@@ -0,0 +1,202 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { elementAt, elementsOf, readSource, sourceBody } from './html-source.ts';
+import { copyId, cssEscape, idsIn, pastedElsewhere, pastedPage, relativeTo, weighted, withoutPaste, withPaste, type PasteItem, type PasteLayer, type PasteTarget } from './layer-paste.ts';
+
+const PAGE = `<!doctype html>
+<html><head><style>#card{background:#c33} #title{color:#ff0}</style></head>
+<body>
+ <!-- a card <div> -->
+ <div id="card" class="card">
+ <h1 id="title">Hello</h1>
+ <p class=sub>world<br>again</p>
+ <svg><linearGradient id="g"/><rect fill="url(#g)"/><use href="#g"/><use xlink:href="#g"/></svg>
+ </div>
+ <p>Open paragraph
+ <div id="dot"></div>
+ <script>if (a < b && "</div>") go();</script>
+</body></html>`;
+
+test('a page\'s file read as it is written: comments, raw text, end tags left out, attributes quoted or not', () => {
+ const body = sourceBody(readSource(PAGE));
+ assert.deepEqual(elementsOf(body).map((e) => e.tag), ['div', 'p', 'div', 'script']);
+ const card = elementAt(body, [0], ['div'])!;
+ assert.equal(PAGE.slice(card.start, card.end).split('\n')[0], '<div id="card" class="card">');
+ assert.ok(PAGE.slice(card.start, card.end).endsWith('</div>'));
+ assert.deepEqual(elementsOf(card).map((e) => e.tag), ['h1', 'p', 'svg']);
+ assert.equal(elementAt(body, [0, 1], ['div', 'p'])!.attrs[0]!.value, 'sub');
+ assert.equal(elementAt(body, [1], ['p'])!.end, elementAt(body, [2], ['div'])!.start, 'a <p> left open ends at the next block');
+ assert.equal(elementAt(body, [0, 0], ['div', 'div']), null, 'a step of another tag: not it');
+});
+
+test('as the browser reads it: rows in a <tbody>, <div/> left open, <noscript> and <template> as it has them', () => {
+ const body = sourceBody(readSource('<body><table id="t"><tr><td><span id="cell">X</span></td></tr></table><div id="x"/></div><noscript><p>n</p></noscript><template><p>t</p></template><h1 class="t">Hi</h1></body>'));
+ const tags = (e: ReturnType<typeof sourceBody>): unknown => [e.tag, elementsOf(e).map(tags)];
+ assert.deepEqual(tags(body), ['body', [
+ ['table', [['tbody', [['tr', [['td', [['span', []]]]]]]]]],
+ ['div', []],
+ ['noscript', [['p', []]]],
+ ['template', []],
+ ['h1', []],
+ ]]);
+ assert.ok(elementAt(body, [0, 0], ['table', 'tbody'])!.implied, 'the <tbody> is not in the file');
+});
+
+const layer = (over: Partial<PasteLayer> = {}): PasteLayer => ({
+ at: '#card', tag: 'div', id: 'card', classes: ['card'], text: 'Hello worldagain',
+ place: { position: 'static', left: 200, top: 100, width: 900, height: 500 },
+ tweaks: [], ...over,
+});
+const CARD: PasteTarget = {
+ path: [0], tags: ['div'],
+ shape: { tag: 'div', children: [{ tag: 'h1', children: [] }, { tag: 'p', children: [{ tag: 'br', children: [] }] }, { tag: 'svg', children: [{ tag: 'linearGradient', children: [] }, { tag: 'rect', children: [] }, { tag: 'use', children: [] }, { tag: 'use', children: [] }] }] },
+};
+
+test('a copy written right after the layer: new ids and what names them, held in place and moved', () => {
+ const out = pastedPage(PAGE, [{ layer: layer({ tweaks: [{ path: [0], tag: 'h1', text: 'Hi & bye', style: { fontSize: 48 } }, { path: [], tag: 'div', t: [10, 0] }] }), target: CARD }], 24)!;
+ assert.deepEqual(out.ats, ['#card-copy']);
+ const at = out.text.indexOf('<div id="card-copy"');
+ const added = out.text.slice(at, out.text.indexOf('</div>', at) + 6);
+ assert.ok(added.startsWith('<div id="card-copy" class="card" style="position: absolute; left: 200px; top: 100px; width: 900px; height: 500px; margin: 0; box-sizing: border-box; translate: 34px 24px">'), added);
+ assert.ok(added.includes('<h1 id="title-copy" style="font-size: 48px">Hi &amp; bye</h1>'), added);
+ assert.ok(added.includes('<linearGradient id="g-copy"/><rect fill="url(#g-copy)"/><use href="#g-copy"/><use xlink:href="#g-copy"/>'), added);
+ assert.ok(added.includes('<p class=sub>world<br>again</p>'), 'what was not changed is written as it was');
+ assert.equal(withoutPaste(out.text, out.inserted)?.text, PAGE, 'and taken out again, the page as it was');
+});
+
+test('several layers of one page: each found before any is written, so a selector counting them finds the right one', () => {
+ const page = '<body>\n<div id="card">\n <h1 class="line">One</h1>\n <h1 class="line">Two</h1>\n</div>\n</body>';
+ const line = (text: string, i: number): PasteItem => ({
+ layer: layer({ at: `#card > h1.line:nth-of-type(${i + 1})`, tag: 'h1', id: null, classes: ['line'], text, place: { position: 'absolute', left: 0, top: 0, width: 10, height: 10 } }),
+ target: { path: [0, i], tags: ['div', 'h1'], shape: { tag: 'h1', children: [] } },
+ });
+ const out = pastedPage(page, [line('One', 0), line('Two', 1)], 24)!;
+ assert.deepEqual(out.ats, ['#line-copy', '#line-copy-2']);
+ assert.equal(out.text, '<body>\n<div id="card">\n <h1 class="line">One</h1>\n <h1 id="line-copy" class="line" style="translate: 24px 24px">One</h1>'
+ + '\n <h1 class="line">Two</h1>\n <h1 id="line-copy-2" class="line" style="translate: 24px 24px">Two</h1>\n</div>\n</body>');
+ const card: PasteItem = { layer: layer(), target: { path: [0], tags: ['div'], shape: { tag: 'div', children: [{ tag: 'h1', children: [] }, { tag: 'h1', children: [] }] } } };
+ assert.deepEqual(pastedPage(page, [card, line('One', 0)], 24)!.ats, ['#card-copy', ''], 'one inside another copied: with it');
+ const over = pastedPage(out.text, [{ ...line('One', 0), over: { path: [0, 1], tags: ['div', 'h1'], shape: { tag: 'h1', children: [] } } }], 48)!;
+ assert.ok(over.text.includes('<h1 id="line-copy" class="line" style="translate: 24px 24px">One</h1>\n <h1 id="line-copy-3"'), 'pasted again: over the copy before');
+ const last = pastedPage(page, [{ ...line('One', 0), place: { after: 1, siblings: ['h1', 'h1'] } }], 0)!;
+ assert.ok(last.text.includes('<h1 class="line">Two</h1>\n <h1 id="line-copy" class="line">One</h1>\n</div>'), 'at its place when asked');
+ const first = pastedPage(page, [{ ...line('Two', 1), place: { after: -1, siblings: ['h1', 'h1'] } }], 0)!;
+ assert.ok(first.text.startsWith('<body>\n<div id="card">\n <h1 id="line-copy" class="line">Two</h1>'), first.text);
+ const other = pastedPage(page, [{ ...line('One', 0), place: { after: 1, siblings: ['p', 'h1', 'h1'] } }], 0)!;
+ assert.ok(other.text.includes('<h1 class="line">One</h1>\n <h1 id="line-copy"'), 'the file has other elements beside it than the page as drawn: right after it');
+});
+
+test('a copy runs no code: its scripts and handlers go', () => {
+ const page = '<head></head><body><div id="w" onclick="go()"><canvas id="c"></canvas><script>const ctx = 1;</script></div></body>';
+ const out = pastedPage(page, [{
+ layer: layer({ at: '#w', id: 'w', classes: [], place: { position: 'absolute', left: 0, top: 0, width: 1, height: 1 } }),
+ target: { path: [0], tags: ['div'], shape: { tag: 'div', children: [{ tag: 'canvas', children: [] }, { tag: 'script', children: [] }] } },
+ }], 0)!;
+ assert.equal(out.text, '<head></head><body><div id="w" onclick="go()"><canvas id="c"></canvas><script>const ctx = 1;</script></div>\n<div id="w-copy"><canvas id="c-copy"></canvas></div></body>');
+});
+
+test('words written as the film writes them; a file\'s own line breaks; ids keep their numbers', () => {
+ const page = '<body>\r\n<h1 id="h">Quiet<br><em>you</em> now</h1>\r\n</body>';
+ const out = pastedPage(page, [{
+ layer: layer({ at: '#h', tag: 'h1', id: 'h', classes: [], place: { position: 'absolute', left: 0, top: 0, width: 1, height: 1 }, tweaks: [{ path: [], tag: 'h1', text: 'Hello' }] }),
+ target: { path: [0], tags: ['h1'], shape: { tag: 'h1', children: [{ tag: 'br', children: [] }, { tag: 'em', children: [] }] } },
+ }], 0)!;
+ assert.equal(out.text, '<body>\r\n<h1 id="h">Quiet<br><em>you</em> now</h1>\r\n<h1 id="h-copy">Hello<br><em>you</em></h1>\r\n</body>', 'its first run of words, the others taken away');
+ assert.equal(copyId('step-1', new Set(['step-2'])), 'step-1-copy');
+ assert.equal(copyId('step-1-copy', new Set(['step-1-copy'])), 'step-1-copy-2', 'a copy\'s copy named from the first');
+});
+
+test('a layer the file does not hold as the browser reads it (made by the page\'s code): no copy', () => {
+ assert.equal(pastedPage(PAGE, [{ layer: layer(), target: { ...CARD, path: [5] } }], 24), null);
+ assert.equal(pastedPage(PAGE, [{ layer: layer(), target: { ...CARD, shape: { tag: 'div', children: [] } } }], 24), null);
+});
+
+test('an element placed by the page already keeps its place and its own move; one without an id gets one', () => {
+ const page = '<body><span class="tag" style="position:absolute;left:5px;translate:10px 0px">New</span></body>';
+ const out = pastedPage(page, [{
+ layer: layer({ at: 'body > span', tag: 'span', id: null, classes: ['tag'], place: { position: 'absolute', left: 5, top: 0, width: 30, height: 10 } }),
+ target: { path: [0], tags: ['span'], shape: { tag: 'span', children: [] } },
+ }], 24)!;
+ assert.equal(out.ats[0], '#tag-copy');
+ assert.equal(out.text, '<body><span class="tag" style="position:absolute;left:5px;translate:10px 0px">New</span>\n<span id="tag-copy" class="tag" style="position:absolute;left:5px;translate:10px 0px; translate: 34px 24px">New</span></body>');
+});
+
+test('a path named from a page: up and down from its folder', () => {
+ assert.equal(relativeTo('scene.html', 'assets/a.png'), 'assets/a.png');
+ assert.equal(relativeTo('scenes/two/scene.html', 'assets/a.png'), '../../assets/a.png');
+ assert.equal(relativeTo('scenes/scene.html', 'scenes/img/a.png'), 'img/a.png');
+});
+
+test('into another page: the layer as it looks, last in its body, with new ids, its move kept, what it loads named from there', () => {
+ const page = '<html><head></head><body>\n<h2 id="g-copy">Two</h2>\n</body></html>';
+ const base = 'http://127.0.0.1:1/p1/';
+ const shot = {
+ html: `<div id="card" style="position: absolute; left: 10px; top: 20px; translate: 100px 0px; background-image: url(&quot;${base}assets/a%20b.png&quot;)"><img src="${base}assets/logo.png"><svg><linearGradient id="g"></linearGradient><rect fill="url(&quot;#g&quot;)"></rect></svg><a href="https://openfilm.dev">x</a></div>`,
+ fonts: [`@font-face { font-family: Brand; src: url("${base}fonts/b.woff2"); }`],
+ base,
+ };
+ const out = pastedElsewhere(page, 'scenes/two.html', [layer({ snapshot: shot })], 24, (p) => `pasted/p1/${p}`)!;
+ assert.deepEqual(out.ats, ['#card-copy']);
+ assert.equal(out.text, '<html><head><style>@font-face { font-family: Brand; src: url("../pasted/p1/fonts/b.woff2"); }</style>\n</head><body>\n<h2 id="g-copy">Two</h2>\n'
+ + '<div id="card-copy" style="position: absolute; left: 10px; top: 20px; translate: 100px 0px; background-image: url(&quot;../pasted/p1/assets/a b.png&quot;); translate: 124px 24px">'
+ + '<img src="../pasted/p1/assets/logo.png"><svg><linearGradient id="g-copy-2"></linearGradient><rect fill="url(&quot;#g-copy-2&quot;)"></rect></svg><a href="https://openfilm.dev">x</a></div>\n</body></html>');
+ assert.equal(pastedElsewhere(page, 'two.html', [layer()], 0), null, 'copied before its look was known');
+});
+
+test('an undo of a page written since: what the paste wrote taken out, where it is, once; and put back for a redo', () => {
+ const pieces = ['<b>COPY</b>', '<style>x</style>'];
+ const page = '<style>x</style><a>x</a><b>COPY</b><i>agent</i>';
+ const out = withoutPaste(page, pieces)!;
+ assert.equal(out.text, '<a>x</a><i>agent</i>');
+ assert.equal(withPaste(out.text, pieces, out.at), page);
+ assert.equal(withoutPaste('<b>COPY</b><b>COPY</b>', ['<b>COPY</b>']), null, 'twice: not known which');
+ assert.equal(withoutPaste('<a>x</a>', ['<b>COPY</b>']), null, 'gone');
+});
+
+test('what the page\'s rules give the layer and not its copy, and the copy and not it: rules of the copy, weighed as those, after their stylesheet', () => {
+ const page = '<head><style>#col p:first-child { color: var(--accent) }</style><link rel="stylesheet" href="b.css"></head><body><div id="col"><p>A<b>!</b></p><p>B</p></div></body>';
+ const out = pastedPage(page, [{
+ layer: layer({ at: '#col > p:nth-of-type(1)', tag: 'p', id: null, classes: [], place: { position: 'absolute', left: 0, top: 0, width: 1, height: 1 } }),
+ target: { path: [0, 0], tags: ['div', 'p'], shape: { tag: 'p', children: [{ tag: 'b', children: [] }] } },
+ look: [
+ { path: [], rules: [
+ { sheet: 0, within: [], weight: [1, 1, 1], decls: [['color', 'var(--accent)'], ['animation', '1s both in']] },
+ { sheet: 1, within: ['@media (min-width: 800px)'], weight: [0, 0, 1], decls: [['border-top-color', 'unset']] },
+ ] },
+ { path: [0], rules: [{ sheet: 0, within: [], weight: [0, 1, 0], decls: [['font-weight', '700']] }] },
+ ],
+ }], 0)!;
+ assert.equal(out.text, '<head><style>#col p:first-child { color: var(--accent) }</style>'
+ + '\n<style>:where(#p-copy)#p-copy:not(.openfilm-none):not(openfilm-none) { color: var(--accent); animation: 1s both in; } :where(#b-copy):not(.openfilm-none) { font-weight: 700; }</style>'
+ + '<link rel="stylesheet" href="b.css"><style>@media (min-width: 800px) { :where(#p-copy):not(openfilm-none) { border-top-color: unset; } }</style>\n</head>'
+ + '<body><div id="col"><p>A<b>!</b></p>\n<p id="p-copy">A<b id="b-copy">!</b></p><p>B</p></div></body>', 'as the rules write it: live, and weighed as they are');
+ assert.equal(weighted('a', [2, 0, 3]), ':where(#a)#a#a:not(openfilm-none):not(openfilm-none):not(openfilm-none)');
+});
+
+test('ids are written as CSS writes them: a leading digit, a - and a digit, other signs', () => {
+ assert.deepEqual(['1st', '-2x', '-', 'a.b c', 'déjà', 'ok_-9'].map(cssEscape), ['\\31 st', '-\\32 x', '\\-', 'a\\.b\\ c', 'déjà', 'ok_-9']);
+ assert.equal(weighted('1st-copy', [1, 0, 0]), ':where(#\\31 st-copy)#\\31 st-copy');
+ const page = '<head></head><body><p id="1st">A</p></body>';
+ const out = pastedPage(page, [{
+ layer: layer({ at: '#\\31 st', tag: 'p', id: '1st', classes: [], place: { position: 'absolute', left: 0, top: 0, width: 1, height: 1 } }),
+ target: { path: [0], tags: ['p'], shape: { tag: 'p', children: [] } },
+ look: [{ path: [], rules: [{ sheet: -1, within: [], weight: [1, 0, 1], decls: [['font-weight', '700']] }] }],
+ }], 0)!;
+ assert.equal(out.ats[0], '#\\31 st-copy', 'and the copy named so, to be selected');
+ assert.ok(out.text.startsWith('<head><style>:where(#\\31 st-copy)#\\31 st-copy:not(openfilm-none) { font-weight: 700; }</style>'), out.text);
+});
+
+test('the ids a selector names, read as CSS reads them: escapes ended by a space or not, whole names only', () => {
+ const ids = (sel: string) => idsIn(sel).map((t) => t.id);
+ assert.deepEqual(ids('#\\31 '), ['1']);
+ assert.deepEqual(ids('#\\31'), ['1'], 'its ending space trimmed off');
+ assert.deepEqual(ids('#\\31 st > #-\\32 x:hover'), ['1st', '-2x']);
+ assert.deepEqual(ids('#a\\.b, #a.c'), ['a.b', 'a']);
+ assert.deepEqual(ids('#déjà [href="#a"] #a\\:b'), ['déjà', 'a:b'], 'not in quotes');
+ /* a one-digit id's copy, named so */
+ const digit = pastedPage('<head></head><body><p id="1">B</p></body>', [{
+ layer: layer({ at: '#\\31 ', tag: 'p', id: '1', classes: [], place: { position: 'absolute', left: 0, top: 0, width: 1, height: 1 } }),
+ target: { path: [0], tags: ['p'], shape: { tag: 'p', children: [] } },
+ }], 0)!;
+ assert.deepEqual(digit.ats, ['#\\31 -copy']);
+});
diff --git a/packages/openfilm/studio/ui/src/lib/layer-paste.ts b/packages/openfilm/studio/ui/src/lib/layer-paste.ts
new file mode 100644
index 0000000..ab1acf9
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/layer-paste.ts
@@ -0,0 +1,488 @@
+/**
+ * Copied layers written into a page, as a design tool pastes: each a new element of the page, independent of the one
+ * copied from then on. Every other character of the page stays as it was.
+ *
+ * Into its own page (pastedPage), a copy is the copied element's markup as the file has it (lib/html-source finds it
+ * there), right after it, or at the nearest place beside it where the page's CSS draws nothing beside it otherwise
+ * (studio/server/stage.js `afterCopy`), with:
+ * - new ids (`<id>-copy`), and what in it names them (`url(#…)`, `href="#…"`, `for`, `aria-*`);
+ * - the clip's changes of it and of what is in it written in (styles, moves, words); and what the page's rules give
+ * it and not the copy where it goes (`#a`, a `:first-child`), or the copy and not it (`:not(#a)`, a `p + p`), as
+ * rules of the copy the cascade weighs as those, right after their stylesheet, as they write it;
+ * - no scripts and no `on…` handlers (they would run twice, as the page's own code: a copy is a picture);
+ * - when it was in the page's flow, held where it was laid out (`position: absolute`, its size), so nothing else
+ * moves; and `offset` px lower and to the right.
+ * Into another page (pastedElsewhere), a copy is the layer as it looks now (the stage's snapshot: its look written in
+ * its style, as that page's CSS cannot draw it), last in that page's body, what it loads named from there.
+ *
+ * Pure: no DOM, so `node --test` runs it.
+ */
+import type { FilmOverride } from './film.ts';
+import { elementAt, elementsOf, readSource, sameShape, sourceBody, type Shape, type SourceElement } from './html-source.ts';
+
+/** A layer as the stage tells it at a copy (studio/server/stage.js `layerSource`). */
+export interface PasteLayer {
+ /** A selector naming it alone in its page as drawn; null when none does. */
+ at: string | null;
+ tag: string;
+ id: string | null;
+ classes: string[];
+ /** Its words, spaces collapsed (at most 200 characters): to know it in the page's file. */
+ text: string;
+ /** Where it is laid out: its `position`, and its box in what places it (px); null inside an SVG (placed by it). */
+ place: { position: string; left: number; top: number; width: number; height: number } | null;
+ /** The clip's changes of it and of what is in it, in order: where in it (element after element, from it), its tag. */
+ tweaks: Array<{ path: number[]; tag: string } & Omit<FilmOverride, 'at' | 'n' | 'lock'>>;
+ /** It as it looks now, for another page: markup holding its look, its fonts, and its project's address (`base`). */
+ snapshot?: { html: string; fonts: string[]; base: string };
+}
+
+/** A rule written for a copy, weighed as the page's rule it answers: its declarations, as written. */
+export interface CopyRule {
+ sheet: number;
+ within: string[];
+ /** The pseudo-element the page's rule is of (`::before` …), '' the element's own. */
+ pseudo?: string;
+ weight: [number, number, number];
+ decls: Array<[string, string]>;
+}
+
+/** Where a layer is in the page's file, as the browser reads the file: its path from `<body>`, and its shape. */
+export interface PasteTarget {
+ path: number[];
+ tags: string[];
+ shape: Shape;
+}
+
+/**
+ * One layer to write: where it is; `place`, where among the elements beside it its copy goes (studio/server/stage.js
+ * `afterCopy`: the index of the one it goes after, -1 first, and their tags, as the page draws them: taken when the
+ * file has the same ones), else right after it; `over`, the copy pasted before at this spot (each paste goes over the
+ * one before).
+ */
+export interface PasteItem {
+ layer: PasteLayer;
+ target: PasteTarget;
+ place?: { after: number; siblings: string[] };
+ over?: PasteTarget;
+ /**
+ * What the page's rules give the layer and not its copy where it goes, and the copy and not it (`afterCopy`), element
+ * by element: rules for the copy, each with the weight, at-rules and stylesheet of the page's rule it answers, so the
+ * cascade weighs it as that one.
+ */
+ look?: Array<{ path: number[]; rules: CopyRule[] }>;
+}
+
+export interface PastedPage {
+ text: string;
+ /** Each copy, as an override names it (in the order asked; '' for one copied inside another). */
+ ats: string[];
+ /** What was written in, as it was written: taken out again by an undo of a page changed since (withoutPaste). */
+ inserted: string[];
+}
+
+const UNITLESS = /opacity|z-index|font-weight|line-height|flex/;
+const kebab = (k: string) => (k.startsWith('--') ? k : k.replace(/[A-Z]/g, (ch) => `-${ch.toLowerCase()}`));
+const escAttr = (v: string) => v.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
+const escText = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+const NAMES_IDS = new Set(['for', 'aria-labelledby', 'aria-describedby', 'aria-controls', 'aria-owns', 'list', 'form', 'headers']);
+const FILE_ATTRS = new Set(['src', 'href', 'poster', 'xlink:href']);
+
+/** The CSS a change writes into an element's own style (an override's `t`, `s`, `r` and `style`), by property. */
+function declarations(t: Omit<FilmOverride, 'at' | 'n' | 'lock'>): Array<[string, string]> {
+ const out: Array<[string, string]> = [];
+ if (t.t) out.push(['translate', `${t.t[0]}px ${t.t[1]}px`]);
+ if (t.s != null) out.push(['scale', Array.isArray(t.s) ? `${t.s[0]} ${t.s[1]}` : String(t.s)]);
+ if (t.r != null) out.push(['rotate', `${t.r}deg`]);
+ for (const [k, v] of Object.entries(t.style ?? {})) {
+ const prop = kebab(k);
+ out.push([prop, typeof v === 'number' && !prop.startsWith('--') && !UNITLESS.test(prop) ? `${v}px` : String(v)]);
+ }
+ return out;
+}
+
+/** A free id for a copy of `base`: `base-copy`, `base-copy-2` … (a copy's copy is named from the first). */
+export function copyId(base: string, taken: Set<string>): string {
+ const stem = `${base.replace(/-copy(-\d+)?$/, '') || 'layer'}-copy`;
+ let id = stem;
+ for (let n = 2; taken.has(id); n++) id = `${stem}-${n}`;
+ taken.add(id);
+ return id;
+}
+
+/** The `translate` a style says, in px ([0, 0] without one). */
+function translateOf(style: string | null | undefined): [number, number] {
+ const m = /(?:^|;)\s*translate\s*:\s*(-?[\d.]+)px(?:\s+(-?[\d.]+)px)?/.exec(style ?? '');
+ return m ? [Number(m[1]), Number(m[2] ?? 0)] : [0, 0];
+}
+
+interface CopyOptions {
+ /** The new ids, by the old ones; the copy's own (root) id. */
+ renamed: ReadonlyMap<string, string>;
+ rootId: string;
+ /** Per element of it, CSS to write in its style, and words. */
+ css: ReadonlyMap<SourceElement, ReadonlyMap<string, string>>;
+ words: ReadonlyMap<SourceElement, string>;
+ /** An address of a file, as the page it goes into names it. */
+ url?: (url: string) => string;
+ /** Ids given to elements of it that had none (a rule of the copy's names them). */
+ added?: ReadonlyMap<SourceElement, string>;
+}
+
+/** `el` of `text` as a copy (see the top): its markup with the edits made. */
+function copyMarkup(text: string, el: SourceElement, o: CopyOptions): string {
+ const edits: Array<{ start: number; end: number; text: string }> = [];
+ const url = o.url ?? ((u: string) => u);
+ /* `url(…)` in a value: an id renamed, a file named from the page it goes into */
+ const inValue = (value: string) => value.replace(/url\((&quot;|["']?)(.*?)\1\)/g, (_m, q: string, raw: string) => {
+ const u = q === '&quot;' ? raw.replace(/&amp;/g, '&') : raw;
+ const id = u.startsWith('#') ? o.renamed.get(u.slice(1)) : undefined;
+ const to = id ? `#${id}` : url(u);
+ return `url(${q}${q === '&quot;' ? escAttr(to) : to}${q})`;
+ });
+ const walk = (n: SourceElement) => {
+ /* a script goes, with all in it */
+ if (n.tag === 'script') { edits.push({ start: n.start, end: n.end, text: '' }); return; }
+ const extra = o.css.get(n);
+ let styled = false;
+ for (const a of n.attrs) {
+ if (/^on/.test(a.name)) { edits.push({ start: a.start - (/\s/.test(text[a.start - 1] ?? '') ? 1 : 0), end: a.end, text: '' }); continue; }
+ let value = a.value;
+ if (a.name === 'id' && value) value = n === el ? o.rootId : o.renamed.get(value) ?? value;
+ else if (value && NAMES_IDS.has(a.name)) value = value.split(/\s+/).map((v) => o.renamed.get(v) ?? v).join(' ');
+ else if (value && FILE_ATTRS.has(a.name)) value = value.startsWith('#') ? `#${o.renamed.get(value.slice(1)) ?? value.slice(1)}` : url(value);
+ else if (value) value = inValue(value);
+ if (a.name === 'style' && extra?.size) {
+ styled = true;
+ const own = (value ?? '').trim().replace(/;\s*$/, '');
+ value = [own, ...[...extra].map(([k, v]) => `${k}: ${v}`)].filter(Boolean).join('; ');
+ }
+ if (value !== a.value) edits.push({ start: a.start, end: a.end, text: `${a.name}="${escAttr(value ?? '')}"` });
+ }
+ /* an id added first, a style after its own attributes */
+ const added = n === el ? o.rootId : o.added?.get(n);
+ if (added && !n.attrs.some((a) => a.name === 'id')) edits.push({ start: n.nameEnd, end: n.nameEnd, text: ` id="${escAttr(added)}"` });
+ if (extra?.size && !styled) {
+ const after = n.attrs.length ? n.attrs[n.attrs.length - 1]!.end : n.nameEnd;
+ edits.push({ start: after, end: after, text: ` style="${escAttr([...extra].map(([k, v]) => `${k}: ${v}`).join('; '))}"` });
+ }
+ const said = o.words.get(n);
+ if (said != null) {
+ const kids = n.children;
+ /* as the film writes words (src/overrides.mjs): all of them, a <br> at each line break, when it holds words and
+ <br>s alone; else its first run of words, the other runs taken away, its elements kept */
+ if (kids.every((k) => k.kind === 'text' || k.tag === 'br')) {
+ edits.push({ start: n.openEnd, end: n.closeStart, text: said.split('\n').map(escText).join('<br>') });
+ return;
+ }
+ let first = true;
+ for (const k of kids) {
+ if (k.kind !== 'text' || !text.slice(k.start, k.end).trim()) continue;
+ edits.push({ start: k.start, end: k.end, text: first ? escText(said) : '' });
+ first = false;
+ }
+ }
+ for (const c of elementsOf(n)) walk(c);
+ };
+ walk(el);
+ let copy = text.slice(el.start, el.end);
+ /* from the last place up; two at one place in the order made (the later one written first, so it ends up after) */
+ const order = edits.map((e, i) => ({ ...e, i })).sort((a, b) => b.start - a.start || b.i - a.i);
+ for (const e of order) copy = copy.slice(0, e.start - el.start) + e.text + copy.slice(e.end - el.start);
+ return copy;
+}
+
+/** Each element of `el` by its path from it. */
+function byPath(el: SourceElement): Map<string, SourceElement> {
+ const at = new Map<string, SourceElement>();
+ const walk = (n: SourceElement, path: number[]) => { at.set(path.join('.'), n); elementsOf(n).forEach((c, i) => walk(c, [...path, i])); };
+ walk(el, []);
+ return at;
+}
+
+/** New ids for every id in `el`, the root's from `base` when it has none. */
+function newIds(el: SourceElement, base: string, taken: Set<string>): { renamed: Map<string, string>; rootId: string } {
+ const renamed = new Map<string, string>();
+ for (const n of byPath(el).values()) {
+ const id = n.attrs.find((a) => a.name === 'id')?.value;
+ if (id && !renamed.has(id)) renamed.set(id, copyId(id, taken));
+ }
+ const own = el.attrs.find((a) => a.name === 'id')?.value;
+ return { renamed, rootId: (own && renamed.get(own)) || copyId(base, taken) };
+}
+
+/** Every id the page's file has. */
+function idsOf(root: SourceElement): Set<string> {
+ const out = new Set<string>();
+ const walk = (n: SourceElement) => {
+ const id = n.attrs.find((a) => a.name === 'id')?.value;
+ if (id) out.add(id);
+ elementsOf(n).forEach(walk);
+ };
+ walk(root);
+ return out;
+}
+
+/** Where a `<style>` goes in the page's head: at the end of its `<head>`, else just inside `<html>`, else its top. */
+function headAt(text: string, root: SourceElement): number {
+ const html = elementsOf(root).find((e) => e.tag === 'html');
+ const head = elementsOf(html ?? root).find((e) => e.tag === 'head');
+ if (head && text.startsWith('</', head.closeStart)) return head.closeStart;
+ if (html) return html.openEnd;
+ const doctype = /^\s*<!doctype[^>]*>/i.exec(text);
+ return doctype ? doctype[0].length : 0;
+}
+
+/** The whitespace a line starts with up to `at`, when only whitespace is before it there. */
+function indentAt(text: string, at: number): string {
+ const line = text.lastIndexOf('\n', at - 1) + 1;
+ const before = text.slice(line, at);
+ return /^[ \t]*$/.test(before) ? before : '';
+}
+
+const lineBreak = (text: string) => (text.includes('\r\n') ? '\r\n' : '\n');
+
+/** A name as CSS writes it in a selector (CSS.escape, CSSOM: a leading digit, a `-` and a digit, other signs). */
+export function cssEscape(value: string): string {
+ let out = '';
+ for (let i = 0; i < value.length; i++) {
+ const ch = value[i]!;
+ const code = value.charCodeAt(i);
+ const digit = code >= 0x30 && code <= 0x39;
+ if (code === 0) out += '\uFFFD';
+ else if ((code >= 1 && code <= 0x1f) || code === 0x7f || (i === 0 && digit) || (i === 1 && digit && value.charCodeAt(0) === 0x2d)) out += `\\${code.toString(16)} `;
+ else if (i === 0 && value.length === 1 && ch === '-') out += `\\${ch}`;
+ else if (code >= 0x80 || /[\w-]/.test(ch)) out += ch;
+ else out += `\\${ch}`;
+ }
+ return out;
+}
+
+/** An id as a CSS selector names it. */
+const idSel = (id: string) => `#${cssEscape(id)}`;
+
+/**
+ * The ids a selector names, as CSS reads them: a `#` and a name, its escapes read (`\31 ` a 1, `\.` a dot) and
+ * what is not ASCII part of it; not in quotes. Each with where it is written.
+ */
+export function idsIn(sel: string): Array<{ start: number; end: number; id: string }> {
+ const out: Array<{ start: number; end: number; id: string }> = [];
+ /* an escape at `i` (a `\`): what it stands for, and where it ends */
+ const escape = (i: number): [string, number] => {
+ const hex = /^[0-9a-fA-F]{1,6}/.exec(sel.slice(i + 1, i + 7))?.[0];
+ if (!hex) return [sel[i + 1] ?? '', Math.min(sel.length, i + 2)];
+ let end = i + 1 + hex.length;
+ if (/\s/.test(sel[end] ?? '')) end++;
+ const code = Number.parseInt(hex, 16);
+ return [code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : '\uFFFD', end];
+ };
+ let quote: string | null = null;
+ for (let i = 0; i < sel.length;) {
+ const ch = sel[i]!;
+ if (quote) { i += ch === '\\' ? 2 : 1; if (ch === quote) quote = null; continue; }
+ if (ch === '"' || ch === "'") { quote = ch; i++; continue; }
+ if (ch === '\\') { i = escape(i)[1]; continue; }
+ if (ch !== '#') { i++; continue; }
+ let id = '';
+ let k = i + 1;
+ while (k < sel.length) {
+ const c = sel[k]!;
+ if (c === '\\') { const [got, end] = escape(k); id += got; k = end; } else if (/[\w-]/.test(c) || sel.charCodeAt(k) >= 0x80) { id += c; k++; } else break;
+ }
+ if (id) out.push({ start: i, end: k, id });
+ i = k;
+ }
+ return out;
+}
+
+/**
+ * A selector finding the element of id `id` alone, of weight `weight`: `:where()` weighs nothing, an id again, a
+ * `:not()` of a class or a tag no element has weigh one each.
+ */
+export function weighted(id: string, weight: readonly [number, number, number]): string {
+ const sel = idSel(id);
+ return `:where(${sel})${sel.repeat(weight[0])}${':not(.openfilm-none)'.repeat(weight[1])}${':not(openfilm-none)'.repeat(weight[2])}`;
+}
+
+/** A rule in its at-rules. */
+const wrapped = (within: readonly string[], rule: string) => within.reduceRight((inner, at) => `${at} { ${inner} }`, rule);
+
+/**
+ * Where a copy's rules of stylesheet `sheet` go: right after its `<style>` or `<link>` in the file (the `sheet`-th of
+ * them, so the cascade weighs them as its own rules, after them), when it is in the page's head; else at the end of
+ * the head.
+ */
+function sheetAt(text: string, root: SourceElement, sheet: number): number {
+ const owners: SourceElement[] = [];
+ const walk = (n: SourceElement, inBody: boolean) => {
+ for (const c of elementsOf(n)) {
+ if (c.tag === 'style' || (c.tag === 'link' && /(^|\s)stylesheet(\s|$)/i.test(c.attrs.find((a) => a.name === 'rel')?.value ?? ''))) owners.push(inBody ? { ...c, end: -1 } : c);
+ walk(c, inBody || c.tag === 'body');
+ }
+ };
+ walk(root, false);
+ const owner = sheet >= 0 ? owners[sheet] : undefined;
+ return owner && owner.end >= 0 ? owner.end : headAt(text, root);
+}
+
+/**
+ * The page `text` with a copy of each layer of `items` written in (see the top), `offset` px lower and to the right.
+ * Every layer is found in the file before anything is written; one inside another asked is copied with it. Null when
+ * the file does not hold one as the browser reads it (an element the page's code makes as it runs).
+ */
+export function pastedPage(text: string, items: readonly PasteItem[], offset: number): PastedPage | null {
+ const root = readSource(text);
+ const body = sourceBody(root);
+ const els = items.map(({ target }) => {
+ const el = elementAt(body, target.path, target.tags);
+ return el && !el.implied && sameShape(el, target.shape) ? el : null;
+ });
+ if (els.some((el) => !el)) return null;
+ const taken = idsOf(root);
+ const nl = lineBreak(text);
+ const writes: Array<{ at: number; text: string }> = [];
+ const rules: Array<{ sheet: number; text: string }> = [];
+ const ats: string[] = [];
+ items.forEach(({ layer, target, place, over, look }, i) => {
+ const el = els[i]!;
+ /* inside another one copied (or the same twice): copied with it */
+ if (els.some((o, k) => k !== i && o!.start <= el.start && o!.end >= el.end && (o!.start < el.start || o!.end > el.end || k < i))) {
+ ats.push('');
+ return;
+ }
+ const at = byPath(el);
+ const { renamed, rootId } = newIds(el, layer.classes[0] ?? layer.tag, taken);
+ const css = new Map<SourceElement, Map<string, string>>();
+ const words = new Map<SourceElement, string>();
+ const put = (n: SourceElement, decls: Array<[string, string]>) => {
+ const m = css.get(n) ?? new Map<string, string>();
+ for (const [k, v] of decls) { m.delete(k); m.set(k, v); }
+ css.set(n, m);
+ };
+ /* what the page's rules give the layer where it is (a :first-child) and not its copy where it goes, and the copy
+ and not it (a p + p): rules of the copy's, each weighed as the page's rule it answers, after its stylesheet (an
+ element of it without an id gets one for them) */
+ const added = new Map<SourceElement, string>();
+ const scoped: Array<{ sheet: number; text: string }> = [];
+ for (const { path, rules: own } of look ?? []) {
+ const n = at.get(path.join('.'));
+ if (!n || !own.length) continue;
+ const had = n.attrs.find((a) => a.name === 'id')?.value;
+ let id = n === el ? rootId : had ? renamed.get(had) : added.get(n);
+ if (!id) { id = copyId(n.attrs.find((a) => a.name === 'class')?.value?.split(/\s+/)[0] || n.tag, taken); added.set(n, id); }
+ for (const r of own) scoped.push({ sheet: r.sheet, text: wrapped(r.within, `${weighted(id, r.weight)}${r.pseudo ?? ''} { ${r.decls.map(([p, v]) => `${p}: ${v};`).join(' ')} }`) });
+ }
+ for (const { path, tag, ...tweak } of layer.tweaks) {
+ const n = at.get(path.join('.'));
+ if (!n || n.tag !== tag.toLowerCase()) continue;
+ put(n, declarations(tweak));
+ if (tweak.text != null) words.set(n, tweak.text);
+ }
+ /* held where it is laid out, moved by `offset` (and by its own move, a change's or its style's) */
+ const p = layer.place;
+ if (p && p.position !== 'absolute' && p.position !== 'fixed') {
+ put(el, [['position', 'absolute'], ['left', `${p.left}px`], ['top', `${p.top}px`], ['width', `${p.width}px`], ['height', `${p.height}px`], ['margin', '0'], ['box-sizing', 'border-box']]);
+ }
+ if (offset) {
+ const moved = css.get(el)?.get('translate')?.match(/^(-?[\d.]+)px (-?[\d.]+)px$/);
+ const [x, y] = moved ? [Number(moved[1]), Number(moved[2])] : translateOf(el.attrs.find((a) => a.name === 'style')?.value);
+ put(el, [['translate', `${x + offset}px ${y + offset}px`]]);
+ }
+ const copy = copyMarkup(text, el, { renamed, rootId, css, words, added });
+ rules.push(...scoped);
+ /* where it goes: over the copy before; else at its place among the elements beside it, when the file has them
+ as the page draws them; else right after it */
+ const parent = target.path.length > 1 ? elementAt(body, target.path.slice(0, -1), target.tags.slice(0, -1)) : body;
+ const kids = parent ? elementsOf(parent) : [];
+ const placed = Boolean(place && parent && !parent.implied && kids.length === place.siblings.length
+ && kids.every((k, n) => k.tag === place.siblings[n]!.toLowerCase()));
+ const previous = over ? elementAt(body, over.path, over.tags) : null;
+ const into = previous?.end ?? (placed && place && parent ? (place.after < 0 ? parent.openEnd : kids[place.after]!.end) : el.end);
+ writes.push({ at: into, text: `${nl}${indentAt(text, el.start)}${copy}` });
+ ats.push(idSel(rootId));
+ });
+ /* each stylesheet's after it, one <style> each */
+ const bySheet = new Map<number, string[]>();
+ for (const r of rules) bySheet.set(sheetAt(text, root, r.sheet), [...(bySheet.get(sheetAt(text, root, r.sheet)) ?? []), r.text]);
+ for (const [at, list] of bySheet) writes.push({ at, text: at === headAt(text, root) ? `<style>${list.join(' ')}</style>${nl}` : `${nl}<style>${list.join(' ')}</style>` });
+ return written(text, writes, ats);
+}
+
+/** `writes` made in `text`, from the last place up (two at one place: in the order given). */
+function written(text: string, writes: Array<{ at: number; text: string }>, ats: string[]): PastedPage {
+ let out = text;
+ const order = writes.map((w, i) => ({ ...w, i })).sort((a, b) => b.at - a.at || b.i - a.i);
+ for (const w of order) out = `${out.slice(0, w.at)}${w.text}${out.slice(w.at)}`;
+ return { text: out, ats, inserted: writes.map((w) => w.text) };
+}
+
+/** `path` (project relative) as a page at `page` names it. */
+export function relativeTo(page: string, path: string): string {
+ const from = page.split('/').slice(0, -1);
+ const to = path.split('/');
+ let k = 0;
+ while (k < from.length && k < to.length - 1 && from[k] === to[k]) k++;
+ return [...from.slice(k).map(() => '..'), ...to.slice(k)].join('/');
+}
+
+/**
+ * The page `text` (the project's page `page`) with a copy of each of `layers` written last in its `<body>` (drawn
+ * over the rest), as it looks now (its snapshot), where it was in its page, `offset` px lower and to the right of where
+ * it is drawn (its own move kept). Its ids are new ones in this page, what names them in it too. What it loads from its
+ * project is named from this page; `moved` says where a file of its project is in this one (another project's are
+ * brought in first). Null when one has no snapshot.
+ */
+export function pastedElsewhere(
+ text: string, page: string, layers: readonly PasteLayer[], offset: number, moved: (path: string) => string = (p) => p,
+): PastedPage | null {
+ if (layers.some((l) => !l.snapshot)) return null;
+ const root = readSource(text);
+ const body = sourceBody(root);
+ const taken = idsOf(root);
+ const nl = lineBreak(text);
+ const at = body.tag === 'body' && text.startsWith('</', body.closeStart) ? body.closeStart : text.length;
+ const writes: Array<{ at: number; text: string }> = [];
+ const fonts = new Set<string>();
+ const ats: string[] = [];
+ for (const layer of layers) {
+ const shot = layer.snapshot!;
+ const local = (url: string) => (url.startsWith(shot.base) ? relativeTo(page, moved(decodeURI(url.slice(shot.base.length)))) : url);
+ const el = elementsOf(readSource(shot.html))[0];
+ if (!el) return null;
+ const { renamed, rootId } = newIds(el, layer.id ?? layer.classes[0] ?? layer.tag, taken);
+ const css = new Map<SourceElement, Map<string, string>>();
+ if (offset) {
+ const [x, y] = translateOf(el.attrs.find((a) => a.name === 'style')?.value);
+ css.set(el, new Map([['translate', `${x + offset}px ${y + offset}px`]]));
+ }
+ writes.push({ at, text: `${copyMarkup(shot.html, el, { renamed, rootId, css, words: new Map(), url: local })}${nl}` });
+ for (const f of shot.fonts) fonts.add(f.replace(/url\((["']?)([^"')]+)\1\)/g, (_m, _q, u: string) => `url("${local(u)}")`));
+ ats.push(idSel(rootId));
+ }
+ if (fonts.size) writes.push({ at: headAt(text, root), text: `<style>${[...fonts].join(' ')}</style>${nl}` });
+ return written(text, writes, ats);
+}
+
+/**
+ * The page `text` without what a paste wrote in (`inserted`, as pastedPage says it), for an undo of a page written
+ * since (by the agent): each piece taken out where it is, once; with where each was (in the text as it was then,
+ * piece after piece), for a redo (withPaste). Null when one is not there as it was written.
+ */
+export function withoutPaste(text: string, inserted: readonly string[]): { text: string; at: number[] } | null {
+ let out = text;
+ const at: number[] = [];
+ for (const piece of inserted) {
+ const i = out.indexOf(piece);
+ if (i < 0 || out.indexOf(piece, i + 1) >= 0) return null;
+ out = out.slice(0, i) + out.slice(i + piece.length);
+ at.push(i);
+ }
+ return { text: out, at };
+}
+
+/** `text` with the pieces withoutPaste took out of it put back where they were (a redo of that undo). */
+export function withPaste(text: string, inserted: readonly string[], at: readonly number[]): string {
+ let out = text;
+ for (let k = inserted.length - 1; k >= 0; k--) out = out.slice(0, at[k]) + inserted[k] + out.slice(at[k]);
+ return out;
+}