The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Studio: delete layers inside a page, not only hide them (#270)
riverisbuildingf17330f2f6a8
diff --git a/.changeset/delete-layers.md b/.changeset/delete-layers.mdnew file mode 100644index 0000000..73911f4--- /dev/null+++ b/.changeset/delete-layers.md@@ -0,0 +1,5 @@+---+"openfilm": patch+---++Studio: layers inside a page can be deleted, not only hidden. Use the bin on a row of the Layers panel, Delete in the layer's menu (one layer or several), or Delete / Backspace while a layer is selected and no text field has focus. The page file is not changed: the clip gets a `display: none` override for the layer. Its other changes, the changes of the layers inside it and the component properties made from them are removed in the same step. One undo brings everything back. The deleted layer no longer appears in the Layers panel.diff --git a/packages/openfilm/studio/server/stage.js b/packages/openfilm/studio/server/stage.jsindex 5ede781..bd8a943 100644--- a/packages/openfilm/studio/server/stage.js+++ b/packages/openfilm/studio/server/stage.js@@ -1228,13 +1228,17 @@/* ── the Layers panel's tree ── */const ROWS = 800;- /** Per element, whether the clip's kept overrides hide it (the panel's eye) or lock it: the last one to say counts. */+ /**+ * Per element, whether the clip's kept overrides hide it (the panel's eye), lock it, or delete it (`display: none`,+ * the panel's delete: it has no row): the last one to say counts.+ */const ownOverrides = (c) => {const out = new Map();for (const o of c.overrides ?? []) {const says = {...(o.style && 'visibility' in o.style ? { hidden: o.style.visibility === 'hidden' } : {}),...('lock' in o ? { locked: o.lock === true } : {}),+ ...(o.style && 'display' in o.style ? { deleted: o.style.display === 'none' } : {}),};if (Object.keys(says).length) for (const el of matches(c.win.document, o)) out.set(el, { ...out.get(el), ...says });}@@ -1260,7 +1264,7 @@for (const ch of parentEl.children) {if (count >= ROWS) break;const tag = ch.localName.toLowerCase();- if (SKIP.has(tag) || ch.hasAttribute(EDITOR_ATTR)) continue;+ if (SKIP.has(tag) || ch.hasAttribute(EDITOR_ATTR) || kept.get(ch)?.deleted) continue;const kind = kindOf(ch) ?? (isGroup(ch) ? 'box' : null);const leaf = tag === 'svg' || kind === 'text' || kind === 'image';const inner = leaf ? [] : collect(ch);@@ -1461,6 +1465,21 @@lost: c.overrides.filter((o, i) => o?.at && !c.found?.[i] && !matches(c.win.document, o).length).map((o) => o.at),}));},+ /**+ * Which of `targets` (selectors with their match, as overrides and component properties name a layer) name only+ * layers that are, or are inside, the layers `of` of clip `clip`: what deleting those leaves pointing at nothing.+ * One answer per target; a target that finds nothing is not one of them.+ */+ within({ clip, of, targets }) {+ const c = clipById(clip);+ const doc = c?.kind === 'page' ? c.win?.document : null;+ if (!doc) return null;+ const gone = (of ?? []).flatMap((o) => matches(doc, o));+ return (targets ?? []).map((o) => {+ const found = o?.at ? matches(doc, o) : [];+ return found.length > 0 && found.every((el) => gone.some((g) => g.contains(el)));+ });+ },/** 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.mjsindex 57417c6..045956c 100644--- a/packages/openfilm/studio/server/stage.test.mjs+++ b/packages/openfilm/studio/server/stage.test.mjs@@ -445,3 +445,32 @@ test('a picture inside a page says what it draws: an <img>, a box painted with oawait stage.close();}});++test('a deleted layer has no row in the Layers tree; what points only at it or inside it is found', { timeout: 60_000 }, async () => {+ const dir = mkdtempSync(join(tmpdir(), 'of-stage-delete-'));+ writeFileSync(join(dir, 'card.html'), `<!doctype html><body style="margin:0">+<div id="card" style="position:absolute;left:20px;top:20px;width:200px;height:120px;background:#f60">+ <h1 id="title" style="margin:0;font:700 24px sans-serif">Every parcel</h1>+ <p class="note" style="margin:0;font:14px sans-serif">On time</p>+</div>+<p class="note" style="position:absolute;left:240px;top:20px;margin:0;font:14px sans-serif">Elsewhere</p>+<script>window.film={duration:2,frame(){}}</script></body>`);+ const overrides = [{ at: '#card', style: { display: 'none' } }, { at: '#title', 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 labels = (rows) => rows.flatMap((r) => [r.label, ...labels(r.children)]);+ const tree = await stage.ask('tree');+ const shown = labels(tree[0].layers);+ assert.ok(shown.includes('Elsewhere'), 'the layer outside it keeps its row');+ assert.ok(!shown.includes('Every parcel') && !shown.includes('On time'), 'neither it nor what is inside it has a row');+ const within = await stage.ask('within', {+ clip: 'card',+ of: [{ at: '#card' }],+ targets: [{ at: '#card' }, { at: '#title' }, { at: '.note' }, { at: '.note', n: 1 }, { at: '.note', n: 2 }, { at: '#nothing' }, {}],+ });+ assert.deepEqual(within, [true, true, false, true, false, false, false]);+ } finally {+ await stage.close();+ }+});diff --git a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsxindex 90f179d..da1a8cb 100644--- a/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx+++ b/packages/openfilm/studio/ui/src/components/FilmStageSelect.tsx@@ -216,6 +216,8 @@ export interface FilmStageControl {picked(): StagePick[];/** Write now what the arrow keys moved and is not written yet: before an undo, or any other edit. */flushPending(): void;+ /** These layers deleted: let go of them if they are in hand, so no frame stays on what is gone. */+ letGo(elements: readonly StageElement[]): void;/*** Several layers in hand: their bounds put at `x` / `y` (all moved alike), or made `w` / `h` wide (all scaled alike,* in proportion, about the bounds' top left), as the inspector's fields move and scale a selection. Stage px.@@ -1144,15 +1146,17 @@ function FilmStageSelectImpl({if (!nudgeClip(e)) nudgeLayer(e);return;}- /* the shortcuts are the menu's items: ⇧⌘H hide, ⇧⌘L lock, ] / [ to the front / back; grayed ones- do nothing. A whole clip's delete / copy / paste are the timeline's keys. */+ /* 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. */const mod = e.metaKey || e.ctrlKey;const k = e.key.toLowerCase();+ const action = keyAction(e);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'- : null;+ : action === 'remove' || action === 'ripple-delete' ? 'delete'+ : null;/* C crops the video or still in hand */if (!mod && !e.altKey && !e.shiftKey && k === 'c' && !textEdit.current && !typingNow()) {if (startCrop()) e.preventDefault();@@ -1173,8 +1177,12 @@ function FilmStageSelectImpl({e.preventDefault();e.stopPropagation();item.onSelect();+ /* a delete leaves no frame behind (the layer is gone) */+ if (menuId === 'delete') dropPick();return;}+ /* a locked layer's Delete deletes nothing, not its clip on the timeline either */+ if (item && menuId === 'delete') { e.preventDefault(); e.stopPropagation(); return; }}}if (e.key === 'Enter' && !e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey) {@@ -1349,6 +1357,11 @@ function FilmStageSelectImpl({return () => { lookPreviewRef.current = null; };}, [ask, lookPreviewRef]);+ const letGoRef = React.useRef<(elements: readonly StageElement[]) => void>(() => {});+ letGoRef.current = (elements) => {+ const held = [...(multiRef.current ?? []).map((item) => item.element), pickedRef.current?.element];+ if (held.some((h) => h && elements.some((e) => e.loc === h.loc && e.clipId === h.clipId))) dropPick();+ };/* the inspector's live layer previews */React.useEffect(() => {if (!controlRef) return undefined;@@ -1358,6 +1371,7 @@ function FilmStageSelectImpl({return target && element.clipId ? { clip: element.clipId, ...target } : null;};controlRef.current = {+ letGo: (elements) => letGoRef.current(elements),previewStyle(element, patch) {const at = named(element);if (at) void ask('tweak', { ...at, patch: { style: clean(patch as Record<string, string | number | null | undefined>) } }).then(syncGeomSoon);diff --git a/packages/openfilm/studio/ui/src/components/LayersPanel.tsx b/packages/openfilm/studio/ui/src/components/LayersPanel.tsxindex c32221a..8517e01 100644--- a/packages/openfilm/studio/ui/src/components/LayersPanel.tsx+++ b/packages/openfilm/studio/ui/src/components/LayersPanel.tsx@@ -1,15 +1,16 @@/*** The Layers panel: what is on the picture at the playhead as layers, the top one first. Each picture clip shown is* 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 and its lock keeps it from- * being moved; 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.+ * 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+ * (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.*/import React from 'react';import {- ChevronRight, Eye, EyeOff, Film, Globe, Image as ImageIcon, Lock, LockOpen, Shapes, Square, SquareDashed, Type, X,+ ChevronRight, Eye, EyeOff, Film, Globe, Image as ImageIcon, Lock, LockOpen, Shapes, Square, SquareDashed, Trash2, Type, X,} from 'lucide-react';import { useT } from '@/i18n';import {@@ -45,6 +46,8 @@ export interface LayersPanelProps {onPoint: (target: { clipId: string; loc: string } | null) => void;/** The eye or the lock of a row. */onToggle: (clipId: string, row: LayerRow, what: 'hidden' | 'locked') => void;+ /** A row's bin: its layer deleted. */+ onDelete: (clipId: string, row: LayerRow) => void;/** 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;@@ -206,7 +209,8 @@ export function LayersPanel(p: LayersPanelProps) {if (loc) p.onSelectClip(loc);}}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); }} />+ onToggle={(what) => { if (line.row) p.onToggle(line.clipId, line.row, what); }}+ onDelete={() => { if (line.row) p.onDelete(line.clipId, line.row); }} />))}{drag ? (<div aria-hidden className="pointer-events-none absolute right-2 h-0.5 rounded-full bg-[var(--accent)]"@@ -224,7 +228,7 @@ export function LayersPanel(p: LayersPanelProps) {);}-function LayerLineRow({ line, top, t, clipOf, selected, dragging, onToggleOpen, onPress, onClick, onPoint, onToggle }: {+function LayerLineRow({ line, top, t, clipOf, selected, dragging, onToggleOpen, onPress, onClick, onPoint, onToggle, onDelete }: {line: LayerLine;top: number;t: ReturnType<typeof useT>;@@ -236,6 +240,7 @@ function LayerLineRow({ line, top, t, clipOf, selected, dragging, onToggleOpen,onClick: () => void;onPoint: () => void;onToggle: (what: 'hidden' | 'locked') => void;+ onDelete: () => void;}) {const row = line.row;const clip = row ? null : clipOf(line.clipId);@@ -270,6 +275,16 @@ function LayerLineRow({ line, top, t, clipOf, selected, dragging, onToggleOpen,) : <span className="w-4 shrink-0" />}<Icon size={13} className={`shrink-0 ${dim ? 'opacity-40' : 'text-[var(--text-muted)]'}`} aria-hidden /><span className={`min-w-0 flex-1 truncate ${row ? '' : 'font-medium text-[var(--text)]'} ${dim ? 'opacity-45' : ''}`}>{label}</span>+ {row && !row.locked ? (+ <Tooltip label={t('layers.delete')} side="bottom">+ <button type="button" aria-label={t('layers.delete')}+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => { e.stopPropagation(); onDelete(); }}+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-[var(--text-dim)] opacity-0 hover:bg-[var(--bg-hover)] hover:text-[var(--err)] focus-visible:opacity-100 group-hover:opacity-100">+ <Trash2 size={12} />+ </button>+ </Tooltip>+ ) : null}{row ? flag('locked', row.locked, Lock, LockOpen, t('layers.unlock'), t('layers.lock')) : null}{row ? flag('hidden', row.hidden, EyeOff, Eye, t('layers.show'), t('layers.hide')) : null}</div>diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsxindex 5f69c18..35c23a2 100644--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx@@ -103,6 +103,7 @@ 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 type { PropsHost } from './PropertiesSection';import type { LayerPropsActions } from './FilmInspector';import { SAVED, refreshSaved, savedActions, savedSources, useSavedListing } from '@/lib/saved';@@ -111,7 +112,7 @@ import { groupInsertAt, groupInsertOps } from '@/lib/saved-insert';import { pageClips, pageMayHave, similarEdits } from '@/lib/similar-layers';import type { MaskSession } from '@/lib/stage-mask';import type { MaskShape } from '@/lib/clip-mask';-import { nextOverrides, overrideOf, type OverrideGeometry } from '@/lib/film-overrides';+import { nextOverrides, overrideOf, type OverrideGeometry, type OverrideTarget } from '@/lib/film-overrides';import { compactScale, type MgTransform, type NodeOverride, type OverridePivot, type StageElement, type StageElementStyle, type StageGeometry } from '@/lib/stage-types';import { usePreviewPrefs } from '@/lib/preview-prefs';import { isTypingTarget } from './typing-target';@@ -1550,6 +1551,57 @@ export function ProjectView({ projectId, onProject, onLeave }: {if (!byClip.size) return t('timeline.editFail');return editBlocks([...byClip].map(([loc, value]) => ({ loc, prop: 'overrides', value: value as unknown as Record<string, unknown> | null })));}, [editBlocks, t]);+ /* layers deleted (lib/layer-delete): in each clip a `display: none` entry for each, and every change or property+ that pointed only at them, or inside them, gone too (the stage tells which); one write, one undo step */+ const deleteLayers = React.useCallback(async (elements: readonly StageElement[]): Promise<string | null> => {+ type Clip = NonNullable<ReturnType<typeof pageClipOf>>['clip'];+ /* the layers by the clip they are in (its place in film.html) */+ const byClip = (doc: FilmDoc) => {+ const out = new Map<string, { clip: Clip; targets: OverrideTarget[] }>();+ for (const element of elements) {+ const found = pageClipOf(doc, element);+ const target = layerTarget(element);+ if (!found || !target) continue;+ const entry = out.get(found.loc) ?? { clip: found.clip, targets: [] };+ entry.targets.push(target);+ out.set(found.loc, entry);+ }+ return out;+ };+ const keyOf = (at: OverrideTarget) => JSON.stringify([at.at, at.n ?? null]);+ const asked = filmRef.current ? byClip(filmRef.current as unknown as FilmDoc) : null;+ if (!asked?.size) return t('timeline.editFail');+ /* per clip, where its changes and properties point that is only at the deleted layers or inside them */+ const gone = new Map<string, Set<string>>();+ for (const { clip, targets } of asked.values()) {+ const pointers = pointersOf(clip.overrides, propsOf(clip));+ const all = [...pointers.overrides, ...pointers.props].filter((at): at is OverrideTarget => at != null);+ const answer = await preview.current?.stage?.<boolean[]>('within', { clip: clip.id, of: targets, targets: all }) ?? [];+ gone.set(clip.id, new Set(all.filter((_, i) => answer[i] === true).map(keyOf)));+ }+ /* the film read again after asking: an edit kept meanwhile is not written over */+ const doc = filmRef.current as unknown as FilmDoc | null;+ const now = doc ? byClip(doc) : null;+ if (!now?.size) return t('timeline.editFail');+ const edits: ClipEdit[] = [];+ for (const [loc, { clip, targets }] of now) {+ const out = gone.get(clip.id) ?? new Set<string>();+ const isGone = (at: OverrideTarget | null) => Boolean(at && out.has(keyOf(at)));+ const props = propsOf(clip);+ const pointers = pointersOf(clip.overrides, props);+ const overrides = withDeleted(clip.overrides, targets, pointers.overrides.map(isGone));+ edits.push({ loc, prop: 'overrides', value: overrides as unknown as Record<string, unknown> | null });+ const kept = propsWithoutDeleted(props, pointers.props.map(isGone));+ if (kept.length !== props.length) edits.push({ loc, prop: 'props', value: propsAttr(kept) });+ }+ const failed = await editBlocks(edits);+ /* refused (a locked track), what is in hand stays in hand */+ if (!failed) {+ setStageElement((el) => (el && elements.some((x) => x.loc === el.loc && x.clipId === el.clipId) ? null : el));+ stageControl.current?.letGo(elements);+ }+ return failed;+ }, [editBlocks, t]);const editStageStyle = React.useCallback(async (loc: string, patch: StageElementStyle): Promise<string | null> => {const held = stageElementRef.current;if (!held?.clipLoc) return t('timeline.editFail');@@ -1665,6 +1717,12 @@ export function ProjectView({ projectId, onProject, onLeave }: {const patch = what === 'hidden' ? { style: { visibility: row.hidden ? null : 'hidden' } } : { lock: !row.locked };void editStageOverrides([{ element: layerElement(clipId, at, row.instance, row.label), patch: patch as OverrideGeometry }]).then((f) => { if (f) toast.show(f); });}, [editStageOverrides, toast]); // eslint-disable-line react-hooks/exhaustive-deps+ const deleteLayerRow = React.useCallback((clipId: string, row: LayerRow) => {+ const at = row.instance ? row.loc.slice(0, -`#${row.instance}`.length) : row.loc;+ /* its outline on the picture goes with it */+ 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-depsconst 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); });@@ -1762,6 +1820,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {const stageMenuFor = React.useCallback((el: StageElement, ctx: StageMenuContext) => stageMenu(el, ctx, {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); }); },selectParent: selectStageParent,selectClip: selectStageClip,notify: (message) => toast.show(message),@@ -2767,6 +2826,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {onSelectClip={selectStageClip}onPoint={setPointedLayer}onToggle={toggleLayerRow}+ onDelete={deleteLayerRow}onRestack={restackLayers}onNotify={toast.show}width={layersShownWidth}diff --git a/packages/openfilm/studio/ui/src/components/stage-menu.tsx b/packages/openfilm/studio/ui/src/components/stage-menu.tsxindex 5d0bdcb..9256d6a 100644--- a/packages/openfilm/studio/ui/src/components/stage-menu.tsx+++ b/packages/openfilm/studio/ui/src/components/stage-menu.tsx@@ -4,7 +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); 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); the clip's actions are+ * the editor's, passed in.*/import type * as React from 'react';import {@@ -76,6 +77,8 @@ export interface StageMenuActions {editOverride(element: StageElement, patch: OverrideGeometry | null): void;/** Several layers' overrides at once: one save, one undo step. */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;/** 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). */@@ -168,6 +171,15 @@ export function stageMenu(el: StageElement, ctx: StageMenuContext, actions: Stagid: '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 } }))),});+ const deleteLayers = actions.deleteLayers;+ if (deleteLayers) {+ m.sep();+ const anyLocked = many.some((x) => x.override?.lock);+ m.push({+ id: 'delete', label: t('timeline.removeBlock'), icon: <Trash2 size={14} />, danger: true, shortcut: hintOf(currentKeymap(), 'remove', MAC),+ disabled: anyLocked, hint: t('stageMenu.lockedHint'), onSelect: () => deleteLayers(many),+ });+ }return m.done();}@@ -258,6 +270,14 @@ export function stageMenu(el: StageElement, ctx: StageMenuContext, actions: Stagif (clipLoc) m.push({ id: 'clip', label: t('stageMenu.selectClip'), icon: <Layers size={14} />, onSelect: () => actions.selectClip(clipLoc) });const words = el.text?.value;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) {+ m.sep();+ m.push({+ id: 'delete', label: t('timeline.removeBlock'), icon: <Trash2 size={14} />, danger: true, shortcut: hintOf(currentKeymap(), 'remove', MAC),+ disabled: locked, hint: t('stageMenu.lockedHint'), onSelect: () => deleteLayers([el]),+ });+ }return m.done();}diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.tsindex cdd8173..ece846a 100644--- a/packages/openfilm/studio/ui/src/i18n/en.ts+++ b/packages/openfilm/studio/ui/src/i18n/en.ts@@ -997,6 +997,7 @@ export const en = {show: 'Show',lock: 'Lock',unlock: 'Unlock',+ delete: 'Delete',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.tsindex 9faa14a..7cf02ee 100644--- a/packages/openfilm/studio/ui/src/i18n/es.ts+++ b/packages/openfilm/studio/ui/src/i18n/es.ts@@ -996,6 +996,7 @@ export const es: Words = {show: 'Mostrar',lock: 'Bloquear',unlock: 'Desbloquear',+ delete: 'Eliminar',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.tsindex b26d2c6..250c3ee 100644--- a/packages/openfilm/studio/ui/src/i18n/ja.ts+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts@@ -996,6 +996,7 @@ export const ja: Words = {show: '表示',lock: 'ロック',unlock: 'ロック解除',+ delete: '削除',notNow: 'この時点では画面にありません',restackFailed: 'このレイヤーの重ね順を変更できませんでした。画面が変わった可能性があります。もう一度お試しください。',},diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.tsindex 91ace62..dad770a 100644--- a/packages/openfilm/studio/ui/src/i18n/ko.ts+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts@@ -993,6 +993,7 @@ export const ko: Words = {show: '표시',lock: '잠금',unlock: '잠금 해제',+ delete: '삭제',notNow: '지금은 화면에 없습니다',restackFailed: '이 레이어의 순서를 바꾸지 못했습니다. 화면이 바뀌었을 수 있으니 다시 시도하세요.',},diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.tsindex 4147f83..1c6e52a 100644--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts@@ -997,6 +997,7 @@ export const zhCN: Words = {show: '显示',lock: '锁定',unlock: '解锁',+ delete: '删除',notNow: '此刻不在画面上',restackFailed: '这个图层没能调整顺序。画面可能刚变过,再试一次。',},diff --git a/packages/openfilm/studio/ui/src/lib/layer-delete.test.ts b/packages/openfilm/studio/ui/src/lib/layer-delete.test.tsnew file mode 100644index 0000000..6b7b1fe--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/layer-delete.test.ts@@ -0,0 +1,43 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { pointersOf, propsWithoutDeleted, withDeleted } from './layer-delete.ts';+import type { ComponentProp } from './component-props.ts';+import type { FilmOverride } from './film.ts';++test('a deleted layer keeps one entry: display none, where its first was', () => {+ const all: FilmOverride[] = [+ { fade: [0.5, 0] },+ { at: '#title', t: [4, 0], style: { color: 'red' }, text: 'Hi' },+ { at: '.card', n: 2, s: 1.2 },+ { at: '#title', lock: true },+ ];+ assert.deepEqual(withDeleted(all, [{ at: '#title' }]), [+ { fade: [0.5, 0] },+ { at: '#title', style: { display: 'none' } },+ { at: '.card', n: 2, s: 1.2 },+ ]);+ /* one of several matches: its own entry, the others' left alone */+ assert.deepEqual(withDeleted(all, [{ at: '.card', n: 1 }]), [...all, { at: '.card', n: 1, style: { display: 'none' } }]);+ assert.deepEqual(withDeleted(undefined, [{ at: '#x' }]), [{ at: '#x', style: { display: 'none' } }]);+});++test('what points only at deleted layers goes with them; the clip\'s own entry stays', () => {+ const all: FilmOverride[] = [{ fade: [0, 1] }, { at: '#card' }, { at: '#title', t: [1, 1] }, { at: '.note', style: { color: 'red' } }];+ assert.deepEqual(withDeleted(all, [{ at: '#card' }], [true, true, true, false]), [+ { fade: [0, 1] },+ { at: '#card', style: { display: 'none' } },+ { at: '.note', style: { color: 'red' } },+ ]);+ assert.equal(withDeleted([{ at: '#title', t: [1, 1] }], [], [true]), null);+});++test('the properties made of deleted layers go; a variable is no layer\'s', () => {+ const props: ComponentProp[] = [+ { name: 'Title', type: 'text', at: '#title' },+ { name: 'Accent', type: 'var', var: '--accent' },+ { name: 'Photo', type: 'image', kind: 'img', at: 'img', n: 2 },+ ];+ const pointers = pointersOf([{ fade: [0, 1] }, { at: '#a', n: 3 }], props);+ assert.deepEqual(pointers, { overrides: [null, { at: '#a', n: 3 }], props: [{ at: '#title' }, null, { at: 'img', n: 2 }] });+ assert.deepEqual(propsWithoutDeleted(props, [true, true, false]).map((p) => p.name), ['Accent', 'Photo']);+});diff --git a/packages/openfilm/studio/ui/src/lib/layer-delete.ts b/packages/openfilm/studio/ui/src/lib/layer-delete.tsnew file mode 100644index 0000000..42cc993--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/layer-delete.ts@@ -0,0 +1,60 @@+/**+ * Deleting layers inside a page (the Layers panel's delete, the picture's Delete key and menu): the page is shared by+ * every clip of it and is the agent's, so it is never written. What goes is the layer in this clip: an override of+ * `display: none` (applied with priority, it takes the layer out of the page's flow as if it were not written), the+ * one entry its clip keeps for it. Every other change pointing only at it or at what is inside it goes too — its own+ * moves and styles, those of the layers inside it, the component properties made of them — so nothing is left that+ * changes nothing. It is one edit of film.html: an undo puts it all back.+ *+ * Pure: no React, no DOM, so `node --test` runs it.+ */++import type { FilmOverride } from './film.ts';+import type { ComponentProp } from './component-props.ts';+import type { OverrideTarget } from './film-overrides.ts';++/** The style that deletes a layer. */+const DELETED_STYLE = { display: 'none' } as const;++const same = (o: { at?: string; n?: number }, t: OverrideTarget) => o.at === t.at && (o.n ?? null) === (t.n ?? null);++/**+ * The clip's overrides with `targets` deleted: each one's entries replaced by one `display: none` entry (where its+ * first entry was, else last), and the entries `gone` says point only at deleted layers (one answer per entry of+ * `all`, studio/server/stage.js `within`) left out. The clip's own entry (its fades) is kept. Null: none left.+ */+export function withDeleted(+ all: readonly FilmOverride[] | undefined, targets: readonly OverrideTarget[], gone: readonly boolean[] = [],+): FilmOverride[] | null {+ const list = all ?? [];+ const out: FilmOverride[] = [];+ const placed = new Set<OverrideTarget>();+ const entry = (t: OverrideTarget): FilmOverride => (+ { at: t.at, ...(t.n != null ? { n: t.n } : {}), style: { ...DELETED_STYLE } }+ );+ list.forEach((o, i) => {+ const t = o.at === undefined ? undefined : targets.find((x) => same(o, x));+ if (t) {+ if (!placed.has(t)) { placed.add(t); out.push(entry(t)); }+ return;+ }+ if (o.at !== undefined && gone[i]) return;+ out.push(o);+ });+ for (const t of targets) if (!placed.has(t)) out.push(entry(t));+ return out.length ? out : null;+}++/** The component properties left once the ones `gone` says name only deleted layers (one answer per property) go. */+export function propsWithoutDeleted(list: readonly ComponentProp[], gone: readonly boolean[]): ComponentProp[] {+ return list.filter((p, i) => p.type === 'var' || !gone[i]);+}++/** What `within` is asked of a clip: where each override and each property points (a variable points at no layer). */+export function pointersOf(overrides: readonly FilmOverride[] | undefined, props: readonly ComponentProp[]): {+ overrides: (OverrideTarget | null)[];+ props: (OverrideTarget | null)[];+} {+ const of = (o: { at?: string; n?: number }) => (o.at ? { at: o.at, ...(o.n != null ? { n: o.n } : {}) } : null);+ return { overrides: (overrides ?? []).map(of), props: props.map((p) => (p.type === 'var' ? null : of(p))) };+}