Skip to content

The VS Code of video editing, built for agents.

TypeScript

Add @inspect variable support in editor and inspector

konstantin-paulusd9cc6b081952
diff --git a/apps/desktop/src/edit.ts b/apps/desktop/src/edit.ts
index bf0adb81..b878d6de 100644
--- a/apps/desktop/src/edit.ts
+++ b/apps/desktop/src/edit.ts
@@ -9,9 +9,9 @@ import { join } from "node:path";
import { IndentationText, Project, SyntaxKind } from "ts-morph";
-import { ID_ATTR, formatSource, isCompositionTag, isLoopTag, isSerializedAssetRef, parseSource } from "@diffusionstudio/jsx";
+import { ID_ATTR, INSPECT_TAG, formatSource, isCompositionTag, isLoopTag, isSerializedAssetRef, parseSource } from "@diffusionstudio/jsx";
-import type { PropValue, SerializedAssetRef } from "@diffusionstudio/jsx";
+import type { InspectValue, PropValue, SerializedAssetRef } from "@diffusionstudio/jsx";
import type {
ArrowFunction,
FunctionExpression,
@@ -121,7 +121,21 @@ export interface SourceUnroll {
iterations: SourceIteration[];
}
-export type SourceEdit = SourceSet | SourceInsert | SourceMove | SourceRemove | SourceUnroll;
+/**
+ * Overwrites the initializer of an `@inspect`-annotated top-level const (see
+ * @diffusionstudio/jsx's inspect). Addressed by file and variable name — a
+ * const's name is unique in its module, so no id is needed — and only written
+ * when the declaration still carries the annotation and holds a literal: an
+ * initializer someone rewrote into an expression is theirs again.
+ */
+export interface SourceVariable {
+ kind: "variable";
+ file: string;
+ name: string;
+ value: InspectValue;
+}
+
+export type SourceEdit = SourceSet | SourceInsert | SourceMove | SourceRemove | SourceUnroll | SourceVariable;
export interface WriteResult {
/** Sources that could not be written, as `id` or `id (prop)`. */
@@ -627,6 +641,10 @@ interface FileWrite {
unrolled: string[];
}
+/** How an edit is named in `WriteResult.skipped`: its source, or the variable's `file:name`. */
+export const editLabel = (edit: SourceEdit): string =>
+ edit.kind === "variable" ? formatSource(edit.file, edit.name) : edit.source;
+
/**
* The element a source names, resolved through the names this write has
* already handed out: an insert answers with a real source, and anything
@@ -779,10 +797,16 @@ class SourceWriter {
const fileOf = new Map<string, string>();
const byFile = new Map<string, SourceEdit[]>();
for (const edit of edits) {
- const address = edit.kind === "insert" ? edit.parent : edit.source;
- const file = parseSource(address)?.file ?? fileOf.get(address);
+ let file: string | undefined;
+ if (edit.kind === "variable") {
+ // A variable names its file itself; nothing about it is pending.
+ file = edit.file;
+ } else {
+ const address = edit.kind === "insert" ? edit.parent : edit.source;
+ file = parseSource(address)?.file ?? fileOf.get(address);
+ }
if (!file) {
- skipped.push(edit.source);
+ skipped.push(editLabel(edit));
continue;
}
if (edit.kind === "insert") fileOf.set(edit.source, file);
@@ -807,7 +831,7 @@ class SourceWriter {
// ts-morph will not vouch for is dropped rather than half written.
if (!written) {
this.discard(file);
- skipped.push(...entries.map((entry) => entry.source));
+ skipped.push(...entries.map(editLabel));
continue;
}
@@ -837,6 +861,11 @@ class SourceWriter {
try {
for (const edit of entries) {
+ if (edit.kind === "variable") {
+ if (!this.setVariable(sourceFile, edit)) skipped.push(`${editLabel(edit)} (variable)`);
+ continue;
+ }
+
if (edit.kind === "insert") {
if (!this.insertElement(file, sourceFile, edit, ids, nextId)) skipped.push(edit.source);
continue;
@@ -924,6 +953,31 @@ class SourceWriter {
return this.files.has(file) ? { skipped, ids, unrolled } : undefined;
}
+ /**
+ * Overwrites the initializer of an `@inspect`-annotated top-level const.
+ * False when no top-level const of that name carries the annotation, or when
+ * its initializer is not a literal anymore — an expression there is authored
+ * reactivity again, the same rule `isWritable` applies to a prop.
+ */
+ private setVariable(sourceFile: SourceFile, edit: SourceVariable): boolean {
+ for (const statement of sourceFile.getVariableStatements()) {
+ const declaration = statement.getDeclarations().find((candidate) => candidate.getName() === edit.name);
+ if (!declaration) continue;
+ // The same leniency the compile step reads with: any leading comment
+ // carrying the tag at the start of a line (past the comment markers).
+ const annotated = statement.getLeadingCommentRanges().some((range) =>
+ new RegExp(`(?:^|\\n)[\\s/*]*@${INSPECT_TAG}\\b`).test(range.getText()),
+ );
+ if (!annotated) continue;
+
+ const initializer = declaration.getInitializer();
+ if (!initializer || !isLiteral(initializer)) return false;
+ declaration.setInitializer(literalText(edit.value));
+ return true;
+ }
+ return false;
+ }
+
/**
* Adds one element to the tree, named on the spot: the canvas is already
* showing it and will address it by that name with its next edit, so it
diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.ts
index f7734a61..e9eb4dfb 100644
--- a/apps/desktop/src/projects.ts
+++ b/apps/desktop/src/projects.ts
@@ -17,8 +17,8 @@ import type { BuildOptions, Plugin } from "esbuild";
import { isHeadless } from "./cli-server";
import { mainBridge } from "./main-manager";
import { MAIN_CHANNELS } from "./main-channels";
-import { applyEdits, stampProject } from "./edit";
-import { canonicalizeTagsPlugin, sourcePlugin } from "./source";
+import { applyEdits, editLabel, stampProject } from "./edit";
+import { canonicalizeTagsPlugin, inspectPlugin, sourcePlugin } from "./source";
import type { CompileResult, FsEntry, FsStat, ProjectInfo, SourceEdit, WriteResult } from "./main-channels";
import type { SourceContext } from "./edit";
@@ -968,7 +968,7 @@ const babelOptions = (file: string, filename: string): TransformOptions => ({
configFile: false,
// Runs before the presets, which is what it needs: Solid's transform
// replaces the JSX trees this stamps.
- plugins: [[sourcePlugin, { file }], canonicalizeTagsPlugin],
+ plugins: [[sourcePlugin, { file }], canonicalizeTagsPlugin, [inspectPlugin, { file }]],
presets: [
[preset("babel-preset-solid"), { generate: "universal", moduleName: RUNTIME_MODULE }],
[preset("@babel/preset-typescript"), { onlyRemoveTypeImports: true }],
@@ -1042,7 +1042,7 @@ export async function writeProject(dir: string, edits: SourceEdit[]): Promise<Wr
try {
return await applyEdits(sourceContext(dir), edits);
} catch (error) {
- return { skipped: edits.map((edit) => edit.source), error: error instanceof Error ? error.message : String(error) };
+ return { skipped: edits.map(editLabel), error: error instanceof Error ? error.message : String(error) };
}
}
diff --git a/apps/desktop/src/source.ts b/apps/desktop/src/source.ts
index 91caf47f..f7c1f4e4 100644
--- a/apps/desktop/src/source.ts
+++ b/apps/desktop/src/source.ts
@@ -11,9 +11,10 @@
// disagreed, a drag would write to the wrong element; that invariant is why
// these two modules are read together.
-import { COMPOSITION_TAGS, ID_ATTR, LOOP_ATTR, SOURCE_ATTR, formatSource, isCompositionTag, isLoopTag } from "@diffusionstudio/jsx";
+import { COMPOSITION_TAGS, ID_ATTR, INSPECT_TAG, INSPECT_TYPES, LOOP_ATTR, SOURCE_ATTR, formatSource, isCompositionTag, isLoopTag } from "@diffusionstudio/jsx";
import type { NodePath, PluginObj, types as t } from "@babel/core";
+import type { InspectDeclaration, InspectType } from "@diffusionstudio/jsx";
/** What babel hands a plugin factory. */
type BabelApi = { types: typeof import("@babel/core").types };
@@ -118,6 +119,191 @@ export function canonicalizeTagsPlugin({ types }: BabelApi): PluginObj {
};
}
+// ---------------------------------------------------------------------------
+// @inspect variables
+
+/** What the compiled module imports `__inspect` from. */
+const INSPECT_MODULE = "@diffusionstudio/jsx";
+
+/**
+ * An `@inspect` tag at the start of a comment line. Anchored there — the way a
+ * JSDoc tag is written — so prose mentioning the tag mid-sentence is not read
+ * as an annotation.
+ */
+const INSPECT_ANNOTATION = new RegExp(`(?:^|\\n)\\s*\\*?\\s*@${INSPECT_TAG}\\b([^\\n]*)`);
+
+const INSPECT_PAIR = /(\w+)=(?:"([^"]*)"|(\S+))/g;
+
+type ParsedInspect = Pick<InspectDeclaration, "type" | "path" | "min" | "max" | "step">;
+
+const isInspectType = (value: string): value is InspectType => (INSPECT_TYPES as readonly string[]).includes(value);
+
+/**
+ * The annotation in `comments`, parsed, or undefined when none of them carry
+ * one. Throws (a plain Error the caller turns into a code frame) on an
+ * annotation that does not spell a control.
+ */
+function parseInspectComments(comments: readonly t.Comment[] | null | undefined): ParsedInspect | undefined {
+ const match = comments?.map((comment) => INSPECT_ANNOTATION.exec(comment.value)).find((found) => found !== null);
+ if (!match) return undefined;
+
+ const line = match[1]!.trim();
+ const typeMatch = /^([A-Za-z]+)\b/.exec(line);
+ if (!typeMatch || !isInspectType(typeMatch[1]!)) {
+ throw new Error(`@${INSPECT_TAG} needs a control type: one of ${INSPECT_TYPES.join(", ")}`);
+ }
+ const type = typeMatch[1] as InspectType;
+
+ const options: Record<string, string> = {};
+ let rest = line.slice(typeMatch[0].length);
+ rest = rest.replace(INSPECT_PAIR, (_, key: string, quoted: string | undefined, bare: string | undefined) => {
+ if (key in options) throw new Error(`@${INSPECT_TAG}: "${key}" is given twice`);
+ options[key] = quoted ?? bare ?? "";
+ return "";
+ });
+ if (rest.trim()) throw new Error(`@${INSPECT_TAG}: cannot read "${rest.trim()}" — options are written as key=value`);
+
+ const parsed: ParsedInspect = { type };
+
+ for (const key of ["min", "max", "step"] as const) {
+ const value = options[key];
+ if (value === undefined) continue;
+ if (type !== "number") throw new Error(`@${INSPECT_TAG}: "${key}" only applies to a number`);
+ const numeric = Number(value);
+ if (!Number.isFinite(numeric)) throw new Error(`@${INSPECT_TAG}: "${key}" must be a number, not "${value}"`);
+ parsed[key] = numeric;
+ }
+
+ const { path, label } = options;
+ if (path !== undefined && label !== undefined) {
+ throw new Error(`@${INSPECT_TAG}: "path" already names the label — drop "label"`);
+ }
+ const spelled = path ?? label;
+ if (spelled !== undefined) {
+ const segments = spelled.split("/").map((segment) => segment.trim()).filter(Boolean);
+ if (!segments.length) throw new Error(`@${INSPECT_TAG}: "${path === undefined ? "label" : "path"}" is empty`);
+ parsed.path = segments;
+ }
+
+ for (const key of Object.keys(options)) {
+ if (!["min", "max", "step", "path", "label"].includes(key)) {
+ throw new Error(`@${INSPECT_TAG}: unknown option "${key}"`);
+ }
+ }
+
+ return parsed;
+}
+
+/** The literal an `@inspect` initializer must be for its type, or undefined. */
+function inspectInitializer(node: t.Expression | null | undefined, type: InspectType): t.Expression | undefined {
+ if (!node) return undefined;
+ if (type === "number") {
+ if (node.type === "NumericLiteral") return node;
+ if (node.type === "UnaryExpression" && (node.operator === "-" || node.operator === "+") && node.argument.type === "NumericLiteral") return node;
+ return undefined;
+ }
+ return node.type === "StringLiteral" ? node : undefined;
+}
+
+/**
+ * Turns `@inspect`-annotated top-level consts into signals: the declaration's
+ * initializer becomes an `__inspect(declaration, literal)` call — which the
+ * editor implements as a signal it also hands its inspector — and every
+ * reference to the variable becomes a call of the accessor. Reads inside the
+ * JSX stay reactive (Solid's transform wraps them); a value derived at module
+ * top level is computed once, like any module-level expression.
+ *
+ * The variable is addressed by file and name, so the source is not written to;
+ * the write direction lives in `./edit`, which overwrites the initializer the
+ * second argument came from.
+ */
+export function inspectPlugin({ types }: BabelApi, { file }: { file: string }): PluginObj {
+ return {
+ name: "jsx-inspect-variables",
+ visitor: {
+ // On Program enter, like the other passes: everything is rewritten
+ // before Solid's transform consumes the JSX the references sit in.
+ Program(program) {
+ const helper = program.scope.generateUidIdentifier("inspect");
+ let used = false;
+
+ program.traverse({
+ VariableDeclaration(path) {
+ let annotation: ParsedInspect | undefined;
+ try {
+ // On an exported declaration the comment sits on the export
+ // statement; read it there too, so the export is refused rather
+ // than the annotation silently ignored.
+ annotation = parseInspectComments(path.node.leadingComments)
+ ?? (path.parentPath.isExportNamedDeclaration()
+ ? parseInspectComments(path.parentPath.node.leadingComments)
+ : undefined);
+ } catch (error) {
+ throw path.buildCodeFrameError((error as Error).message);
+ }
+ if (!annotation) return;
+
+ if (path.parentPath.isExportNamedDeclaration()) {
+ throw path.buildCodeFrameError(
+ `an @${INSPECT_TAG} variable cannot be exported: another module would import the value, not the control`,
+ );
+ }
+ if (!path.parentPath.isProgram()) {
+ throw path.buildCodeFrameError(`@${INSPECT_TAG} only works on a top-level const`);
+ }
+ if (path.node.kind !== "const" || path.node.declarations.length !== 1) {
+ throw path.buildCodeFrameError(`@${INSPECT_TAG} annotates a single const declaration`);
+ }
+
+ const declarator = path.node.declarations[0]!;
+ if (declarator.id.type !== "Identifier") {
+ throw path.buildCodeFrameError(`@${INSPECT_TAG} needs a plain name, not a destructuring`);
+ }
+ const name = declarator.id.name;
+
+ const initial = inspectInitializer(declarator.init, annotation.type);
+ if (!initial) {
+ throw path.buildCodeFrameError(
+ `an @${INSPECT_TAG} ${annotation.type} must be initialized with a ${annotation.type === "number" ? "number" : "string"} literal — it is what the editor writes back to`,
+ );
+ }
+
+ // Every read becomes a call of the accessor. The reference lists
+ // are per binding, so a shadowing local elsewhere keeps its own.
+ const binding = program.scope.getBinding(name);
+ for (const reference of binding?.referencePaths ?? []) {
+ // A type position mentions the name without reading the value.
+ if (reference.findParent((parent) => parent.node.type.startsWith("TS"))) continue;
+ if (reference.parentPath?.isExportSpecifier()) {
+ throw reference.buildCodeFrameError(
+ `an @${INSPECT_TAG} variable cannot be exported: another module would import the value, not the control`,
+ );
+ }
+ // `{ padding }` reads as `{ padding: padding() }` once rewritten.
+ const parent = reference.parent;
+ if (parent.type === "ObjectProperty" && parent.shorthand) parent.shorthand = false;
+ reference.replaceWith(types.callExpression(types.identifier(name), []));
+ }
+
+ const declaration: InspectDeclaration = { file, name, ...annotation };
+ declarator.init = types.callExpression(types.cloneNode(helper), [types.valueToNode(declaration), initial]);
+ used = true;
+ },
+ });
+
+ if (!used) return;
+ program.unshiftContainer(
+ "body",
+ types.importDeclaration(
+ [types.importSpecifier(helper, types.identifier("__inspect"))],
+ types.stringLiteral(INSPECT_MODULE),
+ ),
+ );
+ },
+ },
+ };
+}
+
const jsxTagName = (element: t.JSXElement): string | undefined => {
const name = element.openingElement.name;
return name.type === "JSXIdentifier" ? name.name : undefined;
diff --git a/apps/web/src/components/sidebar-right/inspector/inspector.tsx b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
index 62270225..7a0cd250 100644
--- a/apps/web/src/components/sidebar-right/inspector/inspector.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/inspector.tsx
@@ -20,6 +20,7 @@ import {
import { useAssetSelection, useSelection, useTool } from "@/engine/hooks";
import { InspectorHeader } from "./inspector-header";
import { BackgroundSettings } from "./background";
+import { VariablesSettings } from "./variables";
import { SceneTemplatePanel } from "./scene-template";
import { AssetInfoPanel } from "./asset-info";
import { TimeSettings } from "./time";
@@ -123,6 +124,10 @@ export function Inspector() {
<BackgroundSettings />
</Show>
+ <Show when={includesTarget("stage")}>
+ <VariablesSettings />
+ </Show>
+
<Show when={includesTarget("shape", "text", "audio", "scene", "caption", "group", "mask", "adjustment")}>
<TimeSettings selection={nodes()} />
</Show>
diff --git a/apps/web/src/components/sidebar-right/inspector/text.tsx b/apps/web/src/components/sidebar-right/inspector/text.tsx
index fd8e4b89..79cd2ffd 100644
--- a/apps/web/src/components/sidebar-right/inspector/text.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/text.tsx
@@ -287,7 +287,7 @@ type FontDropdownProps = {
onWeightsChange(weights: string[]): void;
};
-function FontDropdown(props: FontDropdownProps) {
+export function FontDropdown(props: FontDropdownProps) {
const [webfonts] = createSignal(getWebFonts());
const [fontQuery, setFontQuery] = createSignal('');
const fontsPermission = usePermissionState('local-fonts');
@@ -447,7 +447,7 @@ type GrowingTextAreaProps = {
onFocus?(): void;
};
-function GrowingTextArea(props: GrowingTextAreaProps) {
+export function GrowingTextArea(props: GrowingTextAreaProps) {
let ref!: HTMLTextAreaElement;
const lineHeight = 18; // matches text-xs leading
const maxRows = () => props.maxRows ?? 8;
diff --git a/apps/web/src/components/sidebar-right/inspector/variables.tsx b/apps/web/src/components/sidebar-right/inspector/variables.tsx
new file mode 100644
index 00000000..c15fe627
--- /dev/null
+++ b/apps/web/src/components/sidebar-right/inspector/variables.tsx
@@ -0,0 +1,193 @@
+/* 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/. */
+
+/**
+ * The dynamic inspector: one control per `@inspect` variable of the mounted
+ * project (see @diffusionstudio/jsx's inspect), filed under the groups their
+ * paths spell. A control moves the variable's signal live — one reactive
+ * graph, no remount — and every settled value goes through the editor, so the
+ * declaration's initializer and the undo history hear it like any other edit.
+ *
+ * Grouping renders one level deep: a path of `A/B/Label` files the control
+ * under a section titled "A / B". Ungrouped variables come first, under
+ * "Variables".
+ */
+
+import { ControlRow } from "@/components/ui/control-group";
+import { PanelSection } from "@/components/ui/panel-section";
+import { SliderInput } from "@/components/ui/slider-input";
+import { ControlledTextField } from "@/components/ui/text-field";
+import { ColorOpacityPicker } from "@/components/ui/color-opacity-picker";
+import { ColorOpacityRow } from "@/components/ui/color-opacity-row";
+import {
+ FloatingInspector,
+ FloatingInspectorContent,
+ FloatingInspectorHeader,
+ FloatingInspectorTitle,
+} from "@/components/ui/floating-inspector";
+import { Icon } from "@/components/ui/icon";
+import { Button } from "@/components/ui/button";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { For, Match, Switch, createMemo, createSignal } from "solid-js";
+import { WebFonts, loadWebFont } from "@diffusionstudio/runtime";
+import { useWorld } from "@diffusionstudio/koota-solid";
+import { useEditor } from "@/engine/hooks";
+import { useInspectEntries } from "@/engine/inspect";
+import { colorToHex, parseColor } from "@/utils/color";
+import { FontDropdown, GrowingTextArea } from "./text";
+
+import type { InspectEntry } from "@diffusionstudio/reconciler";
+import type { InspectValue } from "@diffusionstudio/jsx";
+
+export function VariablesSettings() {
+ const world = useWorld();
+ const entries = useInspectEntries(world);
+
+ // Sections in order of first appearance, the ungrouped one always first.
+ const sections = createMemo(() => {
+ const grouped = new Map<string, InspectEntry[]>([["", []]]);
+ for (const entry of entries()) {
+ const key = entry.group.join(" / ");
+ grouped.set(key, [...(grouped.get(key) ?? []), entry]);
+ }
+ return [...grouped].filter(([, members]) => members.length > 0);
+ });
+
+ return (
+ <For each={sections()}>
+ {([group, members]) => (
+ <PanelSection title={group || "Variables"}>
+ <For each={members}>{(entry) => <VariableControl entry={entry} />}</For>
+ </PanelSection>
+ )}
+ </For>
+ );
+}
+
+function VariableControl(props: { entry: InspectEntry }) {
+ const world = useWorld();
+ const editor = useEditor();
+ const entry = () => props.entry;
+
+ /** The settled value: the signal for the canvas, the edit for the file. */
+ const commit = (value: InspectValue) => {
+ editor.editVariable(entry().file, entry().name, value);
+ };
+
+ return (
+ <Switch>
+ <Match when={entry().type === "number"}>
+ <NumberControl entry={entry()} onCommit={commit} />
+ </Match>
+ <Match when={entry().type === "color"}>
+ <ColorControl entry={entry()} onCommit={commit} />
+ </Match>
+ <Match when={entry().type === "font"}>
+ <ControlRow label={entry().label}>
+ <FontDropdown
+ family={String(entry().get())}
+ // Hovering previews on the signal alone; closing puts the
+ // authored family back (the dropdown hands it back itself).
+ onPreview={(family) => entry().set(family)}
+ onFamilyChange={(family) => {
+ commit(family);
+ if (family in WebFonts) {
+ void loadWebFont(world, family as keyof typeof WebFonts);
+ }
+ }}
+ onWeightsChange={() => {}}
+ />
+ </ControlRow>
+ </Match>
+ <Match when={entry().type === "text"}>
+ <ControlRow label={entry().label} contentClass="flex flex-col">
+ <GrowingTextArea
+ value={String(entry().get())}
+ maxRows={8}
+ onInput={(value) => commit(value)}
+ />
+ </ControlRow>
+ </Match>
+ </Switch>
+ );
+}
+
+function NumberControl(props: { entry: InspectEntry; onCommit: (value: InspectValue) => void }) {
+ const value = () => Number(props.entry.get());
+
+ return (
+ <ControlRow label={props.entry.label}>
+ {/* A slider needs both ends; without them the field still drags. */}
+ <Switch>
+ <Match when={props.entry.min !== undefined && props.entry.max !== undefined}>
+ <SliderInput
+ value={value()}
+ min={props.entry.min}
+ max={props.entry.max}
+ step={props.entry.step}
+ onChange={(next) => props.onCommit(next)}
+ />
+ </Match>
+ <Match when={true}>
+ <ControlledTextField
+ value={value()}
+ onNumber={(next) => props.onCommit(next)}
+ step={props.entry.step ?? 1}
+ min={props.entry.min}
+ max={props.entry.max}
+ autoSelect
+ sliderEnabled
+ limitEvents
+ />
+ </Match>
+ </Switch>
+ </ControlRow>
+ );
+}
+
+function ColorControl(props: { entry: InspectEntry; onCommit: (value: InspectValue) => void }) {
+ const [isPickerOpen, setIsPickerOpen] = createSignal(false);
+ const color = () => parseColor(String(props.entry.get())) ?? 0;
+ const assignColor = (next: number) => props.onCommit(colorToHex(next));
+
+ let anchorRef: HTMLDivElement | undefined;
+
+ return (
+ <ControlRow label={props.entry.label} ref={anchorRef}>
+ <ColorOpacityRow
+ color={color()}
+ onChangeColor={assignColor}
+ onClick={() => setIsPickerOpen(true)}
+ />
+
+ <FloatingInspector open={isPickerOpen} anchorRef={anchorRef}>
+ <FloatingInspectorHeader>
+ <FloatingInspectorTitle>{props.entry.label}</FloatingInspectorTitle>
+ <div class="ml-auto">
+ <Tooltip>
+ <TooltipTrigger
+ as={Button}
+ size="icon"
+ variant="ghost"
+ class="text-muted-foreground"
+ onClick={() => setIsPickerOpen(false)}
+ >
+ <Icon name="close-remove" class="size-6" />
+ </TooltipTrigger>
+ <TooltipContent>Close</TooltipContent>
+ </Tooltip>
+ </div>
+ </FloatingInspectorHeader>
+ <FloatingInspectorContent class="p-0">
+ <ColorOpacityPicker
+ color={color()}
+ opacity={1}
+ onColorChange={assignColor}
+ withoutOpacity
+ />
+ </FloatingInspectorContent>
+ </FloatingInspector>
+ </ControlRow>
+ );
+}
diff --git a/apps/web/src/engine/editor.ts b/apps/web/src/engine/editor.ts
index d06c07cd..163790c2 100644
--- a/apps/web/src/engine/editor.ts
+++ b/apps/web/src/engine/editor.ts
@@ -16,8 +16,10 @@ import { createRoot } from 'solid-js';
import { authoredElement, authoredTree, getRuntimeDocument, insert, isSceneNode, renderAuthored, withDocument } from '@diffusionstudio/reconciler';
+import { findInspectEntry } from './inspect';
+
import type { SceneNode } from '@diffusionstudio/runtime';
-import type { PropValue, SerializedAssetRef } from '@diffusionstudio/jsx';
+import type { InspectValue, PropValue, SerializedAssetRef } from '@diffusionstudio/jsx';
import type { Entity, World } from 'koota';
import type { AuthoredTree, ProjectDocument, RuntimeDocument } from '@diffusionstudio/reconciler';
@@ -158,7 +160,21 @@ export interface UnrollEdit {
iterations: LoopIteration[];
}
-export type EntityEdit = PropEdit | TextEdit | InsertEdit | MoveEdit | RemoveEdit | UnrollEdit;
+/**
+ * An `@inspect` variable the editor set (see `engine/inspect`). Not an
+ * element's edit at all: it is addressed by file and variable name rather
+ * than by source stamp, and the writer overwrites the declaration's
+ * initializer. `previous` is the inverse for the history, as on `PropEdit`.
+ */
+export interface VariableEdit {
+ kind: 'variable';
+ file: string;
+ name: string;
+ value: InspectValue;
+ previous: InspectValue;
+}
+
+export type EntityEdit = PropEdit | TextEdit | InsertEdit | MoveEdit | RemoveEdit | UnrollEdit | VariableEdit;
/**
* Sources of elements the editor created that no write has named yet. Shaped
@@ -323,6 +339,22 @@ export class DocumentEditor {
this.reportEdit(entity, name, value, previous ?? false);
}
+ /**
+ * Sets an `@inspect` variable and reports it: the signal moves the
+ * composition (one reactive graph, no remount), the report takes the value
+ * to the declaration's initializer and into the history. A name the mount
+ * did not declare is ignored — an undo can outlive the registry entry it
+ * was recorded against.
+ */
+ public editVariable(file: string, name: string, value: InspectValue): void {
+ const entry = findInspectEntry(this.world, file, name);
+ if (!entry) return;
+ const previous = entry.get();
+ if (previous === value) return;
+ entry.set(value);
+ this.emit({ kind: 'variable', file, name, value, previous });
+ }
+
/**
* Writes what a `<text>` says to the document and reports it. Settled
* first for the same reason a prop is: one iteration of a loop cannot say
diff --git a/apps/web/src/engine/history.ts b/apps/web/src/engine/history.ts
index 532f7ae0..a3cd8791 100644
--- a/apps/web/src/engine/history.ts
+++ b/apps/web/src/engine/history.ts
@@ -29,7 +29,7 @@ import { createSignal } from 'solid-js';
import { getDocumentEditor } from './editor';
import type { AuthoredTree } from '@diffusionstudio/reconciler';
-import type { PropValue } from '@diffusionstudio/jsx';
+import type { InspectValue, PropValue } from '@diffusionstudio/jsx';
import type { Entity, World } from 'koota';
import type { CapturedNode, DocumentEditor, EntityEdit } from './editor';
@@ -97,7 +97,30 @@ interface MoveOp {
toBefore?: string;
}
-type HistoryOp = PropOp | TextOp | InsertOp | RemoveOp | MoveOp;
+/**
+ * An `@inspect` variable, set. Addressed by file and variable name — no
+ * source, no entity, so renames never touch it and it replays against
+ * whatever the current mount declared under that name.
+ */
+interface VariableOp {
+ kind: 'variable';
+ file: string;
+ name: string;
+ before: InspectValue;
+ after: InspectValue;
+}
+
+type HistoryOp = PropOp | TextOp | InsertOp | RemoveOp | MoveOp | VariableOp;
+
+/**
+ * The identity a sliding op coalesces on: the same prop of the same element,
+ * or the same variable, adjusted again is one continuing adjustment.
+ */
+const slidingKey = (op: HistoryOp): string | undefined => {
+ if (op.kind === 'prop') return `prop ${op.source} ${op.name}`;
+ if (op.kind === 'variable') return `variable ${op.file} ${op.name}`;
+ return undefined;
+};
/**
* One undo step: the ops of one gesture, or of one synchronous burst of
@@ -263,6 +286,20 @@ export class EditHistory {
return;
}
+ case 'variable': {
+ const transaction = this.ensureOpen();
+ // A slider writes the same variable every frame; one op, sliding.
+ const existing = transaction.ops.find(
+ (op): op is VariableOp => op.kind === 'variable' && op.file === edit.file && op.name === edit.name,
+ );
+ if (existing) {
+ existing.after = edit.value;
+ return;
+ }
+ transaction.ops.push({ kind: 'variable', file: edit.file, name: edit.name, before: edit.previous, after: edit.value });
+ return;
+ }
+
case 'insert': {
const transaction = this.ensureOpen();
// The element as it stands, live values included, rather than
@@ -359,10 +396,9 @@ export class EditHistory {
const last = this.undos[this.undos.length - 1];
if (last && this.coalesces(last, transaction)) {
- for (const op of transaction.ops as PropOp[]) {
+ for (const op of transaction.ops as (PropOp | VariableOp)[]) {
const target = last.ops.find(
- (candidate): candidate is PropOp =>
- candidate.kind === 'prop' && candidate.source === op.source && candidate.name === op.name,
+ (candidate): candidate is PropOp | VariableOp => slidingKey(candidate) === slidingKey(op),
);
if (target) target.after = op.after;
}
@@ -377,18 +413,26 @@ export class EditHistory {
}
/**
- * 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.
+ * Whether `next` is `last` still going: both bursts of sliding ops only —
+ * props or variables, never gestures (two drags are two steps) — over the
+ * same keys, 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));
+ const keysOf = (transaction: Transaction): Set<string> | undefined => {
+ const keys = new Set<string>();
+ for (const op of transaction.ops) {
+ const key = slidingKey(op);
+ if (key === undefined) return undefined;
+ keys.add(key);
+ }
+ return keys;
+ };
+ const lastKeys = keysOf(last);
+ const nextKeys = keysOf(next);
+ if (!lastKeys || !nextKeys) return false;
return lastKeys.size === nextKeys.size && [...nextKeys].every((entry) => lastKeys.has(entry));
}
@@ -424,6 +468,10 @@ export class EditHistory {
this.editor.reparent(entity, parent, anchor);
return;
}
+ case 'variable': {
+ this.editor.editVariable(op.file, op.name, op.before);
+ return;
+ }
}
}
@@ -456,6 +504,10 @@ export class EditHistory {
this.editor.reparent(entity, parent, anchor);
return;
}
+ case 'variable': {
+ this.editor.editVariable(op.file, op.name, op.after);
+ return;
+ }
}
}
diff --git a/apps/web/src/engine/inspect.ts b/apps/web/src/engine/inspect.ts
new file mode 100644
index 00000000..f2381c75
--- /dev/null
+++ b/apps/web/src/engine/inspect.ts
@@ -0,0 +1,48 @@
+/* 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/. */
+
+/**
+ * The `@inspect` variables of the mounted project, held per world so the
+ * inspector and the editor read the same entries the mount collected. Set on
+ * every mount and cleared on unmount (see the editor page): the entries hold
+ * the mount's signals, and a stale entry would write into a dead graph.
+ */
+
+import { createSignal } from 'solid-js';
+
+import type { Accessor } from 'solid-js';
+import type { InspectEntry } from '@diffusionstudio/reconciler';
+import type { World } from 'koota';
+
+interface Registry {
+ entries: Accessor<InspectEntry[]>;
+ setEntries: (entries: InspectEntry[]) => void;
+}
+
+const registries = new WeakMap<World, Registry>();
+
+function registry(world: World): Registry {
+ let existing = registries.get(world);
+ if (!existing) {
+ const [entries, setEntries] = createSignal<InspectEntry[]>([]);
+ existing = { entries, setEntries: (next) => setEntries(next) };
+ registries.set(world, existing);
+ }
+ return existing;
+}
+
+/** Replaces the world's entries with the given mount's (or `[]` on unmount). */
+export function setInspectEntries(world: World, entries: InspectEntry[]): void {
+ registry(world).setEntries(entries);
+}
+
+/** The current entries, reactive under a Solid computation. */
+export function useInspectEntries(world: World): Accessor<InspectEntry[]> {
+ return registry(world).entries;
+}
+
+/** The entry declared as `name` in `file`, or undefined for none. */
+export function findInspectEntry(world: World, file: string, name: string): InspectEntry | undefined {
+ return registry(world).entries().find((entry) => entry.file === file && entry.name === name);
+}
diff --git a/apps/web/src/pages/editor.tsx b/apps/web/src/pages/editor.tsx
index cd296084..81e054ef 100644
--- a/apps/web/src/pages/editor.tsx
+++ b/apps/web/src/pages/editor.tsx
@@ -16,6 +16,7 @@ import { useWorld } from '@diffusionstudio/koota-solid';
import { mount } from '@diffusionstudio/reconciler';
import { getDocumentEditor } from '@/engine/editor';
import { getEditHistory } from '@/engine/history';
+import { setInspectEntries } from '@/engine/inspect';
import { attachLibrary, isLibraryFile } from '@/engine/library';
import { attachAi } from '@/utils/gen-ai';
import { attachProjectConfig, isProjectConfigFile } from '@/engine/project-config';
@@ -71,6 +72,8 @@ export function EditorPage() {
mounted?.dispose();
mounted = undefined;
mountedCode = undefined;
+ // The entries hold the dead mount's signals; the inspector must not.
+ setInspectEntries(world, []);
};
/** Puts `code` on the stage, unless it is what is there already. */
@@ -80,6 +83,8 @@ export function EditorPage() {
unmount();
mounted = mount(code, world);
mountedCode = code;
+ // The `@inspect` variables this mount declared, for the inspector.
+ setInspectEntries(world, mounted.inspect);
// The rendered scene knows which element every entity came from, so
// from here on an edit in the editor can find its way back.
writer = createEditWriter(dir, world);
diff --git a/apps/web/src/projects/edits.ts b/apps/web/src/projects/edits.ts
index 49c7a28f..d0717303 100644
--- a/apps/web/src/projects/edits.ts
+++ b/apps/web/src/projects/edits.ts
@@ -8,7 +8,7 @@ import { toast } from 'somoto';
import { writeProject } from './host';
-import type { EntityEdit, InsertEdit, MoveEdit, RemoveEdit, UnrollEdit } from '@/engine/editor';
+import type { EntityEdit, InsertEdit, MoveEdit, RemoveEdit, UnrollEdit, VariableEdit } from '@/engine/editor';
import type { SourceEdit, WriteResult } from './host';
import type { World } from 'koota';
@@ -40,6 +40,9 @@ class EditWriter {
// worth writing, same as a prop's.
private texts = new Map<string, string>();
private removes = new Set<string>();
+ // `@inspect` variables, by file and name. Independent of the elements:
+ // nothing else addresses one, and none of them is ever pending.
+ private variables = new Map<string, VariableEdit>();
// Pending sources a write is out for: edits to them wait for the answer.
private inflight = new Set<string>();
// The unrolls a write is out for. One the write declines is taken back
@@ -77,6 +80,9 @@ class EditWriter {
} else {
this.moves.set(edit.source, edit);
}
+ } else if (edit.kind === 'variable') {
+ // The last value is the only one worth writing, like a prop's.
+ this.variables.set(`${edit.file}\n${edit.name}`, edit);
} else if (edit.kind === 'text') {
// What an element still waiting to be inserted says is part of how
// it is inserted, the way a prop of it is.
@@ -158,7 +164,7 @@ class EditWriter {
private flush(): void {
this.timer = undefined;
- if (!this.unrolls.size && !this.inserts.size && !this.moves.size && !this.pending.size && !this.texts.size && !this.removes.size) return;
+ if (!this.unrolls.size && !this.inserts.size && !this.moves.size && !this.pending.size && !this.texts.size && !this.removes.size && !this.variables.size) return;
// Anything addressed through an element whose insert is still out
// waits for its name: edits to it, and inserts or moves under or
@@ -216,12 +222,16 @@ class EditWriter {
...[...this.removes]
.filter((source) => !heldRemoves.has(source))
.map((source): SourceEdit => ({ kind: 'remove', source })),
+ // Variables are addressed by name, so nothing above moves them.
+ ...[...this.variables.values()]
+ .map(({ file, name, value }): SourceEdit => ({ kind: 'variable', file, name, value })),
];
if (!edits.length) return;
// The names an unroll handed out are out with it.
this.sent = [...this.unrolls.values()];
this.unrolls = new Map();
+ this.variables = new Map();
this.inflight = new Set([
...[...this.inflight, ...this.inserts.keys()].filter((source) => !heldInserts.has(source)),
...this.sent.flatMap((unroll) => pendingsOf(unroll)),
diff --git a/examples/09-inspect-variables.tsx b/examples/09-inspect-variables.tsx
new file mode 100644
index 00000000..2259783e
--- /dev/null
+++ b/examples/09-inspect-variables.tsx
@@ -0,0 +1,60 @@
+/* @jsxImportSource @diffusionstudio/jsx */
+/* `@inspect` variables: annotate a top-level const and the editor's right
+ * sidebar grows a control for it (stage level, under the background picker).
+ * Moving the control moves the composition live — no remount — and the value
+ * it settles on is written back into the initializer below.
+ *
+ * cp examples/09-inspect-variables.tsx ~/Projects/inspect/index.tsx
+ * dapi open ~/Projects/inspect
+ *
+ * See reference/jsx/variables.md for the full annotation grammar.
+ */
+
+/** @inspect text path="Content/Title" */
+const title = "Hello world";
+
+/** @inspect font path="Typography/Font" */
+const fontFamily = "Inter";
+
+/** @inspect number path="Typography/Size" min=8 max=240 step=1 */
+const fontSize = 120;
+
+/** @inspect color path="Typography/Color" */
+const textColor = "#ffffff";
+
+/** @inspect color */
+const backdrop = "#161616";
+
+/** @inspect number min=0 max=200 */
+const padding = 64;
+
+export default function InspectVariables() {
+ return (
+ <stage>
+ <scene name="Inspect" width={1920} height={1080} fill={backdrop} active>
+ <rect
+ x={padding}
+ y={padding}
+ width={1920 - padding * 2}
+ height={1080 - padding * 2}
+ fill="transparent"
+ cornerRadius={24}
+ >
+ <stroke color="#ffffff33" width={2} />
+ </rect>
+ <text
+ width={1920}
+ height={1080}
+ textAlign="center"
+ textBaseline="middle"
+ color={textColor}
+ fontFamily={fontFamily}
+ fontSize={fontSize}
+ fontWeight="bold"
+ >
+ {title}
+ </text>
+ </scene>
+ </stage>
+ );
+}
diff --git a/packages/jsx/src/index.ts b/packages/jsx/src/index.ts
index d724a5df..f514a0d0 100644
--- a/packages/jsx/src/index.ts
+++ b/packages/jsx/src/index.ts
@@ -45,6 +45,8 @@ export {
export type { CompositionTag, PropValue } from "./source";
export { useTicker } from "./hooks";
export type { Ticker } from "./hooks";
+export { INSPECT_TAG, INSPECT_TYPES, __inspect } from "./inspect";
+export type { InspectDeclaration, InspectType, InspectValue } from "./inspect";
export type {
AdjustmentLayerProps,
AnimatableProperty,
diff --git a/packages/jsx/src/inspect.ts b/packages/jsx/src/inspect.ts
new file mode 100644
index 00000000..685f00b9
--- /dev/null
+++ b/packages/jsx/src/inspect.ts
@@ -0,0 +1,77 @@
+/* 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/. */
+
+/**
+ * The inspect annotation: how a project marks a top-level `const` as editable
+ * from the editor's inspector.
+ *
+ * // A JSDoc comment on the declaration: @inspect number min=0 max=100 step=1
+ * const padding = 24;
+ *
+ * The compile step reads the annotation, turns the declaration into a signal
+ * (`__inspect`), and rewrites every reference into a call of it — so the
+ * inspector can move the value live, and the editor writes what it settles on
+ * back into the initializer. The variable is addressed by file and name;
+ * nothing about it needs an id.
+ *
+ * `path="Typography/Font"` is presentation only: the last segment is the
+ * control's label, the segments before it the group it is filed under. Without
+ * it, the label is the variable's own name, prettified, and the control is
+ * ungrouped. `label="Font"` names the control without grouping it.
+ *
+ * The initializer must be a plain literal — a `number` a numeric one, the
+ * string types a string — since it is what the editor overwrites. Because the
+ * rewrite is per file, an annotated variable cannot be exported: an importer
+ * would receive the accessor where it expects the value.
+ */
+
+import type { Accessor } from "solid-js";
+
+/** The JSDoc tag, without the `@`. */
+export const INSPECT_TAG = "inspect";
+
+/** The controls an annotation can ask for, keyed by how the value is edited. */
+export const INSPECT_TYPES = ["number", "color", "text", "font"] as const;
+
+export type InspectType = (typeof INSPECT_TYPES)[number];
+
+/** What an inspected variable can hold: what its literal initializer can be. */
+export type InspectValue = string | number;
+
+/**
+ * An annotated declaration as the compile step spells it into the bundle —
+ * everything the annotation and the declaration said, verbatim. `path` is the
+ * authored `path` (or `label`) split into segments; presentation derives from
+ * it at mount.
+ */
+export interface InspectDeclaration {
+ /** Project-relative file the variable is declared in. */
+ file: string;
+ /** The variable's own name — with `file`, its identity. */
+ name: string;
+ type: InspectType;
+ path?: string[];
+ min?: number;
+ max?: number;
+ step?: number;
+}
+
+function hostOnly(name: string): never {
+ throw new Error(
+ `${name} is implemented by the editor's renderer and only works inside a mounted project.`,
+ );
+}
+
+/**
+ * What an `@inspect` declaration compiles into: a signal the inspector shares
+ * with the composition. Never authored by hand — the compile step injects the
+ * call and rewrites the variable's references into calls of the accessor; this
+ * declaration exists so the substituted module (see @diffusionstudio/reconciler)
+ * has a signature to stand in for.
+ */
+export function __inspect(declaration: InspectDeclaration, initial: InspectValue): Accessor<InspectValue> {
+ void declaration;
+ void initial;
+ return hostOnly("__inspect");
+}
diff --git a/packages/reconciler/src/index.ts b/packages/reconciler/src/index.ts
index 23df2d40..bcc5baa6 100644
--- a/packages/reconciler/src/index.ts
+++ b/packages/reconciler/src/index.ts
@@ -5,6 +5,7 @@
export * from './document';
export * from './elements';
export { evaluate } from './evaluate';
+export { collectInspect, type InspectEntry } from './inspect';
export { mount, type Mount } from './mount';
export { insert, renderProject, withDocument } from './renderer';
export { JSX_RUNTIME } from './runtime';
diff --git a/packages/reconciler/src/inspect.ts b/packages/reconciler/src/inspect.ts
new file mode 100644
index 00000000..a1c7c6fa
--- /dev/null
+++ b/packages/reconciler/src/inspect.ts
@@ -0,0 +1,89 @@
+/* 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/. */
+
+/**
+ * The live `__inspect` — substituted for the throwing declaration in
+ * @diffusionstudio/jsx (see "./runtime"), so a compiled `@inspect` declaration
+ * resolves to a signal on the host's Solid instance. The composition reads it
+ * through the rewritten references; the inspector reads and writes it through
+ * the entry collected here. One signal, one graph: a set from the inspector
+ * lands in the mounted entities without a remount.
+ */
+
+import { createSignal } from 'solid-js';
+
+import type { Accessor } from 'solid-js';
+import type { InspectDeclaration, InspectType, InspectValue } from '@diffusionstudio/jsx';
+
+/**
+ * One inspected variable of a mount: its identity (`file` and `name`, which is
+ * how an edit of it is addressed to the source), how the inspector presents it
+ * (`label`, `group` — derived from the authored `path`, or from the name), the
+ * constraints its annotation put on it, and the signal itself.
+ */
+export interface InspectEntry {
+ file: string;
+ name: string;
+ type: InspectType;
+ label: string;
+ /** The group segments the control is filed under; empty for ungrouped. */
+ group: string[];
+ min?: number;
+ max?: number;
+ step?: number;
+ /** What the source declared, before anyone touched the signal. */
+ initial: InspectValue;
+ get: Accessor<InspectValue>;
+ set: (value: InspectValue) => void;
+}
+
+// Module evaluation is synchronous (see `evaluate`), so one slot is enough:
+// whichever mount is evaluating right now is who the entries belong to.
+let collecting: InspectEntry[] | null = null;
+
+/**
+ * Runs `fn` (a mount evaluating a bundle) collecting every `__inspect` call it
+ * makes, in declaration order — imported modules first, the way CommonJS
+ * evaluates them.
+ */
+export function collectInspect<T>(fn: () => T): { result: T; entries: InspectEntry[] } {
+ const entries: InspectEntry[] = [];
+ const previous = collecting;
+ collecting = entries;
+ try {
+ return { result: fn(), entries };
+ } finally {
+ collecting = previous;
+ }
+}
+
+/** `fontFamily` as a label: "Font Family". */
+function prettify(name: string): string {
+ return name
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
+ .replace(/[_-]+/g, ' ')
+ .trim()
+ .replace(/^./, (first) => first.toUpperCase());
+}
+
+export function __inspect(declaration: InspectDeclaration, initial: InspectValue): Accessor<InspectValue> {
+ const [get, set] = createSignal(initial);
+ const path = declaration.path ?? [];
+
+ collecting?.push({
+ file: declaration.file,
+ name: declaration.name,
+ type: declaration.type,
+ label: path.at(-1) ?? prettify(declaration.name),
+ group: path.slice(0, -1),
+ ...(declaration.min === undefined ? {} : { min: declaration.min }),
+ ...(declaration.max === undefined ? {} : { max: declaration.max }),
+ ...(declaration.step === undefined ? {} : { step: declaration.step }),
+ initial,
+ get,
+ set,
+ });
+
+ return get;
+}
diff --git a/packages/reconciler/src/mount.ts b/packages/reconciler/src/mount.ts
index 2d89d281..599ef8a3 100644
--- a/packages/reconciler/src/mount.ts
+++ b/packages/reconciler/src/mount.ts
@@ -6,13 +6,21 @@ import { Tickers } from '@diffusionstudio/runtime';
import { createRuntimeDocument } from './document';
import { evaluate } from './evaluate';
+import { collectInspect } from './inspect';
import { renderProject } from './renderer';
import type { World } from 'koota';
+import type { InspectEntry } from './inspect';
export interface Mount {
/** Tears down the reactive graph and every entity the project rendered. */
dispose(): void;
+ /**
+ * The `@inspect` variables the bundle declared, in declaration order, each
+ * holding the live signal the composition reads. Die with the mount: a
+ * remount evaluates the module again and declares them afresh.
+ */
+ inspect: InspectEntry[];
}
/**
@@ -27,7 +35,7 @@ export interface Mount {
* is what `useTicker` subscribes to.
*/
export function mount(code: string, world: World): Mount {
- const component = evaluate(code);
+ const { result: component, entries } = collectInspect(() => evaluate(code));
const document = createRuntimeDocument(world);
let dispose: () => void;
@@ -42,6 +50,7 @@ export function mount(code: string, world: World): Mount {
world.get(Tickers)?.add(advance);
return {
+ inspect: entries,
dispose() {
world.get(Tickers)?.delete(advance);
// Solid's universal render disposer only drops the reactive graph;
diff --git a/packages/reconciler/src/runtime.ts b/packages/reconciler/src/runtime.ts
index ba28ddd0..f8315148 100644
--- a/packages/reconciler/src/runtime.ts
+++ b/packages/reconciler/src/runtime.ts
@@ -20,6 +20,7 @@
import * as authoring from '@diffusionstudio/jsx';
import * as elements from './elements';
+import { __inspect } from './inspect';
import {
createComponent,
createElement,
@@ -52,4 +53,5 @@ export const JSX_RUNTIME = {
mergeProps,
use,
useTicker,
+ __inspect,
};
diff --git a/reference/jsx/README.md b/reference/jsx/README.md
index 526cbc6e..b9e65029 100644
--- a/reference/jsx/README.md
+++ b/reference/jsx/README.md
@@ -50,6 +50,7 @@ export default function Project() {
| [audio-sync.md](./audio-sync.md) | `syncTo` audio alignment |
| [captions.md](./captions.md) | `<captions>` and style presets |
| [generate.md](./generate.md) | Declarative AI asset generation (`generate.*`) |
+| [variables.md](./variables.md) | `@inspect` variables: annotated consts as live inspector controls |
| [lifecycle.md](./lifecycle.md) | Mount lifecycle: always live, persisted + re-executed, `useTicker` |
| [errors.md](./errors.md) | Where each pipeline stage fails and with what effect |
diff --git a/reference/jsx/variables.md b/reference/jsx/variables.md
new file mode 100644
index 00000000..8a311155
--- /dev/null
+++ b/reference/jsx/variables.md
@@ -0,0 +1,59 @@
+# `@inspect` Variables
+
+Mark a top-level `const` with an `@inspect` JSDoc tag and the editor's right sidebar grows a control for it, at the stage level, below the background picker. Moving the control moves the composition **live** — the variable is compiled into a signal on the editor's reactive graph, so nothing remounts — and the value it settles on is written back into the initializer, the same way a dragged rect lands in the file.
+
+```tsx
+/** @inspect number min=0 max=100 step=1 */
+const padding = 24;
+
+/** @inspect font path="Typography/Font" */
+const fontFamily = "Inter";
+
+/** @inspect color path="Typography/Color" */
+const textColor = "#ff3366";
+
+/** @inspect text */
+const title = "Hello world";
+
+export default function Project() {
+ return (
+ <stage>
+ <scene width={1920} height={1080}>
+ <text x={padding} fontFamily={fontFamily} fill={textColor}>{title}</text>
+ </scene>
+ </stage>
+ );
+}
+```
+
+## The annotation
+
+```
+@inspect <type> [min=…] [max=…] [step=…] [path="Group/Label"] [label="Label"]
+```
+
+| Type | Control | Initializer |
+| ---- | ------- | ----------- |
+| `number` | Slider when `min` and `max` are both given, a draggable number field otherwise | a number literal |
+| `color` | Color picker | a string literal (`"#ff3366"`) |
+| `text` | Text area | a string literal |
+| `font` | Font picker (web + system fonts) | a string literal naming the family |
+
+`min`, `max` and `step` only apply to `number`.
+
+**Identity is the file and the variable name** — nothing else. Renaming the variable renames the control's identity; no id is minted, and nothing extra is written into your source.
+
+**Presentation derives from the name.** The label is the variable's own name prettified (`fontFamily` → "Font Family"), and the control sits ungrouped under a "Variables" section. `path="Typography/Font"` overrides both: the last segment is the label, the segments before it the group the control is filed under. `label="Font"` names the control without grouping it. Deeper paths (`"Theme/Colors/Primary"`) flatten into one section title ("Theme / Colors").
+
+## Rules
+
+- **Top-level `const` only**, one declaration per annotation, initialized with a plain literal matching the type — the literal is what the editor overwrites.
+- **Not exportable.** References are rewritten per file, so an importer would receive the accessor where it expects the value. Declare the variable in the file that uses it.
+- **Module-level derivation is computed once.** `const doubled = padding * 2` at the top level does not follow the slider — like any module-level expression, it runs once at evaluate. Reads inside JSX props and component bodies are reactive; derive inside the component (or a memo) when the derivation should be live.
+- **An initializer you rewrite into an expression is yours again.** The write-back only touches a declaration that still carries the annotation and still holds a literal; anything else is skipped, like a prop bound to an expression.
+
+## How it behaves
+
+- Changes are debounced into the same write pipeline as canvas edits, land in the undo history (slider bursts coalesce into one step), and never trigger a recompile or remount — the file catches up with the canvas, not the other way round.
+- A hand edit to the file reloads the project as always; the controls rebuild from the new source.
+- Export and capture recompile from source, so the values the inspector settled on are the values a render uses.