The VS Code of video editing, built for agents.
TypeScript
Implement duplicate functionality in DocumentEditor and keyboard shortcuts
konstantin-paulusca39447b101f
diff --git a/apps/web/src/engine/editor.ts b/apps/web/src/engine/editor.tsindex 7fd57001..6f8343c9 100644--- a/apps/web/src/engine/editor.ts+++ b/apps/web/src/engine/editor.ts@@ -10,11 +10,11 @@* where the commands live.*/-import { Active, Chars, getActiveEntity, getEntityChildren, getEntityTree, getParentEntity, isText, Loop, Selected, setActive, Source, Stage } from '@diffusionstudio/runtime';+import { Active, Chars, getActiveEntity, getEntityChildren, getEntityTree, getParentEntity, isText, Loop, Selected, Sequential, setActive, Source, Stage } from '@diffusionstudio/runtime';import { isPropValue, SOURCE_ATTR } from '@diffusionstudio/jsx';import { createRoot } from 'solid-js';-import { authoredElement, getRuntimeDocument, insert, isSceneNode, withDocument } from '@diffusionstudio/reconciler';+import { authoredElement, authoredTree, getRuntimeDocument, insert, isSceneNode, renderAuthored, withDocument } from '@diffusionstudio/reconciler';import type { PropValue } from '@diffusionstudio/jsx';import type { Entity, World } from 'koota';@@ -399,6 +399,62 @@ export class DocumentEditor {return [...created.keys()].filter((entity) => !created.has(getParentEntity(entity)!));}+ /**+ * Copies `entities`, subtrees included, and reports the copies as inserts+ * so they land in the file too. A copy is spelled from what its source was+ * authored as (`authoredTree`), so it has the same props — the same+ * position — and sits in the same parent, right on top of its source+ * (inserted after it in order). Only the tops of the selected subtrees are+ * copied: a descendant of another one goes with it.+ *+ * The exception is a node inside a sequence: two clips at the same time+ * conflict there, so the copy goes to the nearest parent that is not a+ * sequence, on top of the sequence it came out of. A sequence has no+ * spatial identity and no time of its own, so the same props put the copy+ * where the source is.+ *+ * The selection moves to the copies (`selected` is not copied, nor is+ * `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);+ if (!tree) continue;+ delete tree.props.selected;+ delete tree.props.active;++ // Out of any sequence, on top of what it left.+ let below = source;+ let parent = getParentEntity(below);+ while (parent && parent.has(Sequential)) {+ below = parent;+ parent = getParentEntity(below);+ }+ if (!parent) continue;++ const siblings = getEntityChildren(this.world, parent);+ const anchor = siblings[siblings.indexOf(below) + 1];++ copies.push(...this.insertElement(parent, () => renderAuthored(tree), anchor));+ }++ if (copies.length) this.select(copies);+ return copies;+ }+/*** 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 c977cedc..02d29e0d 100644--- a/apps/web/src/engine/input/shortcuts.ts+++ b/apps/web/src/engine/input/shortcuts.ts@@ -35,6 +35,14 @@ export function deleteSelection(world: World): void {}};+export function duplicateSelection(world: World): void {+ const selected = [...world.query(Selected)];++ if (selected.length) {+ getDocumentEditor(world).duplicate(selected);+ }+}+const NUDGE = 1;const NUDGE_FAST = 10;@@ -59,6 +67,7 @@ const nudge = (dx: number, dy: number) => (world: World): void => nudgeSelectionconst SHORTCUTS: readonly Shortcut[] = [{ key: 'backspace', action: deleteSelection },{ key: 'delete', action: deleteSelection },+ { key: 'd', mod: true, action: duplicateSelection },{ key: 'arrowleft', action: nudge(-NUDGE, 0) },{ key: 'arrowright', action: nudge(NUDGE, 0) },{ key: 'arrowup', action: nudge(0, -NUDGE) },diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.tsindex 91303df7..88b3bd7c 100644--- a/packages/reconciler/src/document.ts+++ b/packages/reconciler/src/document.ts@@ -117,6 +117,30 @@ export function authoredElement(entity: Entity): AuthoredElement | undefined {return { tag: authored.tag, props: { ...authored.props }, ...(text ? { text } : {}) };}+/** An authored element with the authored elements under it, in order. */+export interface AuthoredTree extends AuthoredElement {+ children: AuthoredTree[];+}++/**+ * The subtree `entity` was rendered from, as a project would author it:+ * `authoredElement` of it and, recursively, of every child of its that a+ * document created. Sub-entities the runtime derives (a recipe's paints) are+ * not elements and are left out; they come back with the recipe.+ */+export function authoredTree(world: World, entity: Entity): AuthoredTree | undefined {+ const element = authoredElement(entity);+ if (element === undefined) return undefined;++ const children: AuthoredTree[] = [];+ for (const child of getEntityChildren(world, entity)) {+ const tree = authoredTree(world, child);+ if (tree) children.push(tree);+ }++ return { ...element, children };+}+export function isSceneNode(node: HostNode): node is SceneNode {return 'entity' in node;}diff --git a/packages/reconciler/src/elements.ts b/packages/reconciler/src/elements.tsindex 631a1ee6..3c5bebf5 100644--- a/packages/reconciler/src/elements.ts+++ b/packages/reconciler/src/elements.ts@@ -14,9 +14,10 @@*/import { splitProps } from "solid-js";-import { createElement, spread, use } from "./renderer";+import { createElement, createTextNode, insertNode, setProp, spread, use } from "./renderer";import type { JSX as SolidJSX } from "solid-js";+import type { AuthoredTree } from "./document";import type {AudioProps,CaptionsProps,@@ -53,6 +54,27 @@ function hostElement<P extends object>(tag: string): (props: P) => SolidJSX.Elem};}+/**+ * Builds host nodes from an `AuthoredTree` (see `authoredTree`), the way a+ * project spelling those elements would: one element per node with its props+ * set and its text and children inserted, in order. Static — the values are+ * what the tree holds — and written into whatever document is active, so an+ * editor renders it inside `insertElement`'s thunk to duplicate a subtree.+ */+export function renderAuthored(tree: AuthoredTree): unknown {+ const node = createElement(tree.tag);+ for (const [name, value] of Object.entries(tree.props)) {+ setProp(node, name, value);+ }+ if (tree.text !== undefined) {+ insertNode(node, createTextNode(tree.text));+ }+ for (const child of tree.children) {+ insertNode(node, renderAuthored(child));+ }+ return node;+}+export const Scene = hostElement<SceneProps>("Scene");export const Group = hostElement<GroupProps>("Group");export const Rect = hostElement<RectProps>("Rect");diff --git a/packages/runtime/MIGRATION.md b/packages/runtime/MIGRATION.mdindex 6fbd48ca..6da61f37 100644--- a/packages/runtime/MIGRATION.md+++ b/packages/runtime/MIGRATION.md@@ -139,6 +139,8 @@ 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.+**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.**The active entity is a document property too.** `active?: boolean` in `PatchProps` (picked into `SceneProps` only for now; the scene restriction is a single assertion in `setActive` and goes when it goes), listed in `PATCH_PROP_KEYS`. The `ActiveScene` world trait is gone; `Active` is a tag on the entity, so it dies with the entity (no clearing in `removeNode`) and comes back from `<scene active>` on remount. Two invariants live in `world/observers.ts`, so they hold whichever path adds the tag: `onAdd(Active)` strips it from every other holder (last wins), and `onAdd(ChildOf('*'))` strips it when the new parent is not the stage (root only). The ChildOf half is what catches a nested `<rect active>` from a file, because Solid sets props before insertion while the entity is still a stage child; the cost is that such a rect first steals the tag and then loses it, so a file saying `active` on a scene and on something nested inside it ends with nothing active until the mount fallback below. `DocumentEditor.activate(entity | null)` is the editor route (trait via `setActive`, `active: false` reported for the one it left, `true` for the new one); overlays use it, the encoder calls `setActive` directly (headless, nothing to report), `useActiveScene()` reads `useQuery(Active)[0]`. `pages/editor.tsx` activates the first root scene through the editor after a mount that produced no active entity, so a project without one gets it written into the file and it sticks. A file naming two active scenes keeps both until the next `activate` cleans up; the document does not report edits.