Skip to content

The VS Code of video editing, built for agents.

TypeScript

Enhance edit history functionality and input handling

konstantin-paulus918740ed8ac2
diff --git a/apps/web/src/components/sidebar-left/project-menu/edit-menu.tsx b/apps/web/src/components/sidebar-left/project-menu/edit-menu.tsx
index 67fc9164..c4c6970a 100644
--- a/apps/web/src/components/sidebar-left/project-menu/edit-menu.tsx
+++ b/apps/web/src/components/sidebar-left/project-menu/edit-menu.tsx
@@ -13,6 +13,7 @@ import {
copySelection,
deleteSelection,
duplicateSelection,
+ getEditHistory,
pasteSelection,
selectAll,
selectChildren,
@@ -25,17 +26,18 @@ import {
export function EditMenu() {
const world = useWorld();
const editor = useEditor();
+ const history = getEditHistory(world);
const { nodes } = useSelection();
const hasSelection = () => nodes().length > 0;
return (
<>
<DropdownMenuGroup>
- <DropdownMenuItem disabled>
+ <DropdownMenuItem disabled={!history.canUndo()} onSelect={() => history.undo()}>
Undo
<DropdownMenuShortcut>⌘Z</DropdownMenuShortcut>
</DropdownMenuItem>
- <DropdownMenuItem disabled>
+ <DropdownMenuItem disabled={!history.canRedo()} onSelect={() => history.redo()}>
Redo
<DropdownMenuShortcut>⇧⌘Z</DropdownMenuShortcut>
</DropdownMenuItem>
diff --git a/apps/web/src/engine/create-engine.ts b/apps/web/src/engine/create-engine.ts
index 30abafe6..d431ea90 100644
--- a/apps/web/src/engine/create-engine.ts
+++ b/apps/web/src/engine/create-engine.ts
@@ -5,7 +5,7 @@
import { assetSystem, renderSystem, transformSystem, playbackSystem, motionSystem, AudioEngine, createRuntimeWorld, Geometry, Mode, RenderSurface, Time, ChildOf, syncInteractiveState } from '@diffusionstudio/runtime';
import { hudSystem } from './hud';
import { createSignal, type Accessor, type Setter } from 'solid-js';
-import { AssetSelection, Hud, Keys, Pointer, PointerEvents, ProjectConfig, SnapLines } from './traits';
+import { AssetSelection, Hud, Keys, MODIFIER_KEYS, Pointer, PointerEvents, ProjectConfig, SnapLines } from './traits';
import { inputSystem } from './input/input-system';
import { clearClipFrames, clearClipPeaks, clearMedia, clearPeaks, timelineSystem, TimelineSurface } from './timeline';
import { shortcutSystem } from './input/shortcuts';
@@ -142,9 +142,15 @@ class Engine {
keys.held.delete(key);
keys.lifted.add(key);
- if (isMod) {
- keys.held.delete('mod');
- keys.lifted.add('mod');
+
+ if (!isMod) return;
+
+ keys.held.delete('mod');
+ keys.lifted.add('mod');
+
+ for (const stale of [...keys.held]) {
+ // macOS never delivers the key-up of a key released while ⌘ is held
+ if (!MODIFIER_KEYS.has(stale)) keys.held.delete(stale);
}
};
diff --git a/apps/web/src/engine/editor.ts b/apps/web/src/engine/editor.ts
index 88b3cca6..577dddb2 100644
--- a/apps/web/src/engine/editor.ts
+++ b/apps/web/src/engine/editor.ts
@@ -10,7 +10,7 @@
* where the commands live.
*/
-import { Active, Chars, Computed, End, FrameRate, framesToSeconds, getActiveEntity, getEntityChildren, getEntityTree, getIntrinsicPaint, getParentEntity, getTimelineOrigin, isText, Loop, PaintType, Selected, Sequential, setActive, Size, Source, Stage, Start } from '@diffusionstudio/runtime';
+import { Active, Background, Chars, colorToHex, Computed, DEFAULT_BACKGROUND, End, FrameRate, framesToSeconds, getActiveEntity, getEntityChildren, getEntityTree, getIntrinsicPaint, getParentEntity, getTimelineOrigin, isText, Loop, PaintType, Selected, Sequential, setActive, Size, Source, Stage, Start } from '@diffusionstudio/runtime';
import { isAssetRef, isPropValue, serializeAssetRef, SOURCE_ATTR } from '@diffusionstudio/jsx';
import { createRoot } from 'solid-js';
@@ -40,6 +40,14 @@ export interface PropEdit {
source: string;
name: string;
value: EditValue;
+ /**
+ * What the element authored for `name` before this edit — `false` for a
+ * prop it did not author, the same value an editor unsets one with. The
+ * history inverts the edit from this; the writer ignores it. Absent on an
+ * edit reported after the fact (`reportEdit` with no previous), which is
+ * therefore not invertible.
+ */
+ previous?: unknown;
}
/**
@@ -51,6 +59,8 @@ export interface TextEdit {
kind: 'text';
source: string;
value: string;
+ /** What the `<text>` said before this edit. Inverse info, as on `PropEdit`. */
+ previous?: string;
}
/**
@@ -84,16 +94,44 @@ export interface MoveEdit {
source: string;
parent: string;
before?: string;
+ /**
+ * Where the element came from: the parent it left and the sibling it stood
+ * in front of there, when the file names them. Inverse info, as on
+ * `PropEdit` — moving it back is these two spots swapped in.
+ */
+ fromParent?: string;
+ fromBefore?: string;
+}
+
+/**
+ * A deleted subtree as it stood the moment before it went, one node per
+ * authored element: the source it was stamped with, what a project would
+ * author it as (live values, `AssetRef`s included — this never crosses a
+ * wire), and its children in order. What an undo needs to put the subtree
+ * back, and to pair the old sources with the new ones the reinsert mints.
+ */
+export interface CapturedNode {
+ source: string;
+ tag: string;
+ props: Record<string, unknown>;
+ text?: string;
+ children: CapturedNode[];
}
/**
* An element the editor deleted, descendants included: they were its content
* in the file and went with it on the canvas, so only the top of a deleted
- * subtree is reported. The entity is already gone when this is.
+ * subtree is reported. The entity is already gone when this is — `parent`,
+ * `before` and `node` are its place and its content as they stood just
+ * before, captured for the history (the writer ignores them, as on
+ * `PropEdit`); absent when the subtree could not be captured whole.
*/
export interface RemoveEdit {
kind: 'remove';
source: string;
+ parent?: string;
+ before?: string;
+ node?: CapturedNode;
}
/**
@@ -166,6 +204,48 @@ function wireProps(props: Record<string, unknown>): Record<string, EditValue> {
return wired;
}
+/**
+ * `entity`'s subtree as a `CapturedNode`, or undefined for an entity that is
+ * not an addressable element (no authored element, or no source) — a child
+ * like that is simply left out, the way `authoredTree` leaves out derived
+ * sub-entities. `authoredElement` already copies the props, so the capture
+ * does not change under the caller afterwards.
+ */
+function captureNode(world: World, entity: Entity): CapturedNode | undefined {
+ const element = authoredElement(entity);
+ const source = entity.get(Source)?.value;
+ if (!element || !source) return undefined;
+
+ const children: CapturedNode[] = [];
+ for (const child of getEntityChildren(world, entity)) {
+ const node = captureNode(world, child);
+ if (node) children.push(node);
+ }
+
+ return {
+ source,
+ tag: element.tag,
+ props: element.props,
+ ...(element.text === undefined ? {} : { text: element.text }),
+ children,
+ };
+}
+
+/**
+ * The source of the next sibling after `entity` that the file can name — the
+ * `before` a reinsert at this spot would use — or undefined for none (last).
+ */
+function nextSourceAfter(world: World, entity: Entity): string | undefined {
+ const parent = getParentEntity(entity);
+ if (!parent) return undefined;
+ const siblings = getEntityChildren(world, parent);
+ for (const sibling of siblings.slice(siblings.indexOf(entity) + 1)) {
+ const source = sibling.get(Source)?.value;
+ if (source) return source;
+ }
+ return undefined;
+}
+
/**
* The props of a `<video>`/`<image>` that only mean something while the node
* plays media, dropped when the intrinsic paint is removed (see
@@ -188,7 +268,8 @@ interface Clipboard {
export class DocumentEditor {
private readonly world: World;
- private sink?: (edit: EntityEdit) => void;
+ private readonly sinks = new Set<(edit: EntityEdit) => void>();
+ private readonly renames = new Set<(ids: Record<string, string>) => void>();
private clipboard: Clipboard = { trees: [] };
public constructor(world: World) {
@@ -201,22 +282,45 @@ export class DocumentEditor {
}
/**
- * Listens for edits made through this editor. One sink at a time — a
- * second call replaces the first. Returns an unsubscribe.
+ * Listens for edits made through this editor. Every listener hears every
+ * edit — the writer takes them to the file, the history keeps them —
+ * in the order they subscribed. Returns an unsubscribe.
*/
public onEdit(sink: (edit: EntityEdit) => void): () => void {
- this.sink = sink;
+ this.sinks.add(sink);
return () => {
- if (this.sink === sink) {
- this.sink = undefined;
- }
+ this.sinks.delete(sink);
};
}
+ /**
+ * Listens for `restamp`: whoever holds sources of their own (the history)
+ * hears the same renames the entities get. Returns an unsubscribe.
+ */
+ public onRename(listener: (ids: Record<string, string>) => void): () => void {
+ this.renames.add(listener);
+ return () => {
+ this.renames.delete(listener);
+ };
+ }
+
+ private emit(edit: EntityEdit): void {
+ for (const sink of [...this.sinks]) sink(edit);
+ }
+
/** Writes a prop to the document and reports it. */
public editProperty(entity: Entity, name: string, value: PropValue): void {
- this.document.setProperty(this.document.node(entity), name, value);
- this.reportEdit(entity, name, value);
+ const node = this.document.node(entity);
+ let previous = node.props[name];
+ // The stage keeps no authored record (see RuntimeDocument.setProperty),
+ // so its one editable prop reads its previous value off the trait; the
+ // default spells as the attribute's absence, like any unset prop.
+ if (name === 'background' && previous === undefined) {
+ const background = entity.get(Background)?.value;
+ if (background !== undefined && background !== DEFAULT_BACKGROUND) previous = colorToHex(background);
+ }
+ this.document.setProperty(node, name, value);
+ this.reportEdit(entity, name, value, previous ?? false);
}
/**
@@ -225,12 +329,13 @@ export class DocumentEditor {
* something the others do not.
*/
public editText(entity: Entity, text: string): void {
+ const previous = entity.get(Chars)?.value ?? '';
this.document.setText(entity, text);
this.settle(entity);
const source = entity.get(Source)?.value;
if (source) {
- this.sink?.({ kind: 'text', source, value: text });
+ this.emit({ kind: 'text', source, value: text, previous });
}
}
@@ -238,14 +343,16 @@ export class DocumentEditor {
* Reports an edit whose change the editor already made itself. An entity a
* loop rendered is settled first (see `settle`): its element is every
* iteration's until the loop is unrolled, and the file hears about that
- * before it hears the value.
+ * before it hears the value. `previous` is the inverse for the history
+ * (see `PropEdit`); a caller that cannot say what the value was leaves it
+ * out, and the edit is not undoable.
*/
- public reportEdit(entity: Entity, name: string, value: PropValue): void {
+ public reportEdit(entity: Entity, name: string, value: PropValue, previous?: unknown): void {
this.settle(entity);
const source = entity.get(Source)?.value;
if (source) {
- this.sink?.({ kind: 'prop', source, name, value });
+ this.emit({ kind: 'prop', source, name, value, ...(previous === undefined ? {} : { previous }) });
}
}
@@ -382,7 +489,7 @@ export class DocumentEditor {
for (const member of getEntityTree(this.world, root)) member.remove(Loop);
}
- this.sink?.({ kind: 'unroll', source: first, loop, iterations });
+ this.emit({ kind: 'unroll', source: first, loop, iterations });
}
/**
@@ -464,7 +571,7 @@ export class DocumentEditor {
// has already folded into Chars; that is what the file gets.
const text = isText(entity) ? entity.get(Chars)?.value : undefined;
- this.sink?.({
+ this.emit({
kind: 'insert',
source: entity.get(Source)!.value,
parent: parentSource,
@@ -768,6 +875,10 @@ export class DocumentEditor {
const source = entity.get(Source)!.value;
const parentSource = parent.get(Source)!.value;
+ // Where it stands now, before the document moves it: the inverse move.
+ const fromParent = getParentEntity(entity)?.get(Source)?.value;
+ const fromBefore = nextSourceAfter(this.world, entity);
+
const wasActive = entity.has(Active);
try {
@@ -781,11 +892,13 @@ export class DocumentEditor {
// the honest answer, and where the document put it either way.
const before = anchor?.get(Source)?.value;
- this.sink?.({
+ this.emit({
kind: 'move',
source,
parent: parentSource,
...(before ? { before } : {}),
+ ...(fromParent ? { fromParent } : {}),
+ ...(fromBefore ? { fromBefore } : {}),
});
// Only a root holds the active tag (see world/observers), so a node
@@ -824,8 +937,20 @@ export class DocumentEditor {
// Cut from the file as one iteration's element, not the body's.
this.settle(entity);
const source = entity.get(Source)!.value;
+ // Its place and its content, the moment before they go. A doomed
+ // sibling can be the `before`: the undo reinserts in reverse order,
+ // so it is back by the time anything is placed against it.
+ const parentSource = getParentEntity(entity)?.get(Source)?.value;
+ const before = nextSourceAfter(this.world, entity);
+ const node = captureNode(this.world, entity);
document.removeNode(document.node(getParentEntity(entity) ?? document.stage.entity), document.node(entity));
- this.sink?.({ kind: 'remove', source });
+ this.emit({
+ kind: 'remove',
+ source,
+ ...(parentSource ? { parent: parentSource } : {}),
+ ...(before ? { before } : {}),
+ ...(node ? { node } : {}),
+ });
}
return roots;
@@ -841,6 +966,7 @@ export class DocumentEditor {
const next = ids[entity.get(Source)!.value];
if (next) entity.set(Source, { value: next });
}
+ for (const listener of [...this.renames]) listener(ids);
}
/**
diff --git a/apps/web/src/engine/history.ts b/apps/web/src/engine/history.ts
new file mode 100644
index 00000000..532f7ae0
--- /dev/null
+++ b/apps/web/src/engine/history.ts
@@ -0,0 +1,575 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Undo and redo for the mounted project. The history is a listener on the
+ * one funnel every mutation already goes through: it keeps the edits the
+ * `DocumentEditor` reports as invertible pairs, and an undo replays the
+ * inverses through the same editor commands the edit was made with — so the
+ * canvas changes the way any edit changes it, and the file hears about it
+ * through the same writer. Nothing here knows about a disk, or a second way
+ * to change anything.
+ *
+ * Everything is addressed by `Source` stamp, never by entity: entities die
+ * on remount, stamps survive it. When an undo has to put an element back
+ * (or a redo insert one again), the reinsert mints fresh pending sources —
+ * the history pairs them with the ones it recorded and rewrites itself, the
+ * same rename it hears from `restamp` when a write answers with real names.
+ *
+ * The history is cleared whenever a bundle is (re)mounted: a mount comes
+ * from the file, and edits recorded against a document that is gone cannot
+ * be replayed against the one that replaced it.
+ */
+
+import { Source, getEntityChildren } from '@diffusionstudio/runtime';
+import { authoredElement, renderAuthored } from '@diffusionstudio/reconciler';
+import { createSignal } from 'solid-js';
+
+import { getDocumentEditor } from './editor';
+
+import type { AuthoredTree } from '@diffusionstudio/reconciler';
+import type { PropValue } from '@diffusionstudio/jsx';
+import type { Entity, World } from 'koota';
+import type { CapturedNode, DocumentEditor, EntityEdit } from './editor';
+
+/**
+ * Props that are pointing and viewing rather than composition: undoing them
+ * is not what anyone means by undo, so they pass through to the file without
+ * entering the history. `error` is the runtime speaking (see source-errors),
+ * not the user.
+ */
+const EXCLUDED_PROPS: ReadonlySet<string> = new Set(['selected', 'active', 'camera', 'expanded', 'clipHeight', 'error']);
+
+/**
+ * How long after one step a same-shaped step still merges into it. Edits
+ * that arrive through the DOM rather than a canvas gesture — an inspector
+ * slider, repeated nudges — come as bursts of tiny transactions; within
+ * this window a repeat of the same props reads as one continuing adjustment.
+ */
+const COALESCE_WINDOW = 600;
+
+/** How many steps back the history keeps; beyond it, the oldest fall off. */
+const MAX_TRANSACTIONS = 100;
+
+/**
+ * One recorded edit with what it takes to play it in either direction. An
+ * insert's and a remove's `node` is the element as captured at the moment it
+ * existed (see `CapturedNode`); `parent`/`before` are its place. A move's
+ * two ends are both spelled out. All sources, everywhere, are rewritten as
+ * renames come in.
+ */
+interface PropOp {
+ kind: 'prop';
+ source: string;
+ name: string;
+ before: unknown;
+ after: unknown;
+}
+
+interface TextOp {
+ kind: 'text';
+ source: string;
+ before: string;
+ after: string;
+}
+
+interface InsertOp {
+ kind: 'insert';
+ parent: string;
+ before?: string;
+ node: CapturedNode;
+}
+
+interface RemoveOp {
+ kind: 'remove';
+ parent: string;
+ before?: string;
+ node: CapturedNode;
+}
+
+interface MoveOp {
+ kind: 'move';
+ source: string;
+ fromParent?: string;
+ fromBefore?: string;
+ toParent: string;
+ toBefore?: string;
+}
+
+type HistoryOp = PropOp | TextOp | InsertOp | RemoveOp | MoveOp;
+
+/**
+ * One undo step: the ops of one gesture, or of one synchronous burst of
+ * edits (a shortcut, a compound command, an inspector change). `broken`
+ * marks a step holding an edit that could not be captured whole — replaying
+ * around it would lie, so committing it clears the history instead.
+ */
+interface Transaction {
+ ops: HistoryOp[];
+ gesture: boolean;
+ committedAt: number;
+ broken?: boolean;
+}
+
+export class EditHistory {
+ private readonly world: World;
+ private readonly editor: DocumentEditor;
+
+ private undos: Transaction[] = [];
+ private redos: Transaction[] = [];
+ /** The transaction edits are landing in right now, not yet a step. */
+ private open: Transaction | null = null;
+ /** The transaction being replayed right now: renames reach it too. */
+ private replaying: Transaction | null = null;
+ private gesture = false;
+ private scheduled = false;
+ private applying = false;
+
+ /** Bumped on every change, so the menu's disabled states stay honest. */
+ private readonly changed: () => void;
+ private readonly version: () => number;
+
+ public constructor(world: World) {
+ this.world = world;
+ this.editor = getDocumentEditor(world);
+ this.editor.onEdit((edit) => this.record(edit));
+ this.editor.onRename((ids) => this.rename(ids));
+
+ const [version, setVersion] = createSignal(0);
+ this.version = version;
+ this.changed = () => setVersion((current) => current + 1);
+ }
+
+ /** Whether there is a step to undo. Reactive under a Solid computation. */
+ public canUndo(): boolean {
+ this.version();
+ return this.undos.length > 0 || (this.open?.ops.length ?? 0) > 0;
+ }
+
+ /** Whether there is a step to redo. Reactive under a Solid computation. */
+ public canRedo(): boolean {
+ this.version();
+ return this.redos.length > 0;
+ }
+
+ /**
+ * Starts over, for a fresh mount: what was recorded against the previous
+ * document cannot be replayed against this one.
+ */
+ public reset(): void {
+ this.undos = [];
+ this.redos = [];
+ this.open = null;
+ this.gesture = false;
+ this.changed();
+ }
+
+ /**
+ * Brackets a pointer hold: every edit from press to release — however
+ * many frames a drag writes — is one step. A press while a burst is
+ * still open commits it first, so the gesture starts on its own step.
+ */
+ public beginGesture(): void {
+ if (this.open) this.commit();
+ this.gesture = true;
+ }
+
+ public endGesture(): void {
+ if (!this.gesture) return;
+ this.gesture = false;
+ if (this.open) this.commit();
+ }
+
+ /** Takes back the last step, and hands it to redo. */
+ public undo(): void {
+ if (this.open) this.commit();
+ const transaction = this.undos.pop();
+ if (!transaction) return;
+
+ this.replay(transaction, [...transaction.ops].reverse(), (op) => this.revert(op));
+ this.redos.push(transaction);
+ this.changed();
+ }
+
+ /** Plays the last undone step again, and hands it back to undo. */
+ public redo(): void {
+ if (this.open) this.commit();
+ const transaction = this.redos.pop();
+ if (!transaction) return;
+
+ this.replay(transaction, transaction.ops, (op) => this.apply(op));
+ this.undos.push(transaction);
+ this.changed();
+ }
+
+ /**
+ * Runs one direction of a step through the editor. `applying` keeps the
+ * recorder from hearing the replay as new edits; the writer hears it like
+ * any other change, which is the point. The transaction is held where
+ * renames can reach it: a reinsert in the middle of it renames sources
+ * its own later ops refer to.
+ */
+ private replay(transaction: Transaction, ops: HistoryOp[], step: (op: HistoryOp) => void): void {
+ this.applying = true;
+ this.replaying = transaction;
+ try {
+ for (const op of ops) step(op);
+ } finally {
+ this.applying = false;
+ this.replaying = null;
+ }
+ }
+
+ /** ---- Recording ---- */
+
+ private record(edit: EntityEdit): void {
+ if (this.applying) return;
+
+ switch (edit.kind) {
+ // An unroll renders exactly what the loop rendered: nothing to
+ // invert. The edits that follow it address the settled copies.
+ case 'unroll':
+ return;
+
+ case 'prop': {
+ if (EXCLUDED_PROPS.has(edit.name)) return;
+ // No inverse reported (see `reportEdit`): not undoable, and a
+ // step pretending otherwise would restore the wrong value.
+ if (!('previous' in edit)) return;
+ const transaction = this.ensureOpen();
+ // A drag writes the same prop every frame; one op, sliding.
+ const existing = transaction.ops.find(
+ (op): op is PropOp => op.kind === 'prop' && op.source === edit.source && op.name === edit.name,
+ );
+ if (existing) {
+ existing.after = edit.value;
+ return;
+ }
+ transaction.ops.push({ kind: 'prop', source: edit.source, name: edit.name, before: edit.previous, after: edit.value });
+ return;
+ }
+
+ case 'text': {
+ const transaction = this.ensureOpen();
+ const existing = transaction.ops.find(
+ (op): op is TextOp => op.kind === 'text' && op.source === edit.source,
+ );
+ if (existing) {
+ existing.after = edit.value;
+ return;
+ }
+ transaction.ops.push({ kind: 'text', source: edit.source, before: edit.previous ?? '', after: edit.value });
+ return;
+ }
+
+ case 'insert': {
+ const transaction = this.ensureOpen();
+ // The element as it stands, live values included, rather than
+ // the wire form the edit carries: a redo re-renders it the way
+ // `duplicate` renders a copy. Children arrive as inserts of
+ // their own (parents first), so the node holds none.
+ const entity = this.resolve(edit.source);
+ const element = entity ? authoredElement(entity) : undefined;
+ transaction.ops.push({
+ kind: 'insert',
+ parent: edit.parent,
+ ...(edit.before ? { before: edit.before } : {}),
+ node: {
+ source: edit.source,
+ tag: edit.tag,
+ props: element ? element.props : { ...edit.props },
+ ...(edit.text === undefined ? {} : { text: edit.text }),
+ children: [],
+ },
+ });
+ return;
+ }
+
+ case 'move': {
+ const transaction = this.ensureOpen();
+ transaction.ops.push({
+ kind: 'move',
+ source: edit.source,
+ toParent: edit.parent,
+ ...(edit.before ? { toBefore: edit.before } : {}),
+ ...(edit.fromParent ? { fromParent: edit.fromParent } : {}),
+ ...(edit.fromBefore ? { fromBefore: edit.fromBefore } : {}),
+ });
+ return;
+ }
+
+ case 'remove': {
+ const transaction = this.ensureOpen();
+ if (!edit.parent || !edit.node) {
+ // Gone without a capture: nothing can put it back, and any
+ // older step referring into it would replay wrong.
+ transaction.broken = true;
+ return;
+ }
+ transaction.ops.push({
+ kind: 'remove',
+ parent: edit.parent,
+ ...(edit.before ? { before: edit.before } : {}),
+ node: edit.node,
+ });
+ return;
+ }
+ }
+ }
+
+ /**
+ * The transaction edits are landing in, opened on the first of them. A
+ * burst outside a gesture commits on the microtask, so everything one
+ * event handler did — a shortcut over a whole selection, a compound
+ * command — is one step.
+ */
+ private ensureOpen(): Transaction {
+ if (!this.open) {
+ this.open = { ops: [], gesture: this.gesture, committedAt: 0 };
+ this.changed();
+ }
+ if (!this.gesture && !this.scheduled) {
+ this.scheduled = true;
+ queueMicrotask(() => {
+ this.scheduled = false;
+ // A gesture that began meanwhile owns the step now.
+ if (!this.gesture && this.open) this.commit();
+ });
+ }
+ return this.open;
+ }
+
+ private commit(): void {
+ const transaction = this.open;
+ this.open = null;
+ if (!transaction) return;
+
+ if (transaction.broken) {
+ // Better no history than a history that lies.
+ this.undos = [];
+ this.redos = [];
+ this.changed();
+ return;
+ }
+
+ if (transaction.ops.length === 0) return;
+
+ transaction.committedAt = performance.now();
+
+ const last = this.undos[this.undos.length - 1];
+ if (last && this.coalesces(last, transaction)) {
+ for (const op of transaction.ops as PropOp[]) {
+ const target = last.ops.find(
+ (candidate): candidate is PropOp =>
+ candidate.kind === 'prop' && candidate.source === op.source && candidate.name === op.name,
+ );
+ if (target) target.after = op.after;
+ }
+ last.committedAt = transaction.committedAt;
+ } else {
+ this.undos.push(transaction);
+ if (this.undos.length > MAX_TRANSACTIONS) this.undos.shift();
+ }
+
+ this.redos = [];
+ this.changed();
+ }
+
+ /**
+ * Whether `next` is `last` still going: both prop-only bursts (never
+ * gestures — two drags are two steps), the same props of the same
+ * elements, close enough in time. A slider writes this shape.
+ */
+ private coalesces(last: Transaction, next: Transaction): boolean {
+ if (last.gesture || next.gesture) return false;
+ if (next.committedAt - last.committedAt > COALESCE_WINDOW) return false;
+
+ const key = (op: PropOp): string => `${op.source}${op.name}`;
+ if (!last.ops.every((op) => op.kind === 'prop') || !next.ops.every((op) => op.kind === 'prop')) return false;
+ const lastKeys = new Set((last.ops as PropOp[]).map(key));
+ const nextKeys = new Set((next.ops as PropOp[]).map(key));
+ return lastKeys.size === nextKeys.size && [...nextKeys].every((entry) => lastKeys.has(entry));
+ }
+
+ /** ---- Replaying ---- */
+
+ private revert(op: HistoryOp): void {
+ switch (op.kind) {
+ case 'prop': {
+ const entity = this.resolve(op.source);
+ if (entity) this.editor.editProperty(entity, op.name, op.before as PropValue);
+ return;
+ }
+ case 'text': {
+ const entity = this.resolve(op.source);
+ if (entity) this.editor.editText(entity, op.before);
+ return;
+ }
+ case 'insert': {
+ const entity = this.resolve(op.node.source);
+ if (entity) this.editor.remove(entity);
+ return;
+ }
+ case 'remove': {
+ this.reinsert(op);
+ return;
+ }
+ case 'move': {
+ if (!op.fromParent) return;
+ const entity = this.resolve(op.source);
+ const parent = this.resolve(op.fromParent);
+ if (!entity || !parent) return;
+ const anchor = op.fromBefore === undefined ? undefined : this.resolve(op.fromBefore);
+ this.editor.reparent(entity, parent, anchor);
+ return;
+ }
+ }
+ }
+
+ private apply(op: HistoryOp): void {
+ switch (op.kind) {
+ case 'prop': {
+ const entity = this.resolve(op.source);
+ if (entity) this.editor.editProperty(entity, op.name, op.after as PropValue);
+ return;
+ }
+ case 'text': {
+ const entity = this.resolve(op.source);
+ if (entity) this.editor.editText(entity, op.after);
+ return;
+ }
+ case 'insert': {
+ this.reinsert(op);
+ return;
+ }
+ case 'remove': {
+ const entity = this.resolve(op.node.source);
+ if (entity) this.editor.remove(entity);
+ return;
+ }
+ case 'move': {
+ const entity = this.resolve(op.source);
+ const parent = this.resolve(op.toParent);
+ if (!entity || !parent) return;
+ const anchor = op.toBefore === undefined ? undefined : this.resolve(op.toBefore);
+ this.editor.reparent(entity, parent, anchor);
+ return;
+ }
+ }
+ }
+
+ /**
+ * Puts a captured element back where it was. The reinsert renders it the
+ * way a paste renders a copy, so the entities are real and the writer
+ * hears an insert like any other — under fresh pending sources, which
+ * the history immediately pairs with the recorded ones and renames
+ * itself by, so every other step naming the old sources now names the
+ * reborn element. An anchor that is not there anymore means last, the
+ * same answer the writer gives.
+ */
+ private reinsert(op: InsertOp | RemoveOp): void {
+ const parent = this.resolve(op.parent);
+ if (!parent) return;
+ const anchor = op.before === undefined ? undefined : this.resolve(op.before);
+
+ const [top] = this.editor.insertElement(parent, () => renderAuthored(toAuthored(op.node)), anchor);
+ if (!top) return;
+
+ const ids: Record<string, string> = {};
+ this.pair(op.node, top, ids);
+ this.rename(ids);
+ }
+
+ /**
+ * Pairs a captured subtree with the entities its reinsert produced, in
+ * authored order — the render is the capture replayed, so the shapes
+ * match position for position.
+ */
+ private pair(node: CapturedNode, entity: Entity, ids: Record<string, string>): void {
+ const source = entity.get(Source)?.value;
+ if (source && source !== node.source) ids[node.source] = source;
+
+ const children = getEntityChildren(this.world, entity).filter((child) => authoredElement(child) !== undefined);
+ node.children.forEach((child, index) => {
+ const live = children[index];
+ if (live) this.pair(child, live, ids);
+ });
+ }
+
+ /**
+ * Rewrites every source the history holds, wherever it appears — both
+ * stacks, the open transaction, and the step being replayed right now.
+ * Fed by `restamp` (a write answered with real names) and by `reinsert`
+ * (a reborn element got new ones).
+ */
+ private rename(ids: Record<string, string>): void {
+ if (Object.keys(ids).length === 0) return;
+ const next = (source: string): string => ids[source] ?? source;
+
+ const transactions = [
+ ...this.undos,
+ ...this.redos,
+ ...(this.open ? [this.open] : []),
+ ...(this.replaying ? [this.replaying] : []),
+ ];
+ for (const transaction of transactions) {
+ for (const op of transaction.ops) {
+ switch (op.kind) {
+ case 'prop':
+ case 'text':
+ op.source = next(op.source);
+ break;
+ case 'move':
+ op.source = next(op.source);
+ op.toParent = next(op.toParent);
+ if (op.toBefore !== undefined) op.toBefore = next(op.toBefore);
+ if (op.fromParent !== undefined) op.fromParent = next(op.fromParent);
+ if (op.fromBefore !== undefined) op.fromBefore = next(op.fromBefore);
+ break;
+ case 'insert':
+ case 'remove':
+ op.parent = next(op.parent);
+ if (op.before !== undefined) op.before = next(op.before);
+ renameNode(op.node, next);
+ break;
+ }
+ }
+ }
+ }
+
+ /** The living entity stamped with `source`, or undefined for none. */
+ private resolve(source: string): Entity | undefined {
+ for (const entity of this.world.query(Source)) {
+ if (entity.isAlive() && entity.get(Source)!.value === source) return entity;
+ }
+ return undefined;
+ }
+}
+
+/** A captured node as `renderAuthored` takes it. */
+function toAuthored(node: CapturedNode): AuthoredTree {
+ return {
+ tag: node.tag,
+ props: { ...node.props },
+ ...(node.text === undefined ? {} : { text: node.text }),
+ children: node.children.map(toAuthored),
+ };
+}
+
+function renameNode(node: CapturedNode, next: (source: string) => string): void {
+ node.source = next(node.source);
+ for (const child of node.children) renameNode(child, next);
+}
+
+const histories = new WeakMap<World, EditHistory>();
+
+/** The history for `world`, created on first use. Outlives mounts, like the editor; `reset` it per mount. */
+export function getEditHistory(world: World): EditHistory {
+ let history = histories.get(world);
+ if (!history) {
+ history = new EditHistory(world);
+ histories.set(world, history);
+ }
+ return history;
+}
diff --git a/apps/web/src/engine/index.ts b/apps/web/src/engine/index.ts
index 4f2b8edd..d4eb3e65 100644
--- a/apps/web/src/engine/index.ts
+++ b/apps/web/src/engine/index.ts
@@ -10,6 +10,7 @@ export * from './camera';
export * from './camera-controller';
export * from './hooks';
export * from './editor';
+export * from './history';
export * from './timing';
export * from './split';
export * from './overlap';
diff --git a/apps/web/src/engine/input/input-system.ts b/apps/web/src/engine/input/input-system.ts
index 7ab19750..92428f39 100644
--- a/apps/web/src/engine/input/input-system.ts
+++ b/apps/web/src/engine/input/input-system.ts
@@ -4,6 +4,7 @@
import { HitRegions, Tool, ToolType, Dragging, Hovering, isPointerInEntity, pointInQuad } from '@diffusionstudio/runtime';
+import { getEditHistory } from '../history';
import { Keys, Pointer, PointerEvents } from '../traits';
import { getToolCursor, updateCursor } from './cursor';
import { handleCanvasInteraction, handleGeometryInteraction } from './interactions';
@@ -68,6 +69,7 @@ export function inputSystem(world: World) {
const panning = world.get(Tool)?.value === ToolType.HAND || (world.get(Keys)?.held.has(' ') ?? false);
const queue = world.get(PointerEvents)?.queue ?? [];
const regions = world.get(HitRegions)?.list ?? [];
+ const history = getEditHistory(world);
for (const event of queue) {
world.set(Pointer, {
@@ -82,6 +84,12 @@ export function inputSystem(world: World) {
...(event.type === 'pointerup' && { phase: 'lifted' as const }),
});
+ // One pointer hold is one undo step, whatever the drag writes along
+ // the way. Bracketed before the panning skip: a release must close
+ // the gesture however the press has been reinterpreted since.
+ if (event.type === 'pointerdown' && event.button === 0) history.beginGesture();
+ if (event.type === 'pointerup') history.endGesture();
+
if (panning) continue;
// The other buttons belong to the camera (middle-drag pans) and to
diff --git a/apps/web/src/engine/input/shortcuts.ts b/apps/web/src/engine/input/shortcuts.ts
index efcc8223..5bcc380c 100644
--- a/apps/web/src/engine/input/shortcuts.ts
+++ b/apps/web/src/engine/input/shortcuts.ts
@@ -32,8 +32,9 @@ import { Not, Or } from 'koota';
import { zoomBy, zoomTo, zoomToFit, zoomToSelection } from '../camera';
import { getDocumentEditor } from '../editor';
+import { getEditHistory } from '../history';
import { splitAtPlayhead } from '../split';
-import { Keys, Pointer } from '../traits';
+import { Keys, MODIFIER_KEYS, Pointer } from '../traits';
import { editTransform } from './interactions';
import type { TransformWrite } from './interactions';
@@ -48,6 +49,14 @@ type Shortcut = {
/** The node kinds a shortcut selects, hides or seeks around. */
const NODES = Or(Geometry, Group, AdjustmentLayer);
+export function undoEdit(world: World): void {
+ getEditHistory(world).undo();
+}
+
+export function redoEdit(world: World): void {
+ getEditHistory(world).redo();
+}
+
export function deleteSelection(world: World): void {
const selected = [...world.query(Selected)];
@@ -372,6 +381,8 @@ function deselect(world: World): void {
}
const PRESSED_SHORTCUTS: readonly Shortcut[] = [
+ { keys: ['z', 'mod', '!shift'], action: undoEdit },
+ { keys: ['z', 'mod', 'shift'], action: redoEdit },
{ keys: ['backspace'], action: deleteSelection },
{ keys: ['delete'], action: deleteSelection },
{ keys: ['d', 'mod', '!shift'], action: duplicateSelection },
@@ -422,6 +433,11 @@ const LIFTED_SHORTCUTS: readonly Shortcut[] = [
* be held, and a '!' key has to be up. The key that moved is matched
* against `moved` rather than `held` because a lift takes it out of `held`,
* and a tap shorter than a frame is over before the frame runs.
+ *
+ * Only a non-modifier can be the trigger: ⌘Z means Z pressed under ⌘, not ⌘
+ * pressed over a Z — and `held` can hold a stale letter, since macOS drops
+ * the key-up of a key released while ⌘ is down, so a fresh ⌘ press must not
+ * complete a shortcut on its own.
*/
function matches(shortcut: Shortcut, moved: Set<string>, held: Set<string>): boolean {
let triggered = false;
@@ -429,7 +445,7 @@ function matches(shortcut: Shortcut, moved: Set<string>, held: Set<string>): boo
for (const key of shortcut.keys) {
if (key.startsWith('!')) {
if (held.has(key.slice(1))) return false;
- } else if (moved.has(key)) {
+ } else if (moved.has(key) && !MODIFIER_KEYS.has(key)) {
triggered = true;
} else if (!held.has(key)) {
return false;
diff --git a/apps/web/src/engine/traits.ts b/apps/web/src/engine/traits.ts
index 92a341c9..fc7bcef8 100644
--- a/apps/web/src/engine/traits.ts
+++ b/apps/web/src/engine/traits.ts
@@ -49,6 +49,15 @@ export const Keys = trait({
lifted: () => new Set<string>(),
});
+/**
+ * The keys of `Keys` that are modifiers, `mod` (the ⌘/Ctrl alias) included.
+ * They qualify a shortcut but never trigger one, and they are the only keys
+ * whose key-ups can be trusted: macOS does not deliver the key-up of a key
+ * released while ⌘ is held, so anything else still in `held` when the
+ * modifier goes up may be long gone.
+ */
+export const MODIFIER_KEYS: ReadonlySet<string> = new Set(['mod', 'meta', 'control', 'shift', 'alt']);
+
export type SnapLine = { from: Point; to: Point };
/** Snap guides for the gesture in flight; the HUD draws and empties them. */
diff --git a/apps/web/src/pages/editor.tsx b/apps/web/src/pages/editor.tsx
index c4a9b47d..3c16d77c 100644
--- a/apps/web/src/pages/editor.tsx
+++ b/apps/web/src/pages/editor.tsx
@@ -15,6 +15,7 @@ import { toast } from 'somoto';
import { useWorld } from '@diffusionstudio/koota-solid';
import { mount } from '@diffusionstudio/reconciler';
import { getDocumentEditor } from '@/engine/editor';
+import { getEditHistory } from '@/engine/history';
import { attachLibrary, isLibraryFile } from '@/engine/library';
import { attachAi } from '@/utils/gen-ai';
import { attachProjectConfig, isProjectConfigFile } from '@/engine/project-config';
@@ -84,6 +85,9 @@ export function EditorPage() {
writer = createEditWriter(dir, world);
const editor = getDocumentEditor(world);
unlisten = editor.onEdit((edit) => writer?.push(edit));
+ // A mount comes from the file: edits recorded against the document it
+ // replaced cannot be replayed against this one.
+ getEditHistory(world).reset();
};
const loadProject = async (): Promise<void> => {