Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(details): copy/paste property + component values, reset-to-defaults

esengine32d59c962dc9
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 6ac8d95a7..fe302e115 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -647,18 +647,22 @@ export class SceneCommandsImpl {
});
}
+ // The default data for a component: builtins from the engine registry; user/script
+ // components from the schemas.json shape; an unknown-but-named component is empty.
+ private defaultDataFor(compName: string): Record<string, unknown> {
+ const def = componentByName(compName);
+ return def
+ ? structuredClone(componentDefaults(def))
+ : structuredClone(userSchema(compName)?.default ?? {});
+ }
+
/** Add a component (with its registered/schema defaults) to an entity. Undoable. */
// Apply an add to the model and return its undo op, or null if it's a no-op
// (entity gone / component already present). Shared by the single + batch paths.
private addComponentOp(sourceId: EntityId, compName: string): UndoOp | null {
const entity = this.model.entityBySource(sourceId);
if (!entity || entity.components.some((c) => c.type === compName)) return null;
- const def = componentByName(compName);
- // Builtins default from the engine registry; user/script components from the
- // schemas.json shape; an unknown-but-named component starts empty.
- const data = def
- ? structuredClone(componentDefaults(def))
- : structuredClone(userSchema(compName)?.default ?? {});
+ const data = this.defaultDataFor(compName);
this.model.setComponent(sourceId, compName, data);
return {
forward: () => this.model.setComponent(sourceId, compName, structuredClone(data)),
@@ -666,6 +670,19 @@ export class SceneCommandsImpl {
};
}
+ // Replace an existing component's data wholesale (paste-values / reset). Null if
+ // the entity doesn't have the component (paste/reset only touch what's present).
+ private replaceComponentOp(sourceId: EntityId, compName: string, newData: Record<string, unknown>): UndoOp | null {
+ const cur = this.model.entityBySource(sourceId)?.components.find((c) => c.type === compName);
+ if (!cur) return null;
+ const before = structuredClone(cur.data);
+ this.model.setComponent(sourceId, compName, structuredClone(newData));
+ return {
+ forward: () => this.model.setComponent(sourceId, compName, structuredClone(newData)),
+ reverse: () => this.model.setComponent(sourceId, compName, structuredClone(before)),
+ };
+ }
+
private removeComponentOp(sourceId: EntityId, compName: string): UndoOp | null {
if (compName === 'Transform' || compName === 'Name') return null; // protected
const comp = this.model.entityBySource(sourceId)?.components.find((c) => c.type === compName);
@@ -701,6 +718,26 @@ export class SceneCommandsImpl {
this.history.batch(`Remove ${prettyLabel(compName)}`, ops);
}
+ /**
+ * Paste a copied component's values onto every selected entity that has that
+ * component (the Details "Paste Values"). Wholesale data replacement, one undo
+ * step; entities without the component are skipped.
+ */
+ pasteComponentValuesMany(sourceIds: readonly EntityId[], compName: string, data: Record<string, unknown>): void {
+ const ops = sourceIds.map((id) => this.replaceComponentOp(id, compName, data)).filter((o): o is UndoOp => !!o);
+ this.history.batch(`Paste ${prettyLabel(compName)} Values`, ops);
+ }
+
+ /**
+ * Reset a component to its registered defaults on every selected entity that has
+ * it (the Details "Reset to Defaults"). One undo step.
+ */
+ resetComponentMany(sourceIds: readonly EntityId[], compName: string): void {
+ const defaults = this.defaultDataFor(compName);
+ const ops = sourceIds.map((id) => this.replaceComponentOp(id, compName, defaults)).filter((o): o is UndoOp => !!o);
+ this.history.batch(`Reset ${prettyLabel(compName)}`, ops);
+ }
+
/**
* Toggle an entity's editor visibility — a dedicated editor-only flag the
* reconciler folds into the render projection. Distinct from a component's
diff --git a/desktop/src/engine/inspectorClipboard.ts b/desktop/src/engine/inspectorClipboard.ts
new file mode 100644
index 000000000..146319bcb
--- /dev/null
+++ b/desktop/src/engine/inspectorClipboard.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file inspectorClipboard.ts
+ * @brief The Details panel's copy/paste buffer — one field value, or a whole
+ * component's values. A plain module holder (not the OS clipboard): the
+ * context menus read it when they open, so no subscription is needed. Paste
+ * is type/component-gated so a copied value only lands somewhere compatible.
+ */
+import type { InspectorFieldType, InspectorFieldValue } from '@/types';
+
+type ClipEntry =
+ | { kind: 'component'; comp: string; data: Record<string, unknown> }
+ | { kind: 'field'; comp: string; key: string; type: InspectorFieldType; value: InspectorFieldValue };
+
+let entry: ClipEntry | null = null;
+
+export const InspectorClipboard = {
+ copyComponent(comp: string, data: Record<string, unknown>): void {
+ entry = { kind: 'component', comp, data: structuredClone(data) };
+ },
+ copyField(comp: string, key: string, type: InspectorFieldType, value: InspectorFieldValue): void {
+ entry = { kind: 'field', comp, key, type, value: structuredClone(value) };
+ },
+ /** The buffered component data if it matches `comp`, else null (paste gate). */
+ componentData(comp: string): Record<string, unknown> | null {
+ return entry?.kind === 'component' && entry.comp === comp ? structuredClone(entry.data) : null;
+ },
+ /** The buffered field value if its type matches `type`, else null (paste gate). */
+ fieldValue(type: InspectorFieldType): InspectorFieldValue | null {
+ return entry?.kind === 'field' && entry.type === type ? structuredClone(entry.value) : null;
+ },
+};
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index fc93060cd..97c80a71f 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -10,6 +10,7 @@ import {
Code2,
Component as ComponentIcon,
Copy,
+ ClipboardPaste,
Filter,
FolderOpen,
Image as ImageIcon,
@@ -37,6 +38,7 @@ import { EngineHost } from '@/engine/EngineHost';
import { SceneStore } from '@/engine/SceneStore';
import { SceneQuery, buildEntityInfo, buildInspector } from '@/engine/SceneQuery';
import { SceneModel } from '@/engine/SceneModel';
+import { InspectorClipboard } from '@/engine/inspectorClipboard';
import { SceneCommands, toModelValue } from '@/engine/SceneCommands';
import { PlayInspect } from '@/engine/PlayInspect';
import type { SceneData } from 'esengine';
@@ -1134,8 +1136,30 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp
end();
};
+ // Right-click a property → Copy / Paste its value (the live "Game" inspector has no
+ // undoable write door, so it's disabled there).
+ const [fctx, setFctx] = useState<{ x: number; y: number } | null>(null);
+ const pasteValue = InspectorClipboard.fieldValue(field.type);
+ const doPaste = () => {
+ if (pasteValue == null) return;
+ begin();
+ apply(pasteValue as never);
+ end();
+ };
+
return (
- <div className={`prop${modified ? ' modified' : ''}${mixed ? ' mixed' : ''}`}>
+ <div
+ className={`prop${modified ? ' modified' : ''}${mixed ? ' mixed' : ''}`}
+ onContextMenu={
+ write
+ ? undefined
+ : (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setFctx({ x: e.clientX, y: e.clientY });
+ }
+ }
+ >
<span className={`prop-label${isScalar ? ' scrub' : ''}`} {...(isScalar ? labelScrub : {})}>
{field.label}
</span>
@@ -1149,6 +1173,27 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp
>
<RotateCcw size={11} strokeWidth={2} />
</button>
+ {fctx && (
+ <ContextMenu
+ x={fctx.x}
+ y={fctx.y}
+ onClose={() => setFctx(null)}
+ items={[
+ {
+ label: 'Copy',
+ icon: <Copy size={13} strokeWidth={1.9} />,
+ disabled: mixed,
+ onClick: () => InspectorClipboard.copyField(comp, field.key, field.type, field.value),
+ },
+ {
+ label: 'Paste',
+ icon: <ClipboardPaste size={13} strokeWidth={1.9} />,
+ disabled: pasteValue == null,
+ onClick: doPaste,
+ },
+ ]}
+ />
+ )}
</div>
);
}
@@ -1757,14 +1802,43 @@ function EditorDetails() {
<ContextMenu
x={compMenu.x}
y={compMenu.y}
- items={[
- {
- label: ids.length > 1 ? `Remove Component (${ids.length})` : 'Remove Component',
- danger: true,
- icon: <Trash2 size={13} strokeWidth={1.9} />,
- onClick: () => SceneCommands.removeComponentMany(ids, compMenu.comp),
- },
- ]}
+ items={(() => {
+ const comp = compMenu.comp;
+ const data = SceneModel.entityBySource(ids[0])?.components.find((c) => c.type === comp)?.data as
+ | Record<string, unknown>
+ | undefined;
+ const pasteData = InspectorClipboard.componentData(comp);
+ return [
+ {
+ label: 'Copy Values',
+ icon: <Copy size={13} strokeWidth={1.9} />,
+ disabled: !data,
+ onClick: () => {
+ if (data) InspectorClipboard.copyComponent(comp, data);
+ },
+ },
+ {
+ label: 'Paste Values',
+ icon: <ClipboardPaste size={13} strokeWidth={1.9} />,
+ disabled: !pasteData,
+ onClick: () => {
+ if (pasteData) SceneCommands.pasteComponentValuesMany(ids, comp, pasteData);
+ },
+ },
+ {
+ label: 'Reset to Defaults',
+ icon: <RotateCcw size={13} strokeWidth={1.9} />,
+ onClick: () => SceneCommands.resetComponentMany(ids, comp),
+ },
+ { sep: true },
+ {
+ label: ids.length > 1 ? `Remove Component (${ids.length})` : 'Remove Component',
+ danger: true,
+ icon: <Trash2 size={13} strokeWidth={1.9} />,
+ onClick: () => SceneCommands.removeComponentMany(ids, comp),
+ },
+ ];
+ })()}
onClose={() => setCompMenu(null)}
/>
)}
diff --git a/desktop/tests/component-clipboard.test.ts b/desktop/tests/component-clipboard.test.ts
new file mode 100644
index 000000000..d79c03cbd
--- /dev/null
+++ b/desktop/tests/component-clipboard.test.ts
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file SceneCommands component-clipboard ops — Paste Values (wholesale replace on
+ * entities that have the component, skip the rest) and Reset to Defaults, each
+ * one undo step. Pure TS (model + history are real; no WASM).
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import type { SceneData } from 'esengine';
+import { SceneModelImpl } from '@/engine/SceneModel';
+import { EditorHistoryImpl } from '@/engine/EditorHistory';
+import { SceneCommandsImpl } from '@/engine/SceneCommands';
+
+const tf = () => ({ position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 } });
+
+function scene(): SceneData {
+ return {
+ version: '1.0',
+ name: 't',
+ entities: [
+ { id: 1, name: 'A', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: '@uuid:a', size: { x: 64, y: 64 } } }] },
+ { id: 2, name: 'B', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: '@uuid:b', size: { x: 8, y: 8 } } }] },
+ { id: 3, name: 'C', parent: null, children: [], components: [{ type: 'Transform', data: tf() }] },
+ ],
+ } as unknown as SceneData;
+}
+
+const sprite = (m: SceneModelImpl, id: number) =>
+ m.entityBySource(id)?.components.find((c) => c.type === 'Sprite')?.data as { texture?: unknown } | undefined;
+
+describe('SceneCommands component clipboard', () => {
+ let model: SceneModelImpl;
+ let history: EditorHistoryImpl;
+ let cmds: SceneCommandsImpl;
+
+ beforeEach(() => {
+ model = new SceneModelImpl();
+ history = new EditorHistoryImpl();
+ cmds = new SceneCommandsImpl(model, history);
+ model.adopt(scene(), new Map([[1, 101], [2, 102], [3, 103]]));
+ });
+
+ it('pastes values onto entities that have the component, skips those without, one undo step', () => {
+ const src = sprite(model, 1)!;
+ cmds.pasteComponentValuesMany([2, 3], 'Sprite', src as Record<string, unknown>);
+ expect(sprite(model, 2)).toEqual(src); // B replaced with A's values
+ expect(sprite(model, 3)).toBeUndefined(); // C has no Sprite → skipped
+
+ expect(history.canUndo()).toBe(true);
+ history.undo();
+ expect(sprite(model, 2)?.texture).toBe('@uuid:b'); // restored
+ expect(history.canUndo()).toBe(false); // exactly one batched step
+ });
+
+ it('does not alias the source — editing the pasted copy leaves the original intact', () => {
+ const src = sprite(model, 1)! as { texture: string };
+ cmds.pasteComponentValuesMany([2], 'Sprite', src as unknown as Record<string, unknown>);
+ cmds.setField(2, 'Sprite', 'texture', 'string', '@uuid:changed');
+ expect(sprite(model, 2)?.texture).toBe('@uuid:changed');
+ expect(sprite(model, 1)?.texture).toBe('@uuid:a'); // source untouched
+ });
+
+ it('resets a component to its registered defaults, undoably', () => {
+ expect(sprite(model, 1)?.texture).toBe('@uuid:a');
+ cmds.resetComponentMany([1], 'Sprite');
+ expect(sprite(model, 1)?.texture).not.toBe('@uuid:a'); // back to the Sprite default
+ history.undo();
+ expect(sprite(model, 1)?.texture).toBe('@uuid:a');
+ });
+});