The VS Code of video editing, built for agents.
TypeScript
Add copy and paste functionality to DocumentEditor and keyboard shortcuts
konstantin-paulusf10ee0486ae9
diff --git a/apps/web/src/engine/editor.ts b/apps/web/src/engine/editor.tsindex 6f8343c9..da2191c1 100644--- a/apps/web/src/engine/editor.ts+++ b/apps/web/src/engine/editor.ts@@ -18,7 +18,7 @@ import { authoredElement, authoredTree, getRuntimeDocument, insert, isSceneNode,import type { PropValue } from '@diffusionstudio/jsx';import type { Entity, World } from 'koota';-import type { HostNode, ProjectDocument, RuntimeDocument } from '@diffusionstudio/reconciler';+import type { AuthoredTree, HostNode, ProjectDocument, RuntimeDocument } from '@diffusionstudio/reconciler';/*** A property the editor changed, in the vocabulary of the JSX rather than of@@ -124,9 +124,20 @@ interface Recorded {props: Record<string, PropValue>;}+/**+ * What `copy` took: the subtrees as authored, and the source of the parent+ * they were copied out of (by stamp, so it outlives a remount), which `paste`+ * needs to keep a clip out of the sequence it came from.+ */+interface Clipboard {+ trees: AuthoredTree[];+ parent?: string;+}+export class DocumentEditor {private readonly world: World;private sink?: (edit: EntityEdit) => void;+ private clipboard: Clipboard = { trees: [] };public constructor(world: World) {this.world = world;@@ -417,24 +428,10 @@ export class DocumentEditor {* `active`: one entity holds it). Returns the copies' top-level entities.*/public duplicate(entities: Entity | Entity[]): Entity[] {- const wanted = new Set(- (Array.isArray(entities) ? entities : [entities]).filter(- (entity) => entity.isAlive() && !entity.has(Stage) && !!entity.get(Source)?.value,- ),- );- const roots = [...wanted].filter((entity) => {- for (let parent = getParentEntity(entity); parent; parent = getParentEntity(parent)) {- if (wanted.has(parent)) return false;- }- return true;- });-const copies: Entity[] = [];- for (const source of roots) {- const tree = authoredTree(this.world, source);+ for (const source of this.subtreeRoots(entities)) {+ const tree = this.spell(source);if (!tree) continue;- delete tree.props.selected;- delete tree.props.active;// Out of any sequence, on top of what it left.let below = source;@@ -455,6 +452,78 @@ export class DocumentEditor {return copies;}+ /**+ * Takes a copy of `entities` (the tops of their subtrees, as `duplicate`+ * would) for `paste`. Nothing is reported: the file only changes when the+ * copy lands. Leaves the clipboard alone when there is nothing to copy.+ */+ public copy(entities: Entity | Entity[]): void {+ const roots = this.subtreeRoots(entities);+ const trees = roots.map((root) => this.spell(root)).filter((tree) => tree !== undefined);+ if (!trees.length) return;+ this.clipboard = { trees, parent: getParentEntity(roots[0]!)?.get(Source)?.value };+ }++ /**+ * Inserts what `copy` took under `parent`, in front of `anchor` or last,+ * with the same props it was copied with — same position, if the parent is+ * the same. Pasting back into the sequence it was copied out of would put a+ * clip on top of itself, so that goes to the sequence's parent instead, on+ * top of the sequence (`duplicate`'s rule). The selection moves to the+ * copies. Returns their top-level entities.+ */+ public paste(parent: Entity, anchor?: Entity): Entity[] {+ const { trees, parent: copiedFrom } = this.clipboard;+ if (!trees.length) return [];++ if (parent.has(Sequential) && copiedFrom !== undefined && parent.get(Source)?.value === copiedFrom) {+ const outer = getParentEntity(parent);+ if (!outer) return [];+ const siblings = getEntityChildren(this.world, outer);+ anchor = siblings[siblings.indexOf(parent) + 1];+ parent = outer;+ }++ const copies: Entity[] = [];+ for (const tree of trees) {+ copies.push(...this.insertElement(parent, () => renderAuthored(tree), anchor));+ }++ if (copies.length) this.select(copies);+ return copies;+ }++ /**+ * The tops of the subtrees `entities` span: those the file can address,+ * minus any that sit under another of them, in the given order.+ */+ private subtreeRoots(entities: Entity | Entity[]): Entity[] {+ const wanted = new Set(+ (Array.isArray(entities) ? entities : [entities]).filter(+ (entity) => entity.isAlive() && !entity.has(Stage) && !!entity.get(Source)?.value,+ ),+ );+ return [...wanted].filter((entity) => {+ for (let parent = getParentEntity(entity); parent; parent = getParentEntity(parent)) {+ if (wanted.has(parent)) return false;+ }+ return true;+ });+ }++ /**+ * `entity`'s subtree as a project would author a copy of it: `selected`+ * goes (the copy is selected on its own terms) and so does `active` (one+ * entity holds it).+ */+ private spell(entity: Entity): AuthoredTree | undefined {+ const tree = authoredTree(this.world, entity);+ if (!tree) return undefined;+ delete tree.props.selected;+ delete tree.props.active;+ return tree;+ }+/*** Moves `entity` under `parent`, in front of `anchor` or last, and reports* it so the element moves in the file too. The move goes through thediff --git a/apps/web/src/engine/input/shortcuts.ts b/apps/web/src/engine/input/shortcuts.tsindex 02d29e0d..780cbc1d 100644--- a/apps/web/src/engine/input/shortcuts.ts+++ b/apps/web/src/engine/input/shortcuts.ts@@ -9,7 +9,7 @@* pressed, matches what is held against the table below and runs the action.*/-import { getSelection, Position, Selected } from '@diffusionstudio/runtime';+import { getActiveEntity, getEntityChildren, getParentEntity, getSelection, isGroupLike, Position, Selected } from '@diffusionstudio/runtime';import { getDocumentEditor } from '../editor';import { Keys } from '../traits';@@ -43,6 +43,41 @@ export function duplicateSelection(world: World): void {}}+export function copySelection(world: World): void {+ const selected = [...world.query(Selected)];++ if (selected.length) {+ getDocumentEditor(world).copy(selected);+ }+}++/**+ * Pastes where the selection points: into a selected container (a scene or+ * group, on top of its children), on top of a selected leaf in that leaf's+ * parent, or, with nothing selected, into the active scene. The editor keeps+ * a paste out of the sequence it was copied from.+ */+export function pasteSelection(world: World): void {+ const editor = getDocumentEditor(world);+ const [selected] = world.query(Selected);++ if (selected === undefined) {+ const active = getActiveEntity(world);+ if (active) editor.paste(active);+ return;+ }++ if (isGroupLike(selected)) {+ editor.paste(selected);+ return;+ }++ const parent = getParentEntity(selected);+ if (parent === null) return;+ const siblings = getEntityChildren(world, parent);+ editor.paste(parent, siblings[siblings.indexOf(selected) + 1]);+}+const NUDGE = 1;const NUDGE_FAST = 10;@@ -68,6 +103,8 @@ const SHORTCUTS: readonly Shortcut[] = [{ key: 'backspace', action: deleteSelection },{ key: 'delete', action: deleteSelection },{ key: 'd', mod: true, action: duplicateSelection },+ { key: 'c', mod: true, action: copySelection },+ { key: 'v', mod: true, action: pasteSelection },{ key: 'arrowleft', action: nudge(-NUDGE, 0) },{ key: 'arrowright', action: nudge(NUDGE, 0) },{ key: 'arrowup', action: nudge(0, -NUDGE) },diff --git a/packages/runtime/MIGRATION.md b/packages/runtime/MIGRATION.mdindex 6da61f37..f0e9db36 100644--- a/packages/runtime/MIGRATION.md+++ b/packages/runtime/MIGRATION.md@@ -139,7 +139,7 @@ apps/web now depends on `@diffusionstudio/runtime` and `@diffusionstudio/koota-s**`<group>` and `<sequence>` are hosted.** A group is `Group` + `Position` and no `Size` (its box is the union of its children, resolved by `computeGroupBounds`; `resizeEntity` already drops `Size` on groups, so an authored `width`/`height` is a no-op). A sequence is just `Sequential`: the runtime's onAdd observer adds `Group` and strips the spatial traits, and the document refuses to write `x`/`y`/`offsetX`/`offsetY`/`rotation` on a `Sequential` entity afterwards, since the observer only strips once. Both take `name`, `selected`, the four time props, and `fill`; everything else falls through to the generic prop handling. Note the transform system computes a group's bounds from its children's local matrices as of the previous pass, so a freshly mounted group is one tick behind (same as bitecs; `groupSelection` refreshes children explicitly).- **Duplicate (cmd+d).** `DocumentEditor.duplicate(entities)` copies the tops of the selected subtrees: the reconciler's `authoredTree(world, entity)` reads each back as JSX vocabulary (tag, props, text, authored children; runtime sub-entities are left out and come back with the recipe) and `renderAuthored(tree)` rebuilds host nodes from it inside `insertElement`'s thunk, so a copy is a first-class insert (pending sources, nested inserts naming their pending parent, `before` set) with the same props and parent as its source, anchored at the source's next sibling so it draws on top. A source inside a sequence would collide with itself, so the copy goes to the nearest non-`Sequential` ancestor, right after the sequence it left (a sequence has no spatial identity or time of its own, so the same props put it in the same place). `selected`/`active` are not copied; the selection moves to the copies. `duplicateSelection` in `input/shortcuts.ts` binds it to mod+d.+ **Duplicate (cmd+d).** `DocumentEditor.duplicate(entities)` copies the tops of the selected subtrees: the reconciler's `authoredTree(world, entity)` reads each back as JSX vocabulary (tag, props, text, authored children; runtime sub-entities are left out and come back with the recipe) and `renderAuthored(tree)` rebuilds host nodes from it inside `insertElement`'s thunk, so a copy is a first-class insert (pending sources, nested inserts naming their pending parent, `before` set) with the same props and parent as its source, anchored at the source's next sibling so it draws on top. A source inside a sequence would collide with itself, so the copy goes to the nearest non-`Sequential` ancestor, right after the sequence it left (a sequence has no spatial identity or time of its own, so the same props put it in the same place). `selected`/`active` are not copied; the selection moves to the copies. `duplicateSelection` in `input/shortcuts.ts` binds it to mod+d. **Copy/paste (mod+c / mod+v)** reuse the same pieces: `editor.copy(entities)` keeps the spelled trees plus the stamp of the parent they came from in an editor-held clipboard (in-app only, no system clipboard: the shortcut system runs per frame, outside any user-gesture handler), and `editor.paste(parent, anchor?)` inserts them there, moving the selection to the copies. `pasteSelection` picks the target: a selected scene/group pastes inside it (appended, on top), a selected leaf pastes on top of it in its parent, no selection pastes into the active scene. Pasting into the sequence the trees were copied out of (by stamp) escapes to that sequence's parent, right after it, as duplicate does; a different sequence takes the paste as is.**Selection is a document property.** `selected?: boolean` joined `PatchProps` (picked into `CommonProps` and `SceneProps`, listed in `PATCH_PROP_KEYS`), for the same reason `<stage camera>` and `<scene x y>` exist: the source is the document, so a click on the canvas has nowhere else to be written to, and it means the selection survives the unmount/remount every recompile does. `RuntimeDocument.setProperty('selected')` adds the runtime's `Selected` trait for `true` and removes it for anything else (a bare attribute, a reactive prop going undefined; the stage is never selectable). The editor direction is `DocumentEditor.select(entities, { extend? })` / `deselect` / `clearSelection` (`apps/web/src/engine/editor.ts`): they write the trait and report a `selected` prop edit per entity that changed, `false` for the ones deselected. Selection surfaces go through these rather than touching `Selected` directly (DrawOverlay and SceneInitOverlay do), so nothing else has to know it is a source prop; not an observer on the trait, because a mount adding `Selected` from the file, or an unmount destroying selected entities, must not report as edits. The desktop `setProp` writes `false` as the attribute's absence (`attribute.remove()`), so deselection never leaves `selected={false}` behind, and the same now holds for any boolean prop (`muted`). Not carried over: the bitecs `selectStage/Parent/ChildEntities` helpers and the input system's click/marquee selection, which are still on the old world.