Skip to content

The VS Code of video editing, built for agents.

TypeScript

Update JSX elements to PascalCase and enhance type handling in documentation

konstantin-paulus2bb2add67bbf
diff --git a/README.md b/README.md
index 3fa9f518..73aac13b 100644
--- a/README.md
+++ b/README.md
@@ -28,12 +28,12 @@ const TITLES = [
export default function Project() {
return (
- <scene key="intro" name="Intro" width={1920} height={1080} fill="black">
- <video src={motion} width={1920} height={1080} />
- <sequence>
+ <Scene key="intro" name="Intro" width={1920} height={1080} fill="black">
+ <Video src={motion} width={1920} height={1080} />
+ <Sequence>
<For each={TITLES}>
{(t) => (
- <text
+ <Text
textAlign="center"
textBaseline="middle"
fontSize={128}
@@ -44,11 +44,11 @@ export default function Project() {
end={t.end}
>
{t.text}
- </text>
+ </Text>
)}
</For>
- </sequence>
- </scene>
+ </Sequence>
+ </Scene>
);
}
```
diff --git a/apps/cli/reference/README.md b/apps/cli/reference/README.md
index ecc06222..63e06c72 100644
--- a/apps/cli/reference/README.md
+++ b/apps/cli/reference/README.md
@@ -19,7 +19,7 @@ Each feature command has its own file (linked below). The JSX code syntax consum
How the surface is divided:
- Declarative composition happens through `mount`, which renders a Solid JSX project into the canvas (see [jsx/](./jsx/README.md)); `node insert` runs the same pipeline but inserts the rendered nodes into an existing parent entity instead of mounting document roots.
-- Scenes are created declaratively via `mount` (`<scene key="...">`); there is no imperative scene command.
+- Scenes are created declaratively via `mount` (`<Scene key="...">`); there is no imperative scene command.
- AI asset generation (image / video / speech / audio) is declared in the project module (`generate.*`, see [jsx/generate.md](./jsx/generate.md)) and produced on mount. `models` and `voices` list what those declarations can reference.
- Inspecting an existing asset (probe / transcribe / listen / filmstrip / waveform / grab) lives under `media`; writing an asset's original file back to disk is `asset export`.
- Organizing the library lives under `folder`; moving assets between folders is `asset mv`.
diff --git a/apps/cli/reference/fonts.md b/apps/cli/reference/fonts.md
index 34b96b4e..a6299282 100644
--- a/apps/cli/reference/fonts.md
+++ b/apps/cli/reference/fonts.md
@@ -1,6 +1,6 @@
# `dapi fonts`
-Lists local fonts available on this machine. macOS only. Does not require the app to be running. Font families listed here are valid `fontFamily` values on [`<text>`](./jsx/text.md).
+Lists local fonts available on this machine. macOS only. Does not require the app to be running. Font families listed here are valid `fontFamily` values on [`<Text>`](./jsx/text.md).
## Options
diff --git a/apps/cli/reference/jsx/README.md b/apps/cli/reference/jsx/README.md
index 7c3ac8df..105657a6 100644
--- a/apps/cli/reference/jsx/README.md
+++ b/apps/cli/reference/jsx/README.md
@@ -4,7 +4,7 @@ The JSX API defines the code contract for injecting content into the editor via
A project is structured like a SolidJS app: a **root** is established on the canvas (typically a Scene, identified by its key and created if absent) and the project's component tree renders into it. **All positioning is explicit** (`x`, `y`, `width`, `height` in pixels).
-The markup is **pseudo-SVG**: elements like `<rect>`, `<text>`, `<linearGradientPaint>`, and `<colorStop>` mirror SVG's shape-and-paint model, but the tags and props are the editor's own (see [elements.md](./elements.md)), not the SVG spec.
+The markup is **pseudo-SVG**: elements like `<Rect>`, `<Text>`, `<LinearGradientPaint>`, and `<ColorStop>` mirror SVG's shape-and-paint model, but the tags and props are the editor's own (see [elements.md](./elements.md)), not the SVG spec.
The pipeline is driven by two commands: [`dapi mount`](../mount.md) renders the project's roots into the document, and [`dapi node insert`](../node/insert.md) runs the same pipeline into an existing parent entity. [`dapi node patch`](../node/patch.md) assigns the same props on existing nodes.
@@ -16,17 +16,17 @@ The pipeline is driven by two commands: [`dapi mount`](../mount.md) renders the
| [roots.md](./roots.md) | Root elements, `key` identity, canvas placement |
| [elements.md](./elements.md) | Element-to-node mapping, coordinates and sizing, the shared property table |
| [scene.md](./scene.md), [group.md](./group.md), [rect.md](./rect.md), [text.md](./text.md), [video.md](./video.md), [image.md](./image.md), [audio.md](./audio.md) | Per-element props |
-| [paints.md](./paints.md) | `<solidPaint>`, gradients, `<colorStop>` |
-| [html-paint.md](./html-paint.md) | `<html>`: reactive HTML children drawn into the box |
-| [surface-paint.md](./surface-paint.md) | `<surface>`: a ref-provided canvas you draw into, sampled every frame |
+| [paints.md](./paints.md) | `<SolidPaint>`, gradients, `<ColorStop>` |
+| [html-paint.md](./html-paint.md) | `<Html>`: reactive HTML children drawn into the box |
+| [surface-paint.md](./surface-paint.md) | `<Surface>`: a ref-provided canvas you draw into, sampled every frame |
| [media.md](./media.md) | `src` resolution (paths, URLs, asset ids, `AssetRef`) |
| [timing.md](./timing.md) | `start` / `end` / `sourceIn` / `sourceOut`, time formats |
| [keyframes.md](./keyframes.md) | Keyframe animation and easing |
| [animations.md](./animations.md) | The `animations` prop: preset in/out animations |
| [transitions.md](./transitions.md) | The `transition` prop on sequence clips |
-| [sequences.md](./sequences.md) | `<sequence>` sequential placement |
+| [sequences.md](./sequences.md) | `<Sequence>` sequential placement |
| [audio-sync.md](./audio-sync.md) | `syncTo` audio alignment |
-| [captions.md](./captions.md) | `<captions>` and style presets |
+| [captions.md](./captions.md) | `<Captions>` and style presets |
| [generate.md](./generate.md) | Declarative AI asset generation (`generate.*`) |
| [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 |
@@ -66,7 +66,7 @@ const TITLES = [
function Title(props: { text: string; start: Time; end: Time }) {
return (
- <text
+ <Text
textAlign="center"
textBaseline="middle"
fill="#FFFFFF"
@@ -78,31 +78,31 @@ function Title(props: { text: string; start: Time; end: Time }) {
end={props.end}
>
{props.text}
- </text>
+ </Text>
);
}
export default function Project() {
return (
- <scene key="my-first-scene" name="MyFirstScene" fill="black" width={1920} height={1080}>
- <sequence>
- <video src={heroMotion} start={0} end={5} transition={{ type: "dissolve" }} />
- <video src="/Movies/video.mp4" start={5} end={10} sourceIn={12} />
- </sequence>
+ <Scene key="my-first-scene" name="MyFirstScene" fill="black" width={1920} height={1080}>
+ <Sequence>
+ <Video src={heroMotion} start={0} end={5} transition={{ type: "dissolve" }} />
+ <Video src="/Movies/video.mp4" start={5} end={10} sourceIn={12} />
+ </Sequence>
- <image src={hero} x={40} y={40} width={200} height={112} />
+ <Image src={hero} x={40} y={40} width={200} height={112} />
<For each={TITLES}>{(t) => <Title {...t} />}</For>
- <audio
+ <Audio
src="https://my.videoarchive.com/audio/video-xyz.wav"
sourceIn={6}
sourceOut={16}
volume={-6}
/>
- <captions />
- </scene>
+ <Captions />
+ </Scene>
);
}
```
diff --git a/apps/cli/reference/jsx/animations.md b/apps/cli/reference/jsx/animations.md
index 97fdd000..791dfed2 100644
--- a/apps/cli/reference/jsx/animations.md
+++ b/apps/cli/reference/jsx/animations.md
@@ -3,7 +3,7 @@
`animations` declares **preset in/out animations** on a clip: each entry plays over the clip's head (`"in"`) or tail (`"out"`), between the node's static state and the preset's start/end state. For hand-authored motion on individual props, use [keyframes](./keyframes.md); the two compose on distinct properties.
```tsx
-<video
+<Video
src="/Movies/intro.mp4"
start={0} end={8}
animations={[
@@ -40,7 +40,7 @@ The editor's animations inspector options:
| `"scramble"` | Text only: resolves scrambled characters into the text. |
| `"gain"` | Audio only: volume ramp (fade-in/fade-out of the mix). No visual effect. |
-Text types apply only to [`<text>`](./text.md) and [`<captions>`](./captions.md); a mount that puts them elsewhere fails validation.
+Text types apply only to [`<Text>`](./text.md) and [`<Captions>`](./captions.md); a mount that puts them elsewhere fails validation.
## Semantics
diff --git a/apps/cli/reference/jsx/audio-sync.md b/apps/cli/reference/jsx/audio-sync.md
index b5b3a2ef..f867c9c4 100644
--- a/apps/cli/reference/jsx/audio-sync.md
+++ b/apps/cli/reference/jsx/audio-sync.md
@@ -3,10 +3,10 @@
`syncTo` places a node in time by listening instead of arithmetic: the node's audio is cross-correlated against another node's audio, and its `start` is computed so the two recordings coincide on the timeline. It replaces manual offset measurement for multi-recorder material: a lav or voice track against camera audio, two cameras on the same take, two microphones in one room.
```tsx
-<scene key="talk" width={1920} height={1080}>
- <video key="camera" src="/Movies/take-3.mp4" sourceOut={45} muted />
- <audio src="/Movies/lav.wav" syncTo="camera" />
-</scene>
+<Scene key="talk" width={1920} height={1080}>
+ <Video key="camera" src="/Movies/take-3.mp4" sourceOut={45} muted />
+ <Audio src="/Movies/lav.wav" syncTo="camera" />
+</Scene>
```
## Semantics
diff --git a/apps/cli/reference/jsx/audio.md b/apps/cli/reference/jsx/audio.md
index f9146c55..ed0095cb 100644
--- a/apps/cli/reference/jsx/audio.md
+++ b/apps/cli/reference/jsx/audio.md
@@ -1,9 +1,9 @@
-# `<audio>`
+# `<Audio>`
An audio clip: no visual output, no spatial props; carries volume. When timing is omitted, the node fits its natural duration (see [timing.md](./timing.md)).
```tsx
-<audio src="https://my.videoarchive.com/audio/clip.wav" start={2.2} sourceOut={16} volume={-6} />
+<Audio src="https://my.videoarchive.com/audio/clip.wav" start={2.2} sourceOut={16} volume={-6} />
```
## Props
diff --git a/apps/cli/reference/jsx/captions.md b/apps/cli/reference/jsx/captions.md
index 80ae9df9..55e6d5a3 100644
--- a/apps/cli/reference/jsx/captions.md
+++ b/apps/cli/reference/jsx/captions.md
@@ -1,9 +1,9 @@
# Captions
-`<captions />` inside a scene transcribes that scene's audio into a caption node: a styled, timed transcript, produced on import. To caption an already-open scene, insert one with [`dapi node insert`](../node/insert.md).
+`<Captions />` inside a scene transcribes that scene's audio into a caption node: a styled, timed transcript, produced on import. To caption an already-open scene, insert one with [`dapi node insert`](../node/insert.md).
```tsx
-<captions preset="spotlight" colors={["#FF0055"]} />
+<Captions preset="spotlight" colors={["#FF0055"]} />
```
Transcription is **asynchronous and non-blocking**: the caption node is inserted at commit and its transcript attaches once ready. Because it reads the scene's audio, it runs **after** any generated assets in the scene have landed and after [audio sync](./audio-sync.md) has resolved; captioning a generated `voice`/`audio` track transcribes the finished audio at its final placement. The scene must contain an unmuted audio or video source; otherwise the caption node is left empty.
diff --git a/apps/cli/reference/jsx/elements.md b/apps/cli/reference/jsx/elements.md
index 496a8a1e..4a667269 100644
--- a/apps/cli/reference/jsx/elements.md
+++ b/apps/cli/reference/jsx/elements.md
@@ -1,25 +1,25 @@
# Element reference
-Lowercase intrinsic elements map 1:1 onto internal node types:
+PascalCase composition elements map 1:1 onto internal node types (lowercase tags are DOM vocabulary, valid only inside [`<Html>`](./html-paint.md) content):
| Element | Internal node | Notes |
| ------- | ------------- | ----- |
-| [`<scene>`](./scene.md) | **Geometry with Scene tag** | Clips its children to `width`×`height`. Document root only. |
-| [`<group>`](./group.md) | **Geometry with Group tag** | Container with a transform; auto-fits its size from its children. Takes no `fill` or explicit size. |
-| [`<rect>`](./rect.md) | **Geometry with Solid paint** | A filled rectangle; takes only paint children. |
-| [`<video>`](./video.md) | **Geometry with Video paint** | `src` resolves to a video asset. |
-| [`<image>`](./image.md) | **Geometry with Image paint** | `src` resolves to an image asset. |
-| [`<audio>`](./audio.md) | **Geometry with Audio component and a hidden Waveform paint** | No visual output; carries volume. |
-| [`<text>`](./text.md) | **Geometry with Text component** | Children become editable glyphs. |
-| [`<sequence>`](./sequences.md) | **Sequential group** | Track container for back-to-back clips; positions are explicit. |
-| [`<captions>`](./captions.md) | **Caption node** | Transcribes the enclosing scene's audio. |
-| [`<solidPaint>`](./paints.md) (alias `<solid>`) | **Solid paint** | Paint child. |
-| [`<linearGradientPaint>` / `<radialGradientPaint>`](./paints.md) (aliases `<linearGradient>` / `<radialGradient>`) | **Gradient paint** | Paint child; takes `<colorStop>` children. |
-| [`<colorStop>`](./paints.md) (alias `<stop>`) | **Gradient color stop** | Valid only inside gradient paints. |
-| [`<html>`](./html-paint.md) (long form `<htmlPaint>`) | **Html paint** | Paint child whose children are real, reactive HTML drawn by the browser (html-in-canvas, flagged Chromium API). |
-| [`<surface>`](./surface-paint.md) (long form `<surfacePaint>`) | **Surface paint** | Paint child whose `ref` hands you a canvas to draw with any context type (2d, webgl, webgpu); sampled every frame. |
-
-User-defined components are ordinary Solid components; they compose intrinsics and carry no runtime cost. Only intrinsic elements produce entities.
+| [`<Scene>`](./scene.md) | **Geometry with Scene tag** | Clips its children to `width`×`height`. Document root only. |
+| [`<Group>`](./group.md) | **Geometry with Group tag** | Container with a transform; auto-fits its size from its children. Takes no `fill` or explicit size. |
+| [`<Rect>`](./rect.md) | **Geometry with Solid paint** | A filled rectangle; takes only paint children. |
+| [`<Video>`](./video.md) | **Geometry with Video paint** | `src` resolves to a video asset. |
+| [`<Image>`](./image.md) | **Geometry with Image paint** | `src` resolves to an image asset. |
+| [`<Audio>`](./audio.md) | **Geometry with Audio component and a hidden Waveform paint** | No visual output; carries volume. |
+| [`<Text>`](./text.md) | **Geometry with Text component** | Children become editable glyphs. |
+| [`<Sequence>`](./sequences.md) | **Sequential group** | Track container for back-to-back clips; positions are explicit. |
+| [`<Captions>`](./captions.md) | **Caption node** | Transcribes the enclosing scene's audio. |
+| [`<SolidPaint>`](./paints.md) | **Solid paint** | Paint child. |
+| [`<LinearGradientPaint>` / `<RadialGradientPaint>`](./paints.md) | **Gradient paint** | Paint child; takes `<ColorStop>` children. |
+| [`<ColorStop>`](./paints.md) | **Gradient color stop** | Valid only inside gradient paints. |
+| [`<Html>`](./html-paint.md) (long form `<HtmlPaint>`) | **Html paint** | Paint child whose children are real, reactive HTML drawn by the browser (html-in-canvas, flagged Chromium API). |
+| [`<Surface>`](./surface-paint.md) (long form `<SurfacePaint>`) | **Surface paint** | Paint child whose `ref` hands you a canvas to draw with any context type (2d, webgl, webgpu); sampled every frame. |
+
+User-defined components are ordinary Solid components; they compose the elements above and carry no runtime cost. Only the elements above produce entities.
## Coordinates and sizing
@@ -41,7 +41,7 @@ All visual elements accept:
| `opacity` | `Animatable<number>` | `1` | `0`-`1`. |
| `cornerRadius` | `Animatable<number>` | `0` | Uniform corner radius, px. |
| `start`, `end`, `sourceIn`, `sourceOut` | `Time` | see [timing.md](./timing.md) | Temporal placement. |
-| `transition` | `TransitionSpec \| null` | none | Transition into the next clip; direct children of `<sequence>` only (see [transitions.md](./transitions.md)). |
+| `transition` | `TransitionSpec \| null` | none | Transition into the next clip; direct children of `<Sequence>` only (see [transitions.md](./transitions.md)). |
| `animations` | `AnimationSpec[]` | none | Preset in/out animations over the clip's head and tail (see [animations.md](./animations.md)). |
`Animatable` props also take a keyframe list; see [keyframes.md](./keyframes.md).
diff --git a/apps/cli/reference/jsx/errors.md b/apps/cli/reference/jsx/errors.md
index 121a5cda..95583112 100644
--- a/apps/cli/reference/jsx/errors.md
+++ b/apps/cli/reference/jsx/errors.md
@@ -5,7 +5,7 @@ Where each [pipeline](./README.md#pipeline) stage fails, and with what effect:
| Stage | Where it surfaces | Effect |
| ----- | ----------------- | ------ |
| Compile (syntax/type-stripping/bundling) | CLI stderr, exit 1 | App never contacted. |
-| Evaluate / mount (thrown errors, invalid props, invalid root: e.g. nested `<scene>`, a root element without `key`, missing `src`, malformed `Time`, an unknown or cyclic `syncTo` key, `syncTo` combined with `start`) | CLI stderr, exit 1 | Staging root discarded; **nothing inserted**. |
+| Evaluate / mount (thrown errors, invalid props, invalid root: e.g. nested `<Scene>`, a root element without `key`, missing `src`, malformed `Time`, an unknown or cyclic `syncTo` key, `syncTo` combined with `start`) | CLI stderr, exit 1 | Staging root discarded; **nothing inserted**. |
| Generation (per-model constraints: `aspectRatio`, `duration`, feature flags) | CLI stderr, exit 1, after every generation settled | No rollback; the mounted tree stays committed. The affected placeholder stops showing its generating state and is left without a paint. |
| Sync (a side without a decodable audio track, or no reliable alignment) | CLI stderr, exit 1, after every alignment settled | No rollback; the tree stays committed and the node keeps its default placement. |
diff --git a/apps/cli/reference/jsx/generate.md b/apps/cli/reference/jsx/generate.md
index febe3c00..3df5cf90 100644
--- a/apps/cli/reference/jsx/generate.md
+++ b/apps/cli/reference/jsx/generate.md
@@ -22,10 +22,10 @@ const heroMotion = generate.video({
export default function Project() {
return (
- <scene key="intro" name="Intro" width={1920} height={1080}>
- <video src={heroMotion} start={0} end={5} />
- <image src={hero} x={40} y={40} width={200} height={112} />
- </scene>
+ <Scene key="intro" name="Intro" width={1920} height={1080}>
+ <Video src={heroMotion} start={0} end={5} />
+ <Image src={hero} x={40} y={40} width={200} height={112} />
+ </Scene>
);
}
```
diff --git a/apps/cli/reference/jsx/group.md b/apps/cli/reference/jsx/group.md
index cf80c4cb..3a6147d6 100644
--- a/apps/cli/reference/jsx/group.md
+++ b/apps/cli/reference/jsx/group.md
@@ -1,11 +1,11 @@
-# `<group>`
+# `<Group>`
A container with a transform but no dimensions of its own: a group derives its box from its children, and they are positioned relative to it.
```tsx
-<group x={100} y={100}>
+<Group x={100} y={100}>
{/* children */}
-</group>
+</Group>
```
## Props
diff --git a/apps/cli/reference/jsx/html-paint.md b/apps/cli/reference/jsx/html-paint.md
index 7a30d762..a6700f41 100644
--- a/apps/cli/reference/jsx/html-paint.md
+++ b/apps/cli/reference/jsx/html-paint.md
@@ -1,19 +1,19 @@
-# `<html>`
+# `<Html>`
-A paint whose children are **real HTML** (long form: `<htmlPaint>`). The browser lays them out at the parent geometry's box size and the result is drawn into the box via the [html-in-canvas](https://github.com/WICG/html-in-canvas) API. Use it for content that is painful to build from `<rect>` and `<text>`: styled cards, tables, code blocks, flex/grid layouts.
+A paint whose children are **real HTML** (long form: `<HtmlPaint>`). The browser lays them out at the parent geometry's box size and the result is drawn into the box via the [html-in-canvas](https://github.com/WICG/html-in-canvas) API. Use it for content that is painful to build from `<Rect>` and `<Text>`: styled cards, tables, code blocks, flex/grid layouts.
```tsx
-<rect x={40} y={40} width={800} height={120} cornerRadius={24}>
- <html>
+<Rect x={40} y={40} width={800} height={120} cornerRadius={24}>
+ <Html>
<div style="display:flex;align-items:center;gap:16px;height:100%;
background:#111;color:#fff;font:500 40px Inter;padding:0 32px;">
<span style="color:#7c9cff;">01</span> Introduction
</div>
- </html>
-</rect>
+ </Html>
+</Rect>
```
-Inside `<html>`, every tag is a DOM element: names the editor also uses (`<rect>`, `<text>`, and inside `<svg>` also `<linearGradient>` and `<stop>`) become plain HTML/SVG here, because tags resolve by environment. HTML tags remain invalid outside it.
+Inside `<Html>`, every lowercase tag is a DOM element — the case decides the environment: PascalCase tags are composition elements, lowercase tags are HTML/SVG. Lowercase tags remain invalid outside `<Html>` content.
## Reactivity
@@ -23,11 +23,11 @@ The children are part of the project's Solid graph: signals in attributes and te
const [count, setCount] = createSignal(0);
setInterval(() => setCount((c) => c + 1), 1000);
-<rect width={400} height={200}>
- <html>
+<Rect width={400} height={200}>
+ <Html>
<div style="font:700 96px Inter;color:#fff;">{count()}</div>
- </html>
-</rect>
+ </Html>
+</Rect>
```
## Props
@@ -40,7 +40,7 @@ Like all paints it stacks with siblings in document order and clips to the paren
## Requirements and limitations
-- Requires Chromium's html-in-canvas API, currently behind `chrome://flags/#canvas-draw-element`. Mounting `<html>` fails with an explicit error when the API is unavailable.
+- Requires Chromium's html-in-canvas API, currently behind `chrome://flags/#canvas-draw-element`. Mounting `<Html>` fails with an explicit error when the API is unavailable.
- Markup renders with the page's fonts and full CSS. Event handlers are dropped — the content is painted, not interactive.
- The content lives only as long as its mount: it is not persisted and does not render in exports yet.
- CSS animations in the markup play on the wall clock, not the composition playhead. Animate the parent element's props with [keyframes](./keyframes.md) for frame-accurate motion.
diff --git a/apps/cli/reference/jsx/image.md b/apps/cli/reference/jsx/image.md
index 8d36b50c..39b9547b 100644
--- a/apps/cli/reference/jsx/image.md
+++ b/apps/cli/reference/jsx/image.md
@@ -1,9 +1,9 @@
-# `<image>`
+# `<Image>`
An image. `src` resolves to an image asset (see [media.md](./media.md)).
```tsx
-<image src="/photo.jpg" x={40} y={40} width={200} height={112} />
+<Image src="/photo.jpg" x={40} y={40} width={200} height={112} />
```
## Props
diff --git a/apps/cli/reference/jsx/keyframes.md b/apps/cli/reference/jsx/keyframes.md
index e7e2904f..52a016a9 100644
--- a/apps/cli/reference/jsx/keyframes.md
+++ b/apps/cli/reference/jsx/keyframes.md
@@ -3,7 +3,7 @@
Animatable props accept a keyframe list in place of a static value:
```tsx
-<image
+<Image
src="/photo.jpg"
start={0} end={5}
x={[
diff --git a/apps/cli/reference/jsx/lifecycle.md b/apps/cli/reference/jsx/lifecycle.md
index 69f7ff57..7cbc8d69 100644
--- a/apps/cli/reference/jsx/lifecycle.md
+++ b/apps/cli/reference/jsx/lifecycle.md
@@ -2,9 +2,9 @@
## A mount stays live
-After `dapi mount` returns, its reactive graph keeps running: signals, effects, timers, and [`useTicker`](#useticker) keep driving the mounted entities. Updates land in the document immediately (not as undo steps) — prop writes, conditional inserts and removals (`<Show>`, `<For>`), text, and reactive `src` swaps including `generate.*`. The materialized nodes are ordinary editable entities; asset generation is owned by the engine. `syncTo` and new `<captions>` are mount-only and throw if changed after commit. A run ends when a later `mount` claims one of its root keys (swapping the entities and disposing the old graph) or the project closes.
+After `dapi mount` returns, its reactive graph keeps running: signals, effects, timers, and [`useTicker`](#useticker) keep driving the mounted entities. Updates land in the document immediately (not as undo steps) — prop writes, conditional inserts and removals (`<Show>`, `<For>`), text, and reactive `src` swaps including `generate.*`. The materialized nodes are ordinary editable entities; asset generation is owned by the engine. `syncTo` and new `<Captions>` are mount-only and throw if changed after commit. A run ends when a later `mount` claims one of its root keys (swapping the entities and disposing the old graph) or the project closes.
-The compiled module is persisted with the document and re-executed in every context: reload rebuilds the graph and its runtime hosts (`<surface>`/`<html>`), and export and capture drive the ticker across the frames they render. Re-execution binds to the existing entities rather than re-authoring them, so hand-edits survive; it rewrites only the props your effects animate. This requires the module's structure to be deterministic: `Math.random()` and `Date.now()` must not decide element counts or `<Show>`/`<For>` branches (using them inside an effect is fine).
+The compiled module is persisted with the document and re-executed in every context: reload rebuilds the graph and its runtime hosts (`<Surface>`/`<Html>`), and export and capture drive the ticker across the frames they render. Re-execution binds to the existing entities rather than re-authoring them, so hand-edits survive; it rewrites only the props your effects animate. This requires the module's structure to be deterministic: `Math.random()` and `Date.now()` must not decide element counts or `<Show>`/`<For>` branches (using them inside an effect is fine).
`node insert` renders into an existing parent and is not persisted or kept live.
@@ -18,10 +18,10 @@ import { useTicker } from "@diffusionstudio/jsx";
export default function Project() {
const { time, frame } = useTicker();
return (
- <scene key="hud" width={1920} height={1080}>
- <text fontSize={80}>{`frame ${frame()}`}</text>
- <rect x={860 + Math.sin(time() * 4) * 200} y={490} width={100} height={100} fill="#f43" />
- </scene>
+ <Scene key="hud" width={1920} height={1080}>
+ <Text fontSize={80}>{`frame ${frame()}`}</Text>
+ <Rect x={860 + Math.sin(time() * 4) * 200} y={490} width={100} height={100} fill="#f43" />
+ </Scene>
);
}
```
@@ -39,7 +39,7 @@ The values respect play, pause, scrubbing, looping, and playback speed, which wa
## `useFile`
-Resolves a [`src`](./media.md) (path, asset id, URL, or a `generate.*` ref) to its `File`, so effects can read the raw bytes: draw a library image onto a [`<surface>`](./surface-paint.md), parse a data file, decode audio. The module is sandboxed and can't fetch a path or asset id itself, so resolution goes through the host, exactly as `src` does.
+Resolves a [`src`](./media.md) (path, asset id, URL, or a `generate.*` ref) to its `File`, so effects can read the raw bytes: draw a library image onto a [`<Surface>`](./surface-paint.md), parse a data file, decode audio. The module is sandboxed and can't fetch a path or asset id itself, so resolution goes through the host, exactly as `src` does.
```tsx
import { createSignal, createEffect } from "solid-js";
@@ -57,7 +57,7 @@ function Logo() {
ctx.drawImage(await createImageBitmap(f), 0, 0, el.width, el.height);
});
- return <surface ref={setCanvas} width={640} height={360} />;
+ return <Surface ref={setCanvas} width={640} height={360} />;
}
```
diff --git a/apps/cli/reference/jsx/media.md b/apps/cli/reference/jsx/media.md
index 06a827c0..7d11bb7e 100644
--- a/apps/cli/reference/jsx/media.md
+++ b/apps/cli/reference/jsx/media.md
@@ -1,6 +1,6 @@
# Media source resolution
-`src` (on [`<video>`](./video.md), [`<image>`](./image.md), [`<audio>`](./audio.md)) accepts:
+`src` (on [`<Video>`](./video.md), [`<Image>`](./image.md), [`<Audio>`](./audio.md)) accepts:
- **Global path**: e.g. `"/Movies/video.mp4"`, resolved against the user's OS.
- **Remote URL**: e.g. `"https://my.videoarchive.com/audio/clip.wav"`, registered as a remote asset.
diff --git a/apps/cli/reference/jsx/module.md b/apps/cli/reference/jsx/module.md
index d6d76dee..50096d60 100644
--- a/apps/cli/reference/jsx/module.md
+++ b/apps/cli/reference/jsx/module.md
@@ -3,15 +3,19 @@
The entry file is a standard Solid component module:
```tsx
+import { Scene } from "@diffusionstudio/jsx";
+
export default function Project() {
return (
- <scene key="intro" name="Intro" fill="black" width={1920} height={1080}>
+ <Scene key="intro" name="Intro" fill="black" width={1920} height={1080}>
{/* ... */}
- </scene>
+ </Scene>
);
}
```
+The element import is optional at runtime — the compiler auto-imports PascalCase elements — but it makes the file typecheck (see [Types and tooling](#types-and-tooling)).
+
The component receives no props; which document node each rendered root maps onto is declared in the JSX itself via `key` (see [roots.md](./roots.md)).
## Module environment
@@ -42,7 +46,7 @@ A `dapi.config.json` in the working directory pins versions or redirects userlan
## Types and tooling
-`@diffusionstudio/jsx` ships the JSX namespace (intrinsic elements and props), `Time`, `AssetRef`, and the `generate` namespace. For editor IntelliSense and typechecking in a project folder:
+`@diffusionstudio/jsx` ships the composition elements and their prop types, the JSX namespace, `Time`, `AssetRef`, and the `generate` namespace. The PascalCase elements auto-import at compile time, so project files use them without import statements. For editor IntelliSense and typechecking in a project folder:
```json
{
@@ -53,6 +57,6 @@ A `dapi.config.json` in the working directory pins versions or redirects userlan
}
```
-The CLI does not typecheck; types are stripped at compile time. Run `tsc --noEmit` in the project folder for type safety.
+The CLI does not typecheck; types are stripped at compile time. Run `tsc --noEmit` in the project folder for type safety. The compile-time auto-import is invisible to TypeScript, so for typechecking import the elements you use explicitly (`import { Scene, Text } from "@diffusionstudio/jsx"`) — explicit imports and the auto-import behave identically at runtime.
Userland packages resolve from a CDN at runtime, so they need no runtime install, but the editor still wants their type declarations. For IntelliSense on a library, install it (or its `@types/…`) as a **dev-only** dependency (`npm i -D three`); it is used purely for typechecking and never bundled or shipped.
diff --git a/apps/cli/reference/jsx/paints.md b/apps/cli/reference/jsx/paints.md
index 69e9cc1b..642f1da8 100644
--- a/apps/cli/reference/jsx/paints.md
+++ b/apps/cli/reference/jsx/paints.md
@@ -3,27 +3,25 @@
Internally a node's fill is not a property but a **paint child**: a sub-entity appended to the geometry, exactly like the editor's fill list. The `fill` prop is shorthand for a solid paint; declaring paints as JSX children exposes the full model, including gradients:
```tsx
-<rect width={640} height={360} cornerRadius={24}>
- <linearGradientPaint rotation={90}>
- <colorStop offset={0} color="#FF0055" />
- <colorStop offset={1} color="#0055FF" />
- </linearGradientPaint>
-</rect>
+<Rect width={640} height={360} cornerRadius={24}>
+ <LinearGradientPaint rotation={90}>
+ <ColorStop offset={0} color="#FF0055" />
+ <ColorStop offset={1} color="#0055FF" />
+ </LinearGradientPaint>
+</Rect>
```
-Paint elements are valid inside any filled visual element (`<rect>`, `<scene>`, `<text>`, `<video>`, `<image>`); a `<group>` has no fill of its own, so it takes none. Multiple paints stack in document order; later paints render on top, and a paint child on a `<video>`/`<image>` draws over the media paint created by `src`.
+Paint elements are valid inside any filled visual element (`<Rect>`, `<Scene>`, `<Text>`, `<Video>`, `<Image>`); a `<Group>` has no fill of its own, so it takes none. Multiple paints stack in document order; later paints render on top, and a paint child on a `<Video>`/`<Image>` draws over the media paint created by `src`.
-| Element | Alias | Props | Meaning |
-| ------- | ----- | ----- | ------- |
-| `<solidPaint>` | `<solid>` | `color` (**required**), `opacity` | Solid fill; equivalent to the `fill` prop. |
-| `<linearGradientPaint>` | `<linearGradient>` | `rotation`, `opacity` | Linear gradient across the parent's box; `rotation` in degrees, `0` = left to right. |
-| `<radialGradientPaint>` | `<radialGradient>` | `rotation`, `opacity` | Radial gradient centered in the parent's box. |
-| `<colorStop>` | `<stop>` | `offset` (**required**, `0`-`1`), `color` (**required**), `opacity` | Gradient color stop. Valid only inside gradient paints, which take no other children. |
-| [`<html>`](./html-paint.md) | `<htmlPaint>` | `opacity`, HTML children | Reactive HTML laid out and drawn into the parent's box (flagged Chromium API). |
-| [`<surface>`](./surface-paint.md) | `<surfacePaint>` | `opacity`, `ref` (**required**) | A canvas your `ref` callback draws into (any context type), sampled into the parent's box every frame. |
-
-Both names of a pair work everywhere; names shared with SVG (`<linearGradient>`, `<stop>`) are unambiguous because tags resolve by environment: inside an [`<html>`](./html-paint.md) paint they are the real SVG elements, anywhere else the paints. `<html>` is never a DOM tag — in a composition it always means the element; `<surface>` doesn't collide with a DOM tag at all.
+| Element | Props | Meaning |
+| ------- | ----- | ------- |
+| `<SolidPaint>` | `color` (**required**), `opacity` | Solid fill; equivalent to the `fill` prop. |
+| `<LinearGradientPaint>` | `rotation`, `opacity` | Linear gradient across the parent's box; `rotation` in degrees, `0` = left to right. |
+| `<RadialGradientPaint>` | `rotation`, `opacity` | Radial gradient centered in the parent's box. |
+| `<ColorStop>` | `offset` (**required**, `0`-`1`), `color` (**required**), `opacity` | Gradient color stop. Valid only inside gradient paints, which take no other children. |
+| [`<HtmlPaint>`](./html-paint.md) | `opacity`, HTML children | Reactive HTML laid out and drawn into the parent's box (flagged Chromium API). `<Html>` is shorthand for a `<Rect>` carrying one. |
+| [`<SurfacePaint>`](./surface-paint.md) | `opacity`, `ref` (**required**) | A canvas your `ref` callback draws into (any context type), sampled into the parent's box every frame. `<Surface>` is shorthand for a `<Rect>` carrying one. |
Colors accept any CSS color; alpha is ignored (use `opacity`). `color`, `opacity`, and `offset` are animatable (see [keyframes.md](./keyframes.md)), so gradients can animate. Paints have no spatial or timing props and cannot be document roots.
-Paints are live entities like any other: patch them with [`dapi node patch`](../node/patch.md), and add a stop to an existing gradient with [`dapi node insert`](../node/insert.md) (`node insert <paintId> '<colorStop offset={0.5} color="#FF0055" />'`).
+Paints are live entities like any other: patch them with [`dapi node patch`](../node/patch.md), and add a stop to an existing gradient with [`dapi node insert`](../node/insert.md) (`node insert <paintId> '<ColorStop offset={0.5} color="#FF0055" />'`).
diff --git a/apps/cli/reference/jsx/rect.md b/apps/cli/reference/jsx/rect.md
index 919a4014..a0f7a253 100644
--- a/apps/cli/reference/jsx/rect.md
+++ b/apps/cli/reference/jsx/rect.md
@@ -1,9 +1,9 @@
-# `<rect>`
+# `<Rect>`
A filled rectangle. Takes only [paint children](./paints.md); use `cornerRadius` for rounded corners.
```tsx
-<rect x={40} y={40} width={640} height={360} cornerRadius={24} fill="#FF0055" />
+<Rect x={40} y={40} width={640} height={360} cornerRadius={24} fill="#FF0055" />
```
## Props
diff --git a/apps/cli/reference/jsx/roots.md b/apps/cli/reference/jsx/roots.md
index 580dd57f..64dab56c 100644
--- a/apps/cli/reference/jsx/roots.md
+++ b/apps/cli/reference/jsx/roots.md
@@ -1,20 +1,20 @@
# Roots
-A mount renders one or more root elements (a fragment of roots is allowed) and **refreshes the document**: like reloading a webpage, re-running a mount rebuilds its roots in place instead of accumulating copies; a rendered root with no existing node to replace is created. Roots are typically [`<scene>`](./scene.md) elements, but any element can be a root (e.g. a bare `<rect>`). Every top-level element must declare its identity with a `key`:
+A mount renders one or more root elements (a fragment of roots is allowed) and **refreshes the document**: like reloading a webpage, re-running a mount rebuilds its roots in place instead of accumulating copies; a rendered root with no existing node to replace is created. Roots are typically [`<Scene>`](./scene.md) elements, but any element can be a root (e.g. a bare `<Rect>`). Every top-level element must declare its identity with a `key`:
| Identity | Contract |
| -------- | -------- |
-| `<scene key="intro">` | Rebuilds the existing node carrying the same key, or creates it (storing the key) if none does. Keyed nodes in the document that the render no longer produces are **deleted**; the mount owns its keyed roots. |
+| `<Scene key="intro">` | Rebuilds the existing node carrying the same key, or creates it (storing the key) if none does. Keyed nodes in the document that the render no longer produces are **deleted**; the mount owns its keyed roots. |
-Keys must be unique within a render, and rebuilding keeps the node's entity id and canvas position. Nodes without a key (e.g. hand-made scratch scenes) are never touched. The **first** rendered root becomes the active scene. Assigning a `name` alongside the key (e.g. `<scene key="intro" name="Intro">`) is recommended: the key identifies the node across mounts, the name labels it in the editor.
+Keys must be unique within a render, and rebuilding keeps the node's entity id and canvas position. Nodes without a key (e.g. hand-made scratch scenes) are never touched. The **first** rendered root becomes the active scene. Assigning a `name` alongside the key (e.g. `<Scene key="intro" name="Intro">`) is recommended: the key identifies the node across mounts, the name labels it in the editor.
-`<scene>` is valid **only** at the document root; scenes do not nest.
+`<Scene>` is valid **only** at the document root; scenes do not nest.
[`dapi node insert`](../node/insert.md) skips this reconciliation entirely: its roots take no `key` and every run inserts fresh entities.
## Canvas placement
-The canvas holds many roots, but a root's position on the canvas is an **editor concern, not part of the composition**: `<scene>` has no `x`/`y`, and a project describes content, not canvas arrangement.
+The canvas holds many roots, but a root's position on the canvas is an **editor concern, not part of the composition**: `<Scene>` has no `x`/`y`, and a project describes content, not canvas arrangement.
- **Rebuilt roots** (matched by `key`) keep their existing canvas position.
- **New roots** are placed automatically: in the nearest empty space around the current viewport center, gapped so they never overlap existing content (the same auto-placement the editor uses when generating onto the canvas). A mount that creates multiple roots places them side by side in render order.
diff --git a/apps/cli/reference/jsx/scene.md b/apps/cli/reference/jsx/scene.md
index 4c9bc7ba..b7002a84 100644
--- a/apps/cli/reference/jsx/scene.md
+++ b/apps/cli/reference/jsx/scene.md
@@ -1,11 +1,11 @@
-# `<scene>`
+# `<Scene>`
The composition root: clips its children to `width`×`height`. Valid **only** at the document top level; scenes do not nest. The first rendered root becomes the active scene (see [roots.md](./roots.md)).
```tsx
-<scene key="intro" name="Intro" fill="black" width={1920} height={1080}>
+<Scene key="intro" name="Intro" fill="black" width={1920} height={1080}>
{/* children */}
-</scene>
+</Scene>
```
## Props
@@ -17,4 +17,4 @@ The composition root: clips its children to `width`×`height`. Valid **only** at
| `name` | `string` | none | Scene name (recommended). |
| `fill` | `string` | none | Background fill, any CSS color (alpha is ignored). |
-No timing or transform props. Canvas position is an editor concern; `<scene>` has no `x`/`y`.
+No timing or transform props. Canvas position is an editor concern; `<Scene>` has no `x`/`y`.
diff --git a/apps/cli/reference/jsx/sequences.md b/apps/cli/reference/jsx/sequences.md
index 1ef441da..5bce9f65 100644
--- a/apps/cli/reference/jsx/sequences.md
+++ b/apps/cli/reference/jsx/sequences.md
@@ -1,13 +1,13 @@
# Sequences
-`<sequence>` is a track-like container for back-to-back clips. It carries no timing of its own and **does not position its children at mount** — give each child an explicit `start` (see [timing.md](./timing.md)). What it adds is clip-to-clip [transitions](./transitions.md) on direct children, and, in the editor, a non-overlapping invariant: dragging or regrouping clips trims or removes whatever they land on.
+`<Sequence>` is a track-like container for back-to-back clips. It carries no timing of its own and **does not position its children at mount** — give each child an explicit `start` (see [timing.md](./timing.md)). What it adds is clip-to-clip [transitions](./transitions.md) on direct children, and, in the editor, a non-overlapping invariant: dragging or regrouping clips trims or removes whatever they land on.
```tsx
-<sequence>
- <video src="/Movies/intro.mp4" start={0} end={12} /> {/* timeline 0–12 */}
- <video src="/Movies/main.mp4" start={12} end="02:30" sourceIn={5} /> {/* timeline 12–2:30, source from 5 s */}
- <video src="/Movies/outro.mp4" start="02:30" /> {/* from 2:30, plays to its natural end */}
-</sequence>
+<Sequence>
+ <Video src="/Movies/intro.mp4" start={0} end={12} /> {/* timeline 0–12 */}
+ <Video src="/Movies/main.mp4" start={12} end="02:30" sourceIn={5} /> {/* timeline 12–2:30, source from 5 s */}
+ <Video src="/Movies/outro.mp4" start="02:30" /> {/* from 2:30, plays to its natural end */}
+</Sequence>
```
The next clip's `start` must match the previous clip's on-timeline end — its `end`, or from the source side `start + (sourceOut - sourceIn)`. Here `main` ends at `02:30`, so `outro` starts there. Giving `main` an `end` places the next cut at a round timeline mark without computing source lengths.
diff --git a/apps/cli/reference/jsx/surface-paint.md b/apps/cli/reference/jsx/surface-paint.md
index da96745a..f0837675 100644
--- a/apps/cli/reference/jsx/surface-paint.md
+++ b/apps/cli/reference/jsx/surface-paint.md
@@ -1,9 +1,9 @@
-# `<surface>`
+# `<Surface>`
-A paint backed by a **canvas you draw yourself** (long form: `<surfacePaint>`). The `ref` callback receives a detached `HTMLCanvasElement`; draw into it with any context type — 2d, webgl, webgpu — and the engine samples the bitmap every frame, stretching it into the parent geometry's box. Use it for procedural graphics and for external renderers (three.js, p5, chart libraries) that want to own a canvas.
+A paint backed by a **canvas you draw yourself** (long form: `<SurfacePaint>`). The `ref` callback receives a detached `HTMLCanvasElement`; draw into it with any context type — 2d, webgl, webgpu — and the engine samples the bitmap every frame, stretching it into the parent geometry's box. Use it for procedural graphics and for external renderers (three.js, p5, chart libraries) that want to own a canvas.
```tsx
-<surface x={40} y={40} width={640} height={360} cornerRadius={24}
+<Surface x={40} y={40} width={640} height={360} cornerRadius={24}
ref={(el) => {
const ctx = el.getContext("2d")!;
ctx.fillStyle = "#111";
@@ -14,21 +14,21 @@ A paint backed by a **canvas you draw yourself** (long form: `<surfacePaint>`).
}} />
```
-`<surfacePaint ref={...}>` is the paint child form, valid inside any filled visual element; `<surface>` is a rectangle carrying one, with all [common props](./elements.md#common-props).
+`<SurfacePaint ref={...}>` is the paint child form, valid inside any filled visual element; `<Surface>` is a rectangle carrying one, with all [common props](./elements.md#common-props).
## The ref and the bitmap
- The ref runs **once**, when the paint materializes, inside the mount's reactive owner — `createEffect`, `onCleanup`, and [`useTicker`](./lifecycle.md) all work inside it.
-- **Callback form only** (`ref={(el) => ...}`). Variable refs (`let el; <surface ref={el} />`) receive a renderer-internal node, not the canvas.
+- **Callback form only** (`ref={(el) => ...}`). Variable refs (`let el; <Surface ref={el} />`) receive a renderer-internal node, not the canvas.
- The bitmap is allocated at the element's box size (in composition pixels) **before the ref runs**; after that the engine never touches it — the bitmap belongs to your code. Resize it yourself (`el.width = ...`, or an external renderer's own API) for higher resolution; the bitmap is stretched into the box every frame either way, so an animated box scales pixels rather than re-rasterizing.
-- Unlike [`<html>`](./html-paint.md) no flagged browser API is needed, and the sampled pixels render in exports.
+- Unlike [`<Html>`](./html-paint.md) no flagged browser API is needed, and the sampled pixels render in exports.
## Reactivity
The engine samples the canvas every frame, so anything you draw shows up on the next frame. A [`dapi mount`](../mount.md) stays live, so the reactive graph keeps running: create effects in the ref to redraw from signals, or drive frame-accurate motion from the ticker's composition time:
```tsx
-<surface width={400} height={400}
+<Surface width={400} height={400}
ref={(el) => {
const ctx = el.getContext("2d")!;
const { time } = useTicker();
@@ -49,7 +49,7 @@ Because the ticker follows the playhead, ticker-driven drawing stays frame-accur
Anything that accepts an existing canvas plugs in directly; a detached canvas is fine for WebGL:
```tsx
-<surface width={1280} height={720}
+<Surface width={1280} height={720}
ref={(el) => {
const renderer = new THREE.WebGLRenderer({
canvas: el,
@@ -77,7 +77,7 @@ Anything that accepts an existing canvas plugs in directly; a detached canvas is
| `ref` | `(canvas: HTMLCanvasElement) => void` | **required** | Receives the backing canvas at materialization. |
| `opacity` | `Animatable<number>` | `1` | Paint opacity, `0`-`1`. |
-Like all paints it stacks with siblings in document order and clips to the parent's box (including `cornerRadius`). `<surfacePaint>` takes no children.
+Like all paints it stacks with siblings in document order and clips to the parent's box (including `cornerRadius`). `<SurfacePaint>` takes no children.
## Persistence and export
@@ -87,4 +87,4 @@ The compiled module is persisted with the document, so the drawing is reproducib
- Duplicating or copy-pasting a mounted surface yields a static copy (the drawing does not re-run for the copy); re-mount to get a fresh animated instance.
- Only the `ref` attribute form on the element itself is routed; refs inside spread props are not.
-- A real DOM `<canvas>` is not available inside [`<html>`](./html-paint.md) content — its pixels don't survive the html-in-canvas rasterization. Use `<surface>` for hand-drawn graphics instead.
+- A real DOM `<canvas>` is not available inside [`<Html>`](./html-paint.md) content — its pixels don't survive the html-in-canvas rasterization. Use `<Surface>` for hand-drawn graphics instead.
diff --git a/apps/cli/reference/jsx/text.md b/apps/cli/reference/jsx/text.md
index 6803248c..debc1ea7 100644
--- a/apps/cli/reference/jsx/text.md
+++ b/apps/cli/reference/jsx/text.md
@@ -1,11 +1,11 @@
-# `<text>`
+# `<Text>`
-A text node; children become editable glyphs. Because the box defaults to the parent's box, a centered full-frame title is simply `<text textAlign="center" textBaseline="middle">…</text>`.
+A text node; children become editable glyphs. Because the box defaults to the parent's box, a centered full-frame title is simply `<Text textAlign="center" textBaseline="middle">…</Text>`.
```tsx
-<text fill="#FFFFFF" fontSize={128} fontWeight="bold" textAlign="center" textBaseline="middle">
+<Text fill="#FFFFFF" fontSize={128} fontWeight="bold" textAlign="center" textBaseline="middle">
Hello World
-</text>
+</Text>
```
## Props
diff --git a/apps/cli/reference/jsx/timing.md b/apps/cli/reference/jsx/timing.md
index de47d2d7..d7d065b5 100644
--- a/apps/cli/reference/jsx/timing.md
+++ b/apps/cli/reference/jsx/timing.md
@@ -13,15 +13,15 @@ Timing splits the two independent questions a clip answers: **where it sits on t
- `start` / `end` place the clip on the parent timeline. `sourceIn` / `sourceOut` select which part of the source plays. On-timeline duration always equals the played source length, so `end - start == sourceOut - sourceIn`.
- **`end` and `sourceOut` are two spellings of the same out edge** — the clip's end in timeline time (`end`) versus source time (`sourceOut`). Set one; the last one set wins.
-- Sourceless nodes (`<rect>`, `<group>`, `<text>`) have no footage to trim, so you place them with `start` / `end` alone.
+- Sourceless nodes (`<Rect>`, `<Group>`, `<Text>`) have no footage to trim, so you place them with `start` / `end` alone.
- Instead of setting `start`, a media node can derive its placement from another node's audio with `syncTo` (see [audio-sync.md](./audio-sync.md)).
-- If timing is omitted, a media node fits its natural duration at `start` 0, and a group auto-fits its children. A [`<sequence>`](./sequences.md) does not position its children for you: give each an explicit `start` (the next clip's `start` is the previous clip's end).
+- If timing is omitted, a media node fits its natural duration at `start` 0, and a group auto-fits its children. A [`<Sequence>`](./sequences.md) does not position its children for you: give each an explicit `start` (the next clip's `start` is the previous clip's end).
> Examples:
-> - `<rect start={2} end={5} fill="red" />` — a rectangle on screen from timeline second 2 to 5.
-> - `<video start={5} sourceIn={10} sourceOut={20} />` — plays source seconds 10–20 (a 10-second clip) beginning at timeline second 5.
-> - `<video start={2} end={5} sourceIn={10} />` — the same source starting at 10 s, stretched to fill the timeline window 2–5 (so it plays source 10–13).
-> - `<video start={0} sourceIn={1} />` — trims the first second off the head and places the clip at the top of the timeline.
+> - `<Rect start={2} end={5} fill="red" />` — a rectangle on screen from timeline second 2 to 5.
+> - `<Video start={5} sourceIn={10} sourceOut={20} />` — plays source seconds 10–20 (a 10-second clip) beginning at timeline second 5.
+> - `<Video start={2} end={5} sourceIn={10} />` — the same source starting at 10 s, stretched to fill the timeline window 2–5 (so it plays source 10–13).
+> - `<Video start={0} sourceIn={1} />` — trims the first second off the head and places the clip at the top of the timeline.
## Time formats
diff --git a/apps/cli/reference/jsx/transitions.md b/apps/cli/reference/jsx/transitions.md
index 1017929e..7b9bddb3 100644
--- a/apps/cli/reference/jsx/transitions.md
+++ b/apps/cli/reference/jsx/transitions.md
@@ -1,13 +1,13 @@
# Transitions
-`transition` declares a transition **into the next clip**, set on the **outgoing** clip and rendered centered on the cut. It is valid only on direct children of [`<sequence>`](./sequences.md).
+`transition` declares a transition **into the next clip**, set on the **outgoing** clip and rendered centered on the cut. It is valid only on direct children of [`<Sequence>`](./sequences.md).
```tsx
-<sequence>
- <video src="/Movies/intro.mp4" start={0} end={12} transition={{ type: "fadeToBlack", duration: "20f" }} />
- <video src="/Movies/main.mp4" start={12} end={24} transition={{}} /> {/* dissolve, 1s */}
- <video src="/Movies/outro.mp4" start={24} end={30} />
-</sequence>
+<Sequence>
+ <Video src="/Movies/intro.mp4" start={0} end={12} transition={{ type: "fadeToBlack", duration: "20f" }} />
+ <Video src="/Movies/main.mp4" start={12} end={24} transition={{}} /> {/* dissolve, 1s */}
+ <Video src="/Movies/outro.mp4" start={24} end={30} />
+</Sequence>
```
```ts
diff --git a/apps/cli/reference/jsx/video.md b/apps/cli/reference/jsx/video.md
index 2b7e26f9..4b5baab2 100644
--- a/apps/cli/reference/jsx/video.md
+++ b/apps/cli/reference/jsx/video.md
@@ -1,9 +1,9 @@
-# `<video>`
+# `<Video>`
A video clip. `src` resolves to a video asset (see [media.md](./media.md)); when timing is omitted, the node fits its natural duration (see [timing.md](./timing.md)).
```tsx
-<video src="/Movies/main.mp4" start={0} sourceIn={1} sourceOut={13} volume={-3} />
+<Video src="/Movies/main.mp4" start={0} sourceIn={1} sourceOut={13} volume={-3} />
```
## Props
diff --git a/apps/cli/reference/mount.md b/apps/cli/reference/mount.md
index 1386591d..999d6ff3 100644
--- a/apps/cli/reference/mount.md
+++ b/apps/cli/reference/mount.md
@@ -1,6 +1,6 @@
# `dapi mount (<path> | --code <str>)`
-Compiles a Solid JSX project module and executes it in the app, mounting the rendered roots into the document. Like reloading a webpage, re-mounting rebuilds the roots in place instead of adding copies: every top-level element declares its identity in the JSX with a `key`, and `<scene key="intro">` replaces the node carrying that key (or creates it).
+Compiles a Solid JSX project module and executes it in the app, mounting the rendered roots into the document. Like reloading a webpage, re-mounting rebuilds the roots in place instead of adding copies: every top-level element declares its identity in the JSX with a `key`, and `<Scene key="intro">` replaces the node carrying that key (or creates it).
The full JSX code syntax lives in [jsx/](./jsx/README.md); start with the [pipeline](./jsx/README.md#pipeline) and [roots](./jsx/roots.md).
@@ -13,7 +13,7 @@ Exactly one of:
## Lifecycle
-A mount stays live: its reactive graph keeps running after the command returns, so signals, effects, timers, and [`useTicker`](./jsx/lifecycle.md#useticker) keep driving the mounted entities. The compiled module is persisted with the document and re-executed in every context, so the mount is restored on reload and its ticker-driven [`<surface>`](./jsx/surface-paint.md)/[`<html>`](./jsx/html-paint.md) animate in exports and captures (the module's structure must be deterministic). See [jsx/lifecycle.md](./jsx/lifecycle.md).
+A mount stays live: its reactive graph keeps running after the command returns, so signals, effects, timers, and [`useTicker`](./jsx/lifecycle.md#useticker) keep driving the mounted entities. The compiled module is persisted with the document and re-executed in every context, so the mount is restored on reload and its ticker-driven [`<Surface>`](./jsx/surface-paint.md)/[`<Html>`](./jsx/html-paint.md) animate in exports and captures (the module's structure must be deterministic). See [jsx/lifecycle.md](./jsx/lifecycle.md).
## Output
diff --git a/apps/cli/reference/node/insert.md b/apps/cli/reference/node/insert.md
index ed79e398..0fe66ee8 100644
--- a/apps/cli/reference/node/insert.md
+++ b/apps/cli/reference/node/insert.md
@@ -4,12 +4,12 @@ Compiles an inline JSX fragment and inserts its rendered roots as children of an
The payload is **bare JSX tags** — no `export default`, no file path. Unlike `mount`, an insert renders once and is then discarded: it is never persisted, restored, or kept live, so a component that relies on reactivity (signals, effects, `useTicker`) has nothing to drive it. Reach for [`mount`](../mount.md) when you want a live, reproducible program. The full JSX syntax lives in [jsx/](../jsx/README.md).
-The rendered roots must be valid as children of the target parent, following the JSX containment rules: a node parent takes any element or paint root except `<scene>` (scenes only exist at the document top level) and `<colorStop>`; a gradient paint parent takes only `<colorStop>` roots. That is how a stop is added to an existing gradient (`node insert <paintId> '<colorStop offset={0.5} color="#FF0055" />'`); other sub-entities take no children.
+The rendered roots must be valid as children of the target parent, following the JSX containment rules: a node parent takes any element or paint root except `<Scene>` (scenes only exist at the document top level) and `<ColorStop>`; a gradient paint parent takes only `<ColorStop>` roots. That is how a stop is added to an existing gradient (`node insert <paintId> '<ColorStop offset={0.5} color="#FF0055" />'`); other sub-entities take no children.
## Input
- `<parentId>`: entity id of the parent to insert into (required)
-- `<code>`: inline JSX tags to insert, e.g. `'<rect width={100} height={100} />'` (required). Bare tags only — the source is rejected before contacting the app if it contains `export default` or doesn't look like JSX.
+- `<code>`: inline JSX tags to insert, e.g. `'<Rect width={100} height={100} />'` (required). Bare tags only — the source is rejected before contacting the app if it contains `export default` or doesn't look like JSX.
- `-i, --index <N>`: the inserted node's 0-based position among the parent's children, a non-negative integer (optional; default = append after the last child; values past the end are clamped). Node roots only: paints stack in insertion order and color stops render sorted by `offset`, so `--index` is rejected for them.
## Output
@@ -18,4 +18,4 @@ None.
## Errors
-Exits non-zero if `<code>` is not a bare JSX fragment (contains `export default`, or has no tags), if `<parentId>` doesn't resolve to a live entity, if compilation or evaluation fails, if a rendered root is invalid as a child of the parent (e.g. a `<scene>`, or a non-`<colorStop>` in a gradient paint), or if `--index` is given for a paint or color stop root. On any of these, **nothing is inserted**.
+Exits non-zero if `<code>` is not a bare JSX fragment (contains `export default`, or has no tags), if `<parentId>` doesn't resolve to a live entity, if compilation or evaluation fails, if a rendered root is invalid as a child of the parent (e.g. a `<Scene>`, or a non-`<ColorStop>` in a gradient paint), or if `--index` is given for a paint or color stop root. On any of these, **nothing is inserted**.
diff --git a/apps/cli/src/compile-project.ts b/apps/cli/src/compile-project.ts
index fe7cb987..65745387 100644
--- a/apps/cli/src/compile-project.ts
+++ b/apps/cli/src/compile-project.ts
@@ -92,13 +92,24 @@ function resolveBareSpecifier(spec: string, { cdnBase, importMap }: ResolverConf
return `${cdnBase}/${spec}`;
}
+// Identifiers babel auto-imports from `moduleName` when used as JSX tags
+// without an in-scope binding: Solid's control-flow defaults plus the
+// PascalCase composition elements, so project files need no imports for tags.
+// Element names must match the components in packages/jsx/src/elements.ts.
+const BUILT_INS = [
+ "For", "Show", "Switch", "Match", "Suspense", "SuspenseList", "Portal", "Index", "Dynamic", "ErrorBoundary",
+ "Scene", "Group", "Rect", "Video", "Image", "Audio", "Text", "Sequence", "Captions",
+ "SolidPaint", "LinearGradientPaint", "RadialGradientPaint", "ColorStop",
+ "HtmlPaint", "Html", "SurfacePaint", "Surface",
+];
+
async function transformSolidJsx(source: string, filename: string): Promise<string> {
const result = await transformAsync(source, {
filename,
babelrc: false,
configFile: false,
presets: [
- [presetSolid, { generate: "universal", moduleName: "@diffusionstudio/jsx" }],
+ [presetSolid, { generate: "universal", moduleName: "@diffusionstudio/jsx", builtIns: BUILT_INS }],
[presetTypescript, {}],
],
sourceMaps: "inline",
@@ -148,7 +159,7 @@ function resolverPlugin(config: ResolverConfig): Plugin {
export type CompileInput = { path: string } | { code: string };
// `--code` ergonomics: a bare JSX expression (no `export default`) is wrapped
-// into a component module, so one-liners like `--code '<rect width={10} />'`
+// into a component module, so one-liners like `--code '<Rect width={10} />'`
function wrapBareJsx(code: string): string {
if (/\bexport\s+default\b/.test(code)) return code;
return `export default () => (\n${code.trim().replace(/;+\s*$/, "")}\n);`;
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index 0ed7c005..378de0c3 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -739,7 +739,7 @@ async function nodeInsert(parentId: string, source: string, opts: NodeInsertOpti
process.exit(1);
}
if (!/<\s*[A-Za-z]/.test(source)) {
- console.error("`dapi node insert` expects JSX tags, e.g. '<rect width={10} height={10} />'.");
+ console.error("`dapi node insert` expects JSX tags, e.g. '<Rect width={10} height={10} />'.");
process.exit(1);
}
@@ -1088,7 +1088,7 @@ program
program
.command("mount")
.description(
- `Compile a Solid JSX project module and mount its roots into the canvas. Re-mounting reconciles rather than duplicates: each top-level element carries a \`key\`, and a root replaces the node with that key or creates it (a new <scene key> becomes the active scene and the camera focuses it). A mount stays live: its reactive graph keeps running (signals, effects, timers, \`useTicker\`), and the persisted module is re-executed in every context, so the mount is restored on reload and ticker-driven <surface>/<html> animate in exports and captures (structure must be deterministic). Long-running when the module declares AI assets (blocks until generation finishes). Compile errors fail before the app is contacted; inspect the result with \`dapi context\` or \`dapi node tree\`.`,
+ `Compile a Solid JSX project module and mount its roots into the canvas. Re-mounting reconciles rather than duplicates: each top-level element carries a \`key\`, and a root replaces the node with that key or creates it (a new <Scene key> becomes the active scene and the camera focuses it). A mount stays live: its reactive graph keeps running (signals, effects, timers, \`useTicker\`), and the persisted module is re-executed in every context, so the mount is restored on reload and ticker-driven <Surface>/<Html> animate in exports and captures (structure must be deterministic). Long-running when the module declares AI assets (blocks until generation finishes). Compile errors fail before the app is contacted; inspect the result with \`dapi context\` or \`dapi node tree\`.`,
)
.argument("[path]", "path to a .tsx / .jsx / .ts / .js entry module")
.option("--code <str>", "inline module source; export default wrapper optional for bare JSX")
@@ -1353,10 +1353,10 @@ node
node
.command("insert")
.description(
- `Insert JSX tags as children of an existing entity. The payload is an inline JSX fragment, e.g. \`'<rect width={10} height={10} />'\` — bare tags, no \`export default\`: an insert renders once and is discarded, so there is no live graph to drive (use \`dapi mount\` for anything reactive). Otherwise it shares the \`mount\` pipeline, including AI asset generation, but inserts fresh entities every run rather than reconciling by key, and deletes nothing. Roots must be valid children of the parent (a node takes any element or paint except <scene> and <colorStop>; a gradient paint takes only <colorStop> roots, which is how you add a stop to a gradient).`,
+ `Insert JSX tags as children of an existing entity. The payload is an inline JSX fragment, e.g. \`'<Rect width={10} height={10} />'\` — bare tags, no \`export default\`: an insert renders once and is discarded, so there is no live graph to drive (use \`dapi mount\` for anything reactive). Otherwise it shares the \`mount\` pipeline, including AI asset generation, but inserts fresh entities every run rather than reconciling by key, and deletes nothing. Roots must be valid children of the parent (a node takes any element or paint except <Scene> and <ColorStop>; a gradient paint takes only <ColorStop> roots, which is how you add a stop to a gradient).`,
)
- .argument("<parentId>", "entity id of the parent to insert into — a node, or a gradient paint for <colorStop> roots")
- .argument("<code>", "JSX tags to insert, e.g. '<rect width={10} height={10} />' (no export default)")
+ .argument("<parentId>", "entity id of the parent to insert into — a node, or a gradient paint for <ColorStop> roots")
+ .argument("<code>", "JSX tags to insert, e.g. '<Rect width={10} height={10} />' (no export default)")
.option("-i, --index <n>", "0-based position among the parent's existing children (node roots only; default: append at the end)")
.action((parentId: string, code: string, opts: NodeInsertOptions) => nodeInsert(parentId, code, opts));
@@ -1451,7 +1451,7 @@ program
program
.command("fonts")
.description(
- `List the local fonts available on this machine (macOS only; does not require the app). These family names are valid \`fontFamily\` values on <text>; each family lists its variants.`,
+ `List the local fonts available on this machine (macOS only; does not require the app). These family names are valid \`fontFamily\` values on <Text>; each family lists its variants.`,
)
.option("-f, --family <pattern>", "filter to families whose name contains <pattern> (case-insensitive)")
.option("-w, --weight <weights...>", "filter to variants with the given CSS weight(s), e.g. -w 400 700")
diff --git a/apps/web/src/components/engine/api/components.ts b/apps/web/src/components/engine/api/components.ts
index 9377c452..d4dc79d4 100644
--- a/apps/web/src/components/engine/api/components.ts
+++ b/apps/web/src/components/engine/api/components.ts
@@ -4,6 +4,8 @@
import * as ComponentRegistry from "../components/components";
+export type { MountData } from "../components/components";
+
export function createComponents(): Components {
return Object.fromEntries(
Object.entries(ComponentRegistry)
diff --git a/apps/web/src/components/engine/components/components.ts b/apps/web/src/components/engine/components/components.ts
index 7ad56601..be31247e 100644
--- a/apps/web/src/components/engine/components/components.ts
+++ b/apps/web/src/components/engine/components/components.ts
@@ -380,6 +380,14 @@ export const HtmlHost = [] as (HtmlHostInstance | null)[];
export const SurfaceHost = [] as (SurfaceHostInstance | null)[];
+// Renderer-runtime state on mounted entities (never serialized)
+export type MountData = {
+ props: Record<string, unknown>;
+ textBox?: DocumentFragment;
+};
+
+export const Data = [] as (MountData | null)[];
+
export const ImageDecoder = [] as (ImageDecoderInstance | null)[];
export const VideoDecoder = [] as (VideoDecoderInstance | null)[];
diff --git a/apps/web/src/components/engine/decoders/html.ts b/apps/web/src/components/engine/decoders/html.ts
index cc32a38e..3b305dc2 100644
--- a/apps/web/src/components/engine/decoders/html.ts
+++ b/apps/web/src/components/engine/decoders/html.ts
@@ -92,7 +92,7 @@ export class HtmlHost {
// skips the frame; log once so a permanent one doesn't spam.
if (!this.warned) {
this.warned = true;
- console.error('Error drawing <htmlPaint> content', e);
+ console.error('Error drawing <HtmlPaint> content', e);
}
}
}
@@ -105,7 +105,7 @@ export class HtmlHost {
}
/**
- * Shares <htmlPaint> hosts with a cloned (offline) world. Host DOM is
+ * Shares <HtmlPaint> hosts with a cloned (offline) world. Host DOM is
* runtime state serializeEntity cannot carry, so export/capture worlds
* reference the live hosts directly and sample whatever the mount's reactive
* graph shows while encoding. The source world keeps ownership; offline
diff --git a/apps/web/src/components/engine/decoders/surface.ts b/apps/web/src/components/engine/decoders/surface.ts
index 44fd19ce..d1294040 100644
--- a/apps/web/src/components/engine/decoders/surface.ts
+++ b/apps/web/src/components/engine/decoders/surface.ts
@@ -43,7 +43,7 @@ export class SurfaceHost {
}
/**
- * Shares <surfacePaint> hosts with a cloned (offline) world. The backing
+ * Shares <SurfacePaint> hosts with a cloned (offline) world. The backing
* canvas is runtime state serializeEntity cannot carry, so export/capture
* worlds reference the live hosts directly and sample whatever the mount's
* ref last drew while encoding. The source world keeps ownership; offline
diff --git a/apps/web/src/context/editor-api/mount.ts b/apps/web/src/context/editor-api/mount.ts
index 5818f280..34d01186 100644
--- a/apps/web/src/context/editor-api/mount.ts
+++ b/apps/web/src/context/editor-api/mount.ts
@@ -94,7 +94,7 @@ export function handleMount(engine: Accessor<Engine>) {
* parent entity instead of the document: roots take no key, nothing is
* reconciled or deleted, every run inserts fresh entities. The parent may be
* any live entity that takes children — a node, or a gradient paint for
- * `<colorStop>` roots.
+ * `<ColorStop>` roots.
*/
export function handleNodeInsert(engine: Accessor<Engine>) {
return async ({ code, parentId, index }: NodeInsertRequest): Promise<void> => {
diff --git a/apps/web/src/utils/jsx.ts b/apps/web/src/utils/jsx.ts
index b6675f15..921b5109 100644
--- a/apps/web/src/utils/jsx.ts
+++ b/apps/web/src/utils/jsx.ts
@@ -6,6 +6,7 @@ import { hasComponent, query, Not } from "bitecs";
import { getAssetSpec, isAssetRef, parseTime } from "@diffusionstudio/jsx";
import * as solid from "solid-js";
import * as solidStore from "solid-js/store";
+import { SVGElements } from "solid-js/web";
import * as diffusionJsx from "@diffusionstudio/jsx";
import {
AnimationPhase,
@@ -25,6 +26,7 @@ import {
deleteEntity,
findAssetDuration,
findGeometryAsset,
+ getEntityTree,
getNextName,
getParentEntity,
getSceneAncestor,
@@ -46,55 +48,36 @@ import { resolveAsset, resolveGeneratedAsset } from "@/utils/jsx-generation";
import { assert, assertAllSettled, parseColor } from "@/utils";
import type { AssetInput, AssetRef, AssetSpecInput, ProjectDocument, ProjectTick } from "@diffusionstudio/jsx";
-import type { Engine, EngineWorld } from "@/components/engine";
+import type { Engine, EngineWorld, MountData } from "@/components/engine";
import type { GenerationMemo } from "@/utils/jsx-generation";
+export class EntityNode {
+ public constructor(public readonly eid: number) { }
+}
+
/**
- * Shadow node: the renderer's host tree, kept as plain objects. Lifecycle
- * calls update this representation first; entities and DOM nodes are only
- * created when a node is inserted into the live tree, at which point its
- * environment (ECS world vs DOM under an <htmlPaint>) is known and all
- * initial props have been recorded — Solid attaches a subtree's root last.
+ * The renderer's host node: an entity handle, or a DOM node for <HtmlPaint>
+ * content — the ECS world and the DOM are the scene graph, with no shadow
+ * tree in between. A tag's case decides which side a node lands on at
+ * creation (PascalCase composition elements mint entities, lowercase tags
+ * mint DOM nodes), so `setProperty` always has a live target.
*/
-type DocumentNode = {
- id: number;
- tag?: string;
- text?: string;
- props: Record<string, unknown>;
- children: DocumentNode[];
- parent?: DocumentNode;
- eid?: number;
- dom?: Element | Text;
- host?: HtmlHost;
- surfaceHost?: SurfaceHost;
- ref?(target: unknown): void;
- adopted?: boolean;
-};
+type HostNode = EntityNode | Element | Text;
-let nextNodeId = 1;
-
-function makeNode(init: Pick<DocumentNode, "tag" | "text" | "eid">): DocumentNode {
- return { id: nextNodeId++, ...init, props: {}, children: [] };
-}
+const STAGE = new EntityNode(-1);
/**
* Reads a timing prop as local frames. The record always holds raw `Time`
* values (numbers are seconds), so every read parses; an unparsable value
* reads as absent until its own apply rejects it.
*/
-function timingProp(node: DocumentNode, name: "start" | "end" | "sourceIn" | "sourceOut"): number | undefined {
- const value = node.props[name];
+function timingProp(props: Record<string, unknown> | undefined, name: "start" | "end" | "sourceIn" | "sourceOut"): number | undefined {
+ const value = props?.[name];
return value === undefined ? undefined : parseFrames(String(value), 30);
}
const SVG_NS = "http://www.w3.org/2000/svg";
-// Children of an SVG element stay in the SVG namespace, except under
-// <foreignObject>, which switches back to HTML.
-function isSvgContext(el: Element): boolean {
- return el.namespaceURI === SVG_NS && el.localName !== "foreignObject";
-}
-
// Multiple new scenes are laid side by side in render order.
const PLACEMENT_GAP = 40;
@@ -290,12 +273,22 @@ const CAPTION_PRESET_MAP = {
} as const;
type GenaiQueueItem = {
- node: DocumentNode;
+ eid: number;
ref?: AssetRef;
targetKey?: string;
type: "asset" | "caption" | "sync";
};
+/**
+ * A surface awaiting its box size (and ref) until its subtree connects.
+ */
+type PendingSurface = {
+ eid: number;
+ host: SurfaceHost;
+ paint: boolean;
+ ref?: (target: unknown) => void;
+};
+
export interface WorldDocumentOptions {
/** Mount into an existing parent entity (e.g. `dapi node insert`). */
parentEid?: number;
@@ -312,18 +305,20 @@ export interface WorldDocumentOptions {
mountId?: string;
/** SCRIPT asset holding the compiled module, stamped onto the mount root. */
scriptAssetId?: string;
- /** `adopt` mode: MountPath -> existing entity id, built from the world. */
+ /** `adopt` mode: creation ordinal (`MountPath.path`) -> existing entity id, built from the world. */
adoptIndex?: Map<string, number>;
}
-export class WorldDocument implements ProjectDocument<DocumentNode> {
+export class WorldDocument implements ProjectDocument<HostNode> {
public promises: Promise<void>[] = [];
- public stage: DocumentNode;
+ public stage: HostNode = STAGE;
+ public roots: HostNode[] = [];
public rootEid: number | null = null;
public world: EngineWorld;
public engine?: Engine;
private readonly mode: "author" | "adopt";
+ private readonly stageEid?: number;
private readonly mountId?: string;
private readonly scriptAssetId?: string;
private readonly adoptIndex?: Map<string, number>;
@@ -335,6 +330,73 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
private queue: GenaiQueueItem[] = [];
+ // Entities mint in module-execution order; the ordinal is each element's
+ // persisted identity (`MountPath.path`). A re-run of the same module mints
+ // in the same order, which is what lets adopt bind in `createElement`.
+ private nextOrdinal = 0;
+
+ // Surfaces whose box size (and so ref) can only resolve once their
+ // ancestor chain exists — flushed when the subtree connects to the stage.
+ private pendingSurfaces: PendingSurface[] = [];
+
+ // Entities this render minted or adopted — exactly the renderer's element
+ // nodes. Traversal filters ECS children through this set so internal
+ // sub-entities (a <Text>'s paint) and hand-added children stay invisible
+ // to Solid's reconciler, which deletes whatever it can see but no longer
+ // tracks.
+ private managed = new Set<number>();
+
+ // Adopted entities keep their persisted (possibly hand-edited) values
+ // through the initial adopt render; only post-commit effects write.
+ private adopted = new Set<number>();
+
+ // Entities this render soft-deleted via removeNode. Solid's reconciler
+ // shuffles by removing and re-inserting nodes, so re-attaching one of
+ // these resurrects it — but only these: an entity deleted from outside
+ // (keyed replace, user delete) must stay dead even if a stale reconcile
+ // still references it.
+ private removed = new Set<number>();
+
+ // DOM containers back to their owning entity, as Solid knows it: an html
+ // host element maps to the element Solid inserts DOM content under, a text
+ // fragment to its <Text> entity.
+ private nodeOwner = new WeakMap<Node, number>();
+
+ // Html host per element the renderer inserts DOM content under (the
+ // wrapper for <Html>, the paint entity for <HtmlPaint>).
+ private htmlHosts = new Map<number, HtmlHost>();
+
+ // One stable handle per entity: Solid's reconciliation compares host nodes
+ // by object identity, so traversal must return the same instance that
+ // `createElement` handed out.
+ private entityNodes = new Map<number, EntityNode>();
+
+ /** The entity's stable renderer handle, created on first touch. */
+ private entity(eid: number): EntityNode {
+ let node = this.entityNodes.get(eid);
+ if (node === undefined) {
+ node = new EntityNode(eid);
+ this.entityNodes.set(eid, node);
+ }
+ return node;
+ }
+
+ /** The entity's runtime renderer state, created on first touch. */
+ private data(eid: number): MountData {
+ const c = this.world.components;
+ if (!hasComponent(this.world, eid, c.Data)) {
+ addComponent(this.world, eid, c.Data, false);
+ c.Data[eid] = { props: {} };
+ }
+ return c.Data[eid]!;
+ }
+
+ /** The entity's recorded raw props, if any were recorded. */
+ private props(eid: number): Record<string, unknown> | undefined {
+ const c = this.world.components;
+ return hasComponent(this.world, eid, c.Data) ? c.Data[eid]?.props : undefined;
+ }
+
private trackHost<T extends { dispose(): void }>(host: T): T {
this.createdHosts.push(host);
return host;
@@ -363,7 +425,7 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
public constructor(world: EngineWorld, options: WorldDocumentOptions = {}) {
this.world = world;
this.engine = options.engine;
- this.stage = makeNode({ tag: "#root", eid: options.parentEid });
+ this.stageEid = options.parentEid;
this.mode = options.mode ?? "author";
this.mountId = options.mountId;
this.scriptAssetId = options.scriptAssetId;
@@ -387,9 +449,9 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
{
const memo: GenerationMemo = new Map();
- const results = await Promise.allSettled(this.queue.map(({ node, ref, type }) => {
+ const results = await Promise.allSettled(this.queue.map(({ eid, ref, type }) => {
if (type !== "asset" || !ref) return;
- return this.generateInto(node, ref, memo);
+ return this.generateInto(eid, ref, memo);
}));
assertAllSettled(results);
@@ -398,9 +460,8 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
// Handle sync queue: after generated assets have landed (either side may
// be generated), before captions read the scene's final placement.
{
- for (const { node, targetKey, type } of this.queue) {
- if (node.eid === undefined || type !== "sync" || !targetKey) continue;
- const nodeEid = node.eid;
+ for (const { eid: nodeEid, targetKey, type } of this.queue) {
+ if (type !== "sync" || !targetKey || hasComponent(world, nodeEid, c.Deleted)) continue;
const targetEid = query(world, [c.Key, Not(c.Deleted)]).find(eid => c.Key[eid] === targetKey);
assert(targetEid !== undefined, `syncTo: no other element carries key "${targetKey}"`);
@@ -431,26 +492,26 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
// `sourceIn`/`sourceOut` are source-relative; default to the overlap
// with the target window. `end` (timeline) converts through `delay`.
- const end = timingProp(node, "end");
- const trimStart = timingProp(node, "sourceIn") ?? Math.max(0, targetStart - delay);
- const trimEnd = timingProp(node, "sourceOut")
+ const props = this.data(nodeEid).props;
+ const end = timingProp(props, "end");
+ const trimStart = timingProp(props, "sourceIn") ?? Math.max(0, targetStart - delay);
+ const trimEnd = timingProp(props, "sourceOut")
?? (end !== undefined
? end - delay
: (duration !== null ? Math.min(duration, targetEnd - delay) : targetEnd - delay));
assert(trimEnd > trimStart, `syncTo: the aligned clip does not overlap the window of "${targetKey}"`);
setComponent(world, nodeEid, c.Trim, { start: trimStart, end: trimEnd });
- node.props.sourceIn = `${trimStart}f`;
- node.props.sourceOut = `${trimEnd}f`;
- delete node.props.end;
- node.props.start = `${delay + trimStart}f`;
+ props.sourceIn = `${trimStart}f`;
+ props.sourceOut = `${trimEnd}f`;
+ delete props.end;
+ props.start = `${delay + trimStart}f`;
}
}
// Handle captioning queue
{
- for (const { node, type } of this.queue) {
- if (node.eid === undefined || hasComponent(world, node.eid, c.Deleted) || type !== "caption" || c.AssetId[node.eid]) continue;
- const nodeEid = node.eid;
+ for (const { eid: nodeEid, type } of this.queue) {
+ if (hasComponent(world, nodeEid, c.Deleted) || type !== "caption" || c.AssetId[nodeEid]) continue;
const sceneEid = getSceneAncestor(world, nodeEid);
if (!sceneEid || !hasAudioSources(world, sceneEid)) continue;
@@ -525,7 +586,7 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
const world = this.world;
const c = world.components;
- let current = this.rootEid ?? this.stage.eid ?? null;
+ let current = this.rootEid ?? this.stageEid ?? null;
while (current !== null && !hasComponent(world, current, c.Deleted)) {
if (hasComponent(world, current, c.Playback)) return current;
current = getParentEntity(world, current);
@@ -537,112 +598,143 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
* Resolves a generated asset and attaches it: during commit via the genai
* queue, or immediately when a live mount sets an asset ref after commit.
*/
- private async generateInto(node: DocumentNode, ref: AssetRef, memo: GenerationMemo): Promise<void> {
+ private async generateInto(eid: number, ref: AssetRef, memo: GenerationMemo): Promise<void> {
const world = this.world;
const c = world.components;
- if (node.eid === undefined || hasComponent(world, node.eid, c.Deleted)) return;
- const eid = node.eid;
+ if (hasComponent(world, eid, c.Deleted)) return;
try {
const asset = await resolveGeneratedAsset(world, ref, memo);
- await this.mountSource(node, asset.id);
+ await this.mountSource(eid, asset.id);
} finally {
world.history.untrack(() => removeComponent(world, eid, c.Generating));
}
}
- public createElement(tag: string): DocumentNode {
- return makeNode({ tag });
+ public createElement(tag: string): HostNode {
+ // When the tag starts with a lowercase letter, it's a DOM vocabulary
+ if (tag[0] === tag[0].toLowerCase()) {
+ return SVGElements.has(tag)
+ ? document.createElementNS(SVG_NS, tag)
+ : document.createElement(tag);
+ }
+ return this.entity(this.track(() => this.bindEntity(tag)));
}
- public createTextNode(text: string): DocumentNode {
- return makeNode({ text });
+ /**
+ * Binds a composition element to its entity: adopt mode looks up the
+ * persisted entity minted at the same creation ordinal, author mode creates
+ * one and stamps the ordinal as its `MountPath`. New elements an adopted
+ * mount's effects create later (no persisted counterpart) author as usual.
+ */
+ private bindEntity(tag: string): number {
+ const path = String(this.nextOrdinal++);
+ const adoptedEid = this.mode === "adopt" ? this.adoptIndex?.get(path) : undefined;
+
+ let eid: number;
+ if (adoptedEid !== undefined) {
+ eid = adoptedEid;
+ this.adopted.add(eid);
+ this.reattachRuntimeHostsForTag(tag, eid);
+ } else {
+ eid = this.createEntityForTag(tag);
+ if (this.mountId !== undefined) {
+ setComponent(this.world, eid, this.world.components.MountPath, { mountId: this.mountId, path });
+ }
+ }
+
+ this.managed.add(eid);
+ return eid;
}
- /** Tag-specific entity setup for a node materializing into the ECS world. */
- private createEntityForTag(node: DocumentNode): number {
+ public createTextNode(text: string): HostNode {
+ return document.createTextNode(text);
+ }
+
+ /** Tag-specific entity setup for a composition element. */
+ private createEntityForTag(tag: string): number {
const world = this.world;
const c = world.components;
const eid = createEntity(world);
- switch (node.tag) {
- case "scene": {
+ switch (tag) {
+ case "Scene": {
setComponent(world, eid, c.Geometry, GeometryType.RECT);
addComponent(world, eid, c.Scene);
addComponent(world, eid, c.ClipsContent);
setComponent(world, eid, c.Playback, {});
setComponent(world, eid, c.Name, getNextName(world, "Scene"));
break;
- } case "group": {
+ } case "Group": {
setComponent(world, eid, c.Geometry, GeometryType.RECT);
addComponent(world, eid, c.Group);
setComponent(world, eid, c.Name, getNextName(world, "Group"));
break;
- } case "rect": {
+ } case "Rect": {
setComponent(world, eid, c.Geometry, GeometryType.RECT);
setComponent(world, eid, c.Name, getNextName(world, "Rect"));
break;
- } case "sequence": {
+ } case "Sequence": {
addComponent(world, eid, c.Group);
addComponent(world, eid, c.Sequential);
setComponent(world, eid, c.Name, getNextName(world, "Sequence"));
break;
- } case "video": {
+ } case "Video": {
setComponent(world, eid, c.Geometry, GeometryType.RECT);
setComponent(world, eid, c.Name, getNextName(world, "Video"));
break;
- } case "image": {
+ } case "Image": {
setComponent(world, eid, c.Geometry, GeometryType.RECT);
setComponent(world, eid, c.Name, getNextName(world, "Image"));
break;
- } case "audio": {
+ } case "Audio": {
addComponent(world, eid, c.Audio);
setComponent(world, eid, c.Geometry, GeometryType.RECT);
setComponent(world, eid, c.Name, getNextName(world, "Audio"));
break;
- } case "text": {
+ } case "Text": {
setComponent(world, eid, c.Geometry, GeometryType.TEXT);
const fid = createEntity(world);
setComponent(world, fid, c.Paint, PaintType.SOLID);
setComponent(world, fid, c.Color, 0xffffff);
appendChild(world, fid, eid);
break;
- } case "captions": {
- assert(!this.committed, "<captions> cannot be created after commit; re-mount instead");
+ } case "Captions": {
+ assert(!this.committed, "<Captions> cannot be created after commit; re-mount instead");
setComponent(world, eid, c.Geometry, GeometryType.TEXT);
setComponent(world, eid, c.Caption, {});
setComponent(world, eid, c.Name, getNextName(world, "Captions"));
- this.queue.push({ node, type: "caption" });
+ this.queue.push({ eid, type: "caption" });
break;
- } case "solidPaint": case "solid": {
+ } case "SolidPaint": {
setComponent(world, eid, c.Paint, PaintType.SOLID);
setComponent(world, eid, c.Color, 0xE0E0E0);
break;
- } case "linearGradientPaint": case "linearGradient": {
+ } case "LinearGradientPaint": {
setComponent(world, eid, c.Paint, PaintType.LINEAR_GRADIENT);
break;
- } case "radialGradientPaint": case "radialGradient": {
+ } case "RadialGradientPaint": {
setComponent(world, eid, c.Paint, PaintType.RADIAL_GRADIENT);
break;
- } case "colorStop": case "stop": {
+ } case "ColorStop": {
setComponent(world, eid, c.ColorStop, {});
break;
- } case "htmlPaint": {
+ } case "HtmlPaint": {
assert(
isHtmlInCanvasSupported(),
- "<htmlPaint> requires the html-in-canvas API; enable chrome://flags/#canvas-draw-element",
+ "<HtmlPaint> requires the html-in-canvas API; enable chrome://flags/#canvas-draw-element",
);
setComponent(world, eid, c.Paint, PaintType.HTML);
const host = this.trackHost(new HtmlHost());
addComponent(world, eid, c.HtmlHost, false);
c.HtmlHost[eid] = host;
- node.host = host;
+ this.registerHtmlHost(eid, host);
break;
- } case "html": {
- // A rect carrying an html paint; the node's children are the paint's
- // DOM content, so `node.host` points at the paint's host.
+ } case "Html": {
+ // A rect carrying an html paint; the element's children are the
+ // paint's DOM content, so the wrapper routes to the paint's host.
assert(
isHtmlInCanvasSupported(),
- "<html> requires the html-in-canvas API; enable chrome://flags/#canvas-draw-element",
+ "<Html> requires the html-in-canvas API; enable chrome://flags/#canvas-draw-element",
);
setComponent(world, eid, c.Geometry, GeometryType.RECT);
setComponent(world, eid, c.Name, getNextName(world, "HTML"));
@@ -652,18 +744,18 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
addComponent(world, fid, c.HtmlHost, false);
c.HtmlHost[fid] = host;
appendChild(world, fid, eid);
- node.host = host;
+ this.registerHtmlHost(eid, host);
break;
- } case "surfacePaint": {
+ } case "SurfacePaint": {
setComponent(world, eid, c.Paint, PaintType.SURFACE);
const host = this.trackHost(new SurfaceHost());
addComponent(world, eid, c.SurfaceHost, false);
c.SurfaceHost[eid] = host;
- node.surfaceHost = host;
+ this.pendingSurfaces.push({ eid, host, paint: true });
break;
- } case "surface": {
- // A rect carrying a surface paint; the node's ref receives the
- // paint's backing canvas, so `node.surfaceHost` points at it.
+ } case "Surface": {
+ // A rect carrying a surface paint; the element's ref receives the
+ // paint's backing canvas.
setComponent(world, eid, c.Geometry, GeometryType.RECT);
setComponent(world, eid, c.Name, getNextName(world, "Surface"));
const fid = createEntity(world);
@@ -672,10 +764,10 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
addComponent(world, fid, c.SurfaceHost, false);
c.SurfaceHost[fid] = host;
appendChild(world, fid, eid);
- node.surfaceHost = host;
+ this.pendingSurfaces.push({ eid, host, paint: false });
break;
} default: {
- assert(false, `<${node.tag}> is only valid inside <html> content`);
+ assert(false, `<${tag}> is not a composition element`);
}
}
@@ -688,41 +780,46 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
* state is hydrated from the entity's components so a partial patch (say,
* only `sourceIn`) composes with its existing delay/trim like a full render.
*/
- public element(eid: number): DocumentNode {
+ public element(eid: number): EntityNode {
const world = this.world;
const c = world.components;
- const node = makeNode({ tag: "#entity", eid });
+ const props = this.data(eid).props;
+ // Reset the timing record from the entity's components — they are the
+ // source of truth (hand-edits bypass any props a live mount recorded).
+ delete props.start;
+ delete props.end;
+ delete props.sourceIn;
+ delete props.sourceOut;
const delay = hasComponent(world, eid, c.Delay) ? c.Delay[eid] : 0;
if (hasComponent(world, eid, c.Trim)) {
const start = c.Trim.start[eid];
const end = c.Trim.end[eid];
if (start !== undefined) {
- node.props.sourceIn = `${start}f`;
+ props.sourceIn = `${start}f`;
}
if (end !== undefined) {
- node.props.sourceOut = `${end}f`;
+ props.sourceOut = `${end}f`;
}
}
// start = timeline placement of source-0 (Delay) shifted by the source in point.
- if (hasComponent(world, eid, c.Delay) || node.props.sourceIn !== undefined) {
- node.props.start = `${delay + (timingProp(node, "sourceIn") ?? 0)}f`;
+ if (hasComponent(world, eid, c.Delay) || props.sourceIn !== undefined) {
+ props.start = `${delay + (timingProp(props, "sourceIn") ?? 0)}f`;
}
- return node;
+ return this.entity(eid);
}
- private reconcileTiming(node: DocumentNode) {
- if (node.eid === undefined) return;
+ private reconcileTiming(eid: number) {
const world = this.world;
const c = world.components;
- const eid = node.eid;
- const sourceIn = timingProp(node, "sourceIn") ?? 0;
- const start = timingProp(node, "start") ?? 0;
- const end = timingProp(node, "end");
- const sourceOut = timingProp(node, "sourceOut");
+ const props = this.props(eid);
+ const sourceIn = timingProp(props, "sourceIn") ?? 0;
+ const start = timingProp(props, "start") ?? 0;
+ const end = timingProp(props, "end");
+ const sourceOut = timingProp(props, "sourceOut");
const delay = start - sourceIn;
setComponent(world, eid, c.Delay, delay);
- if (timingProp(node, "sourceIn") !== undefined) {
+ if (timingProp(props, "sourceIn") !== undefined) {
setComponent(world, eid, c.Trim, { start: sourceIn });
}
if (sourceOut !== undefined) {
@@ -734,65 +831,65 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
}
}
- public replaceText(node: DocumentNode, text: string) {
- assert(node.text !== undefined, "replaceText target is not a text node");
- node.text = text;
- // Text inside HTML content is backed by a live DOM node.
- if (node.dom !== undefined) {
- (node.dom as Text).data = text;
- return;
- }
- // Already-materialized text inside a <text> element (a live mount
- // updating a signal) must land in the world too.
- const parent = node.parent;
- if (parent !== undefined && this.isTextEntity(parent)) {
- this.track(() => this.assignChars(parent));
+ public replaceText(node: HostNode, text: string) {
+ assert(node instanceof Text, "replaceText target is not a text node");
+ node.data = text;
+ // Text inside a <Text> element (a live mount updating a signal) must
+ // land in the world too.
+ const owner = node.parentNode !== null ? this.nodeOwner.get(node.parentNode) : undefined;
+ if (owner !== undefined && this.isTextEntity(owner)) {
+ this.track(() => this.syncChars(owner));
}
}
- public isTextNode(node: DocumentNode): boolean {
- return node.text !== undefined;
+ public isTextNode(node: HostNode): boolean {
+ return node instanceof Text;
}
- private isTextEntity(node: DocumentNode): boolean {
+ private isTextEntity(eid: number): boolean {
const c = this.world.components;
- return c.Geometry[node.eid ?? -1] === GeometryType.TEXT;
+ return c.Geometry[eid] === GeometryType.TEXT;
}
/**
- * Chars mirrors the concatenation of a text element's text children — a
- * reactive segment compiles to its own text node (`frame {frame()}` is two).
+ * Chars mirrors the concatenation of a text element's text runs, held in
+ * its Data fragment — a reactive segment compiles to its own text node
+ * (`frame {frame()}` is two).
*/
- private assignChars(parent: DocumentNode): void {
+ private syncChars(eid: number): void {
const c = this.world.components;
- const texts = parent.children.filter((child) => child.text !== undefined);
- assert(parent.eid !== undefined, "syncChars parent is not a text entity");
+ // Adopted text keeps its persisted (possibly hand-edited) Chars through
+ // the initial adopt render; only actively re-running effects write.
+ if (this.adopted.has(eid) && !this.committed) return;
+ const textBox = hasComponent(this.world, eid, c.Data) ? c.Data[eid]?.textBox : undefined;
- if (texts.length === 0) {
- removeComponent(this.world, parent.eid, c.Chars);
+ if (textBox === undefined || textBox.firstChild === null) {
+ removeComponent(this.world, eid, c.Chars);
} else {
- setComponent(this.world, parent.eid, c.Chars, texts.map((child) => child.text).join(""));
+ setComponent(this.world, eid, c.Chars, textBox.textContent ?? "");
}
}
- public setProperty(node: DocumentNode, name: string, value: unknown) {
- if (name === "children" || name === "ref" || value === undefined || node.text !== undefined) return;
- // update shadow node props
- node.props[name] = value;
-
- // dom path
- if (node.dom !== undefined) {
- setDomProperty(node.dom as Element, name, value);
- } else if (node.eid !== undefined) {
- // ecs path
- this.track(() => this.applyEcsProperty(node, name, value));
+ public setProperty(node: HostNode, name: string, value: unknown) {
+ if (name === "children" || name === "ref" || value === undefined || node instanceof Text) return;
+
+ if (node instanceof Element) {
+ setDomProperty(node, name, value);
+ return;
}
+ const eid = node.eid;
+ // Recorded even when not applied: timing, sync, and box-size resolution
+ // read the raw props back.
+ this.data(eid).props[name] = value;
+ // Adopted entities keep their persisted (possibly hand-edited) values
+ // through the initial adopt render; only actively re-running effects write.
+ if (this.adopted.has(eid) && !this.committed) return;
+ this.track(() => this.applyEcsProperty(eid, name, value));
}
- private applyEcsProperty(node: DocumentNode, name: string, value: unknown) {
+ private applyEcsProperty(eid: number, name: string, value: unknown) {
const world = this.world;
const c = world.components;
- const eid = node.eid!;
switch (name) {
case "name": {
@@ -878,8 +975,7 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
if (Array.isArray(value)) {
const keyframes = parseKeyframes(name, value, (v) => {
assert(typeof v === "number", "`opacity` must be a number" + `, value: ${v}`);
- assert(v >= 0 && v <= 1, "`opacity` must be between 0 and 1");
- return v;
+ return Math.min(1, Math.max(0, v));
});
if (isStop) setComponent(world, eid, c.ColorStop, { opacity: keyframes[0].value });
else setComponent(world, eid, c.Appearance, { opacity: keyframes[0].value });
@@ -888,11 +984,11 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
}
setKeyframeTrack(world, eid, isStop ? "stop.opacity" : "opacity", []);
assert(typeof value === "number", "`opacity` must be a number" + `, value: ${value}`);
- assert(value >= 0 && value <= 1, "`opacity` must be between 0 and 1");
+ const opacity = Math.min(1, Math.max(0, value));
if (isStop) {
- setComponent(world, eid, c.ColorStop, { opacity: value });
+ setComponent(world, eid, c.ColorStop, { opacity });
} else {
- setComponent(world, eid, c.Appearance, { opacity: value });
+ setComponent(world, eid, c.Appearance, { opacity });
}
break;
} case "cornerRadius": {
@@ -914,28 +1010,24 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
} case "start": {
const parsed = parseFrames(String(value), 30);
assert(typeof parsed === "number", "`start` must be a string or number" + `, value: ${value}`);
- node.props.start = value;
- this.reconcileTiming(node);
+ this.reconcileTiming(eid);
break;
} case "end": {
const parsed = parseFrames(String(value), 30);
assert(typeof parsed === "number", "`end` must be a string or number" + `, value: ${value}`);
- node.props.end = value;
- delete node.props.sourceOut;
- this.reconcileTiming(node);
+ delete this.data(eid).props.sourceOut;
+ this.reconcileTiming(eid);
break;
} case "sourceIn": {
const parsed = parseFrames(String(value), 30);
assert(typeof parsed === "number", "`sourceIn` must be a string or number" + `, value: ${value}`);
- node.props.sourceIn = value;
- this.reconcileTiming(node);
+ this.reconcileTiming(eid);
break;
} case "sourceOut": {
const parsed = parseFrames(String(value), 30);
assert(typeof parsed === "number", "`sourceOut` must be a string or number" + `, value: ${value}`);
- node.props.sourceOut = value;
- delete node.props.end;
- this.reconcileTiming(node);
+ delete this.data(eid).props.end;
+ this.reconcileTiming(eid);
break;
}
case "fill": {
@@ -983,7 +1075,7 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
assert(typeof value === "string", "`syncTo` must be a string" + `, value: ${value}`);
assert(value.trim().length > 0, "`syncTo` must be a non-empty string");
assert(!this.committed, "`syncTo` cannot change after commit; re-mount instead");
- this.queue.push({ node, targetKey: value.trim(), type: "sync" });
+ this.queue.push({ eid, targetKey: value.trim(), type: "sync" });
break;
} case "transition": {
if (value === null) {
@@ -1031,15 +1123,15 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
resizeEntity(world, eid, placeholderSize(getAssetSpec(value)));
}
// Post-commit (live mount) nothing drains the queue; resolve now.
- if (this.committed) this.generateInto(node, value, new Map()).catch(console.error);
- else this.queue.push({ node, ref: value, type: "asset" });
+ if (this.committed) this.generateInto(eid, value, new Map()).catch(console.error);
+ else this.queue.push({ eid, ref: value, type: "asset" });
break;
}
assert(typeof value === "string", "`src` must be a string" + `, value: ${value}`);
assert(value.trim().length > 0, "`src` must be a non-empty string");
- if (this.committed) this.mountSource(node, value).catch(console.error);
- else this.promises.push(this.mountSource(node, value));
+ if (this.committed) this.mountSource(eid, value).catch(console.error);
+ else this.promises.push(this.mountSource(eid, value));
break;
} case "objectFit": {
assert(typeof value === "string", "`objectFit` must be a string" + `, value: ${value}`);
@@ -1118,7 +1210,7 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
}
break;
} case "offset": {
- assert(hasComponent(world, eid, c.ColorStop), "`offset` only applies to <colorStop>");
+ assert(hasComponent(world, eid, c.ColorStop), "`offset` only applies to <ColorStop>");
if (Array.isArray(value)) {
const keyframes = parseKeyframes(name, value, (v) => {
assert(typeof v === "number", "`offset` must be a number" + `, value: ${v}`);
@@ -1135,13 +1227,13 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
setComponent(world, eid, c.ColorStop, { offset: value });
break;
} case "preset": {
- assert(hasComponent(world, eid, c.Caption), "`preset` only applies to <captions>");
+ assert(hasComponent(world, eid, c.Caption), "`preset` only applies to <Captions>");
assert(typeof value === "string", "`preset` must be a string" + `, value: ${value}`);
assert(value in CAPTION_PRESET_MAP, `invalid preset value: "${value}"`);
setComponent(world, eid, c.Caption, { type: CAPTION_PRESET_MAP[value as keyof typeof CAPTION_PRESET_MAP] });
break;
} case "colors": {
- assert(hasComponent(world, eid, c.Caption), "`colors` only applies to <captions>");
+ assert(hasComponent(world, eid, c.Caption), "`colors` only applies to <Captions>");
assert(Array.isArray(value), "`colors` must be an array of CSS colors" + `, value: ${value}`);
const colors = value.map((entry) => {
assert(typeof entry === "string", "`colors` entries must be strings" + `, value: ${entry}`);
@@ -1155,68 +1247,84 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
}
}
- public insertNode(parent: DocumentNode, node: DocumentNode, anchor?: DocumentNode) {
- // Shadow first — re-inserting an attached node moves it (how the
- // renderer reorders), so detach it from its previous position.
- if (node.parent) {
- node.parent.children = node.parent.children.filter((child) => child !== node);
- }
- const index = anchor !== undefined ? parent.children.indexOf(anchor) : -1;
- if (index === -1) parent.children.push(node);
- else parent.children.splice(index, 0, node);
- node.parent = parent;
-
- if (parent === this.stage || parent.eid !== undefined || parent.dom !== undefined) {
- this.track(() => this.attach(parent, node, anchor));
- }
+ public insertNode(parent: HostNode, node: HostNode, anchor?: HostNode) {
+ this.track(() => this.attach(parent, node, anchor));
+ this.flushConnectedSurfaces();
}
/**
- * Inserts `node` under a live parent, materializing it first if needed.
- * The environment is the parent's: children of an <htmlPaint> (or of any
- * DOM node) become real DOM, everything else lands in the ECS world.
+ * Links `node` under its parent: DOM nodes into the parent's DOM (an
+ * <HtmlPaint>'s host element, or an element under one), entities into the
+ * ECS tree. Both sides already exist — the tag's case decided the
+ * environment at creation — so insertion only validates and links.
*/
- private attach(parent: DocumentNode, node: DocumentNode, anchor?: DocumentNode): void {
+ private attach(parent: HostNode, node: HostNode, anchor?: HostNode): void {
const world = this.world;
const c = world.components;
- const domParent = parent.host?.element ?? parent.dom;
- if (domParent !== undefined) {
- assert(domParent instanceof Element, "text nodes cannot contain children");
- if (node.dom === undefined) this.materializeDom(node, isSvgContext(domParent));
- domParent.insertBefore(node.dom!, anchor?.dom ?? null);
+ if (parent instanceof Element) {
+ assert(node instanceof Element || node instanceof Text, "a composition element cannot be <Html> content");
+ parent.insertBefore(node, anchor instanceof Node ? anchor : null);
return;
}
+ assert(parent instanceof EntityNode, "text nodes cannot contain children");
+
+ // DOM content lands in the parent's html host (the wrapper's paint host
+ // for <Html>); text runs of a <Text> element land in its Data fragment.
+ if (node instanceof Element || node instanceof Text) {
+ if (parent === STAGE) {
+ // Only Solid's empty placeholders may sit at the stage; they hold
+ // root positions in `roots` but never touch the world.
+ assert(node instanceof Text && node.data === "", "the stage cannot contain content");
+ this.insertRoot(node, anchor);
+ return;
+ }
- // Text in the ECS world is the content of a text element; anywhere else
- // only the empty placeholders Solid's control flow leaves behind pass.
- if (node.text !== undefined) {
- if (parent === this.stage) return;
- if (this.isTextEntity(parent)) {
- if (!(parent.adopted === true && !this.committed)) this.assignChars(parent);
- } else {
- assert(node.text === "", `<${parent.tag}> cannot contain text`);
+ const host = this.htmlHosts.get(parent.eid);
+ if (host !== undefined) {
+ host.element.insertBefore(node, anchor instanceof Node && anchor.parentNode === host.element ? anchor : null);
+ return;
+ }
+
+ if (this.isTextEntity(parent.eid)) {
+ assert(node instanceof Text, "a text element can only contain text");
+ const data = this.data(parent.eid);
+ if (data.textBox === undefined) {
+ data.textBox = document.createDocumentFragment();
+ this.nodeOwner.set(data.textBox, parent.eid);
+ }
+ data.textBox.insertBefore(node, anchor instanceof Node && anchor.parentNode === data.textBox ? anchor : null);
+ this.syncChars(parent.eid);
+ return;
}
+
+ // Anywhere else only the empty placeholders Solid's control flow
+ // leaves behind pass; they stay unparented and act as inert anchors.
+ assert(node instanceof Text && node.data === "", "this element cannot contain text or DOM content");
return;
}
- if (node.eid === undefined) this.materializeEcs(node);
- const eid = node.eid!;
-
- if (parent !== this.stage) {
- if (!node.adopted) this.attachEntity(eid, parent.eid!);
+ if (parent !== STAGE) {
+ assert(!this.htmlHosts.has(parent.eid), "a composition element cannot be <Html> content");
+ // Adopted entities already sit under their persisted parent, so this
+ // no-ops for them on the initial adopt render; afterwards it moves and
+ // resurrects them like any other entity (e.g. a <For> shuffling rows).
+ this.attachEntity(node.eid, parent.eid);
return;
}
+ this.insertRoot(node, anchor);
+ const eid = node.eid;
+
// An adopted root is already placed and parented in the world; re-running
// placement/replace would overwrite its persisted position and delete it.
- if (node.adopted) {
+ if (this.adopted.has(eid)) {
this.rootEid = eid;
return;
}
- if (this.stage.eid !== undefined) {
- this.attachEntity(eid, this.stage.eid);
+ if (this.stageEid !== undefined) {
+ this.attachEntity(eid, this.stageEid);
} else {
assert(hasComponent(world, eid, c.Geometry), "this element cannot be a document root");
const key = c.Key[eid];
@@ -1251,9 +1359,28 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
this.rootEid = eid;
}
+ /** Places a node into the stage's `roots` list (its only bookkeeping). */
+ private insertRoot(node: HostNode, anchor?: HostNode): void {
+ const existing = this.roots.indexOf(node);
+ if (existing !== -1) this.roots.splice(existing, 1);
+ const index = anchor !== undefined ? this.roots.indexOf(anchor) : -1;
+ if (index === -1) this.roots.push(node);
+ else this.roots.splice(index, 0, node);
+ }
+
// Fresh entities append; an entity that already has a parent is a Solid
// reorder or reparent (e.g. a <For> moving rows in a live mount).
private attachEntity(eid: number, parentEid: number): void {
+ const c = this.world.components;
+ if (hasComponent(this.world, eid, c.Deleted)) {
+ // Like a DOM node, an entity this render just removed re-attaches
+ // intact; anything something else deleted stays dead.
+ if (!this.removed.delete(eid)) return;
+ for (const e of getEntityTree(this.world, eid)) {
+ removeComponent(this.world, e, c.Deleted);
+ }
+ this.managed.add(eid);
+ }
const currentParent = getParentEntity(this.world, eid);
if (currentParent === null) {
appendChild(this.world, eid, parentEid);
@@ -1266,118 +1393,89 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
}
/**
- * Records a `ref` callback (the renderer's `use`). Refs run at
- * materialization, when the backing object exists — for canvas elements
- * the paint's canvas, for DOM nodes under an <htmlPaint> the element.
+ * A `ref` callback (the renderer's `use`). DOM elements exist eagerly, so
+ * their refs fire immediately; surface refs receive the paint's backing
+ * canvas, which is only sized once the ancestor chain exists, so they wait
+ * for the subtree to connect to the stage.
*/
- public applyRef(node: DocumentNode, ref: (target: unknown) => void): void {
- node.ref = ref;
- }
-
- /** Invokes and consumes a node's recorded ref, outside the current tracking scope. */
- private invokeRef(node: DocumentNode, target: unknown): void {
- const ref = node.ref;
- if (ref === undefined) return;
- node.ref = undefined;
- solid.untrack(() => ref(target));
+ public applyRef(node: HostNode, ref: (target: unknown) => void): void {
+ if (node instanceof Element || node instanceof Text) {
+ solid.untrack(() => ref(node));
+ return;
+ }
+ const pending = this.pendingSurfaces.find((entry) => entry.eid === node.eid);
+ assert(pending !== undefined, "`ref` is only supported on surface elements");
+ pending.ref = ref;
}
/**
* The box a canvas paint's bitmap is initially allocated at: the nearest
- * explicit size up the shadow tree (every element's box defaults to its
- * parent's), falling back to a live ancestor's computed size for mounts
- * into existing entities (`dapi node insert`).
+ * explicit size up the entity's ancestor chain (every element's box
+ * defaults to its parent's), falling back to a live ancestor's computed
+ * size for mounts into existing entities (`dapi node insert`).
*/
- private resolveBoxSize(node: DocumentNode): { width: number; height: number } {
+ private resolveBoxSize(eid: number): { width: number; height: number } {
const c = this.world.components;
let width: number | undefined;
let height: number | undefined;
- // Recorded props first — entities in the materializing subtree are fresh,
- // so their Computed sizes are defaults, not layout. Live ancestors'
+ // Recorded props first — entities in the mounted subtree are fresh, so
+ // their Computed sizes are defaults, not layout. Live ancestors'
// Computed only backstops mounts into existing entities (node insert).
- for (let cursor: DocumentNode | undefined = node; cursor !== undefined; cursor = cursor.parent) {
- width ??= sizeProp(cursor.props.width);
- height ??= sizeProp(cursor.props.height);
+ for (let cursor: number | null = eid; cursor !== null; cursor = getParentEntity(this.world, cursor)) {
+ const props = this.props(cursor);
+ width ??= sizeProp(props?.width);
+ height ??= sizeProp(props?.height);
if (width !== undefined && height !== undefined) return { width, height };
}
- for (let cursor: DocumentNode | undefined = node; cursor !== undefined; cursor = cursor.parent) {
- // Freshly created entities have an eid but no Size yet; only already
- // live ones (e.g. the target of a `node insert`) carry a real box.
- if (cursor.eid === undefined || !hasComponent(this.world, cursor.eid, c.Size)) continue;
- width ??= c.Computed.width[cursor.eid] || undefined;
- height ??= c.Computed.height[cursor.eid] || undefined;
+ for (let cursor: number | null = eid; cursor !== null; cursor = getParentEntity(this.world, cursor)) {
+ // Freshly created entities carry no Size yet; only already live ones
+ // (e.g. the target of a `node insert`) carry a real box.
+ if (!hasComponent(this.world, cursor, c.Size)) continue;
+ width ??= c.Computed.width[cursor] || undefined;
+ height ??= c.Computed.height[cursor] || undefined;
if (width !== undefined && height !== undefined) break;
}
return { width: width ?? 300, height: height ?? 150 };
}
- /**
- * Creates the entity for an element and replays its shadow state: tag
- * components, children (attached while the subtree is still detached from
- * the stage), then recorded props in authored order.
- */
- private materializeEcs(node: DocumentNode): void {
- const path = this.mountId !== undefined ? this.computeMountPath(node) : undefined;
- const adoptedEid = this.mode === "adopt" && path !== undefined
- ? this.adoptIndex?.get(path)
- : undefined;
-
- if (adoptedEid !== undefined) {
- node.eid = adoptedEid;
- node.adopted = true;
- this.reattachRuntimeHostsForTag(node);
- } else {
- node.eid = this.createEntityForTag(node);
- if (this.mountId !== undefined && path !== undefined) {
- setComponent(this.world, node.eid, this.world.components.MountPath, { mountId: this.mountId, path });
- }
- }
-
- for (const child of node.children) this.attach(node, child);
-
- // Adopted nodes keep their persisted (possibly hand-edited) values; only
- // actively re-running effects write, via setProperty after eid is set.
- if (!node.adopted) {
- for (const [name, value] of Object.entries(node.props)) this.applyEcsProperty(node, name, value);
- }
-
- if (node.surfaceHost !== undefined) {
- const box = this.resolveBoxSize(node.tag === "surfacePaint" ? node.parent ?? node : node);
- node.surfaceHost.setSize(box.width, box.height);
- this.invokeRef(node, node.surfaceHost.canvas);
- }
- assert(node.ref === undefined, `\`ref\` is not supported on <${node.tag}>`);
- }
-
- /** Index of `node` among its parent's entity-bearing (non-text) children. */
- private entitySiblingIndex(node: DocumentNode): number {
- const parent = node.parent;
- if (parent === undefined) return 0;
- let index = 0;
- for (const child of parent.children) {
- if (child === node) break;
- if (child.text === undefined) index++;
+ /** Whether the entity's ancestor chain reaches the stage. */
+ private isConnected(eid: number): boolean {
+ for (let cursor: number | null = eid; cursor !== null; cursor = getParentEntity(this.world, cursor)) {
+ if (cursor === this.stageEid) return true;
+ const handle = this.entityNodes.get(cursor);
+ if (handle !== undefined && this.roots.includes(handle)) return true;
}
- return index;
+ return false;
}
/**
- * A node's stable structural key: the index path of entity-bearing siblings
- * from the mount root down to the node. Computed identically at author and
- * adopt time (deterministic tree → matching paths), so adopt can bind the
- * re-run to the persisted entity carrying the same `MountPath`.
+ * Sizes and hands out the canvases of surfaces whose subtree just connected
+ * to the stage: the box size walks ancestor props, and Solid attaches a
+ * subtree's root last, so only now is the chain complete. Disconnected
+ * surfaces stay pending — a Solid reorder removes and re-inserts them.
*/
- private computeMountPath(node: DocumentNode): string {
- const parts: number[] = [];
- let cursor: DocumentNode | undefined = node;
- while (cursor !== undefined && cursor.parent !== undefined) {
- parts.push(this.entitySiblingIndex(cursor));
- if (cursor.parent === this.stage) break;
- cursor = cursor.parent;
- }
- return parts.reverse().join("/");
+ private flushConnectedSurfaces(): void {
+ if (this.pendingSurfaces.length === 0) return;
+ this.pendingSurfaces = this.pendingSurfaces.filter((entry) => {
+ if (!this.isConnected(entry.eid)) return true;
+
+ const boxEid = entry.paint ? getParentEntity(this.world, entry.eid) ?? entry.eid : entry.eid;
+ const box = this.resolveBoxSize(boxEid);
+ entry.host.setSize(box.width, box.height);
+ if (entry.ref !== undefined) {
+ const ref = entry.ref;
+ solid.untrack(() => ref(entry.host.canvas));
+ }
+ return false;
+ });
+ }
+
+ /** Wires an html host to the element the renderer inserts DOM content under. */
+ private registerHtmlHost(eid: number, host: HtmlHost): void {
+ this.htmlHosts.set(eid, host);
+ this.nodeOwner.set(host.element, eid);
}
/**
@@ -1385,42 +1483,41 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
* binding a fresh host to the existing (adopted) paint entity. Mirrors the
* host setup in `createEntityForTag` but never creates structural entities.
*/
- private reattachRuntimeHostsForTag(node: DocumentNode): void {
+ private reattachRuntimeHostsForTag(tag: string, eid: number): void {
const world = this.world;
const c = world.components;
- const eid = node.eid!;
- switch (node.tag) {
- case "surfacePaint": {
+ switch (tag) {
+ case "SurfacePaint": {
const host = this.trackHost(new SurfaceHost());
addComponent(world, eid, c.SurfaceHost, false);
c.SurfaceHost[eid] = host;
- node.surfaceHost = host;
+ this.pendingSurfaces.push({ eid, host, paint: true });
break;
}
- case "surface": {
+ case "Surface": {
const fid = this.findPaintChild(eid, PaintType.SURFACE);
- assert(fid !== undefined, "adopted <surface> has no surface paint child");
+ assert(fid !== undefined, "adopted <Surface> has no surface paint child");
const host = this.trackHost(new SurfaceHost());
addComponent(world, fid, c.SurfaceHost, false);
c.SurfaceHost[fid] = host;
- node.surfaceHost = host;
+ this.pendingSurfaces.push({ eid, host, paint: false });
break;
}
- case "htmlPaint": {
+ case "HtmlPaint": {
const host = this.trackHost(new HtmlHost());
addComponent(world, eid, c.HtmlHost, false);
c.HtmlHost[eid] = host;
- node.host = host;
+ this.registerHtmlHost(eid, host);
break;
}
- case "html": {
+ case "Html": {
const fid = this.findPaintChild(eid, PaintType.HTML);
- assert(fid !== undefined, "adopted <html> has no html paint child");
+ assert(fid !== undefined, "adopted <Html> has no html paint child");
const host = this.trackHost(new HtmlHost());
addComponent(world, fid, c.HtmlHost, false);
c.HtmlHost[fid] = host;
- node.host = host;
+ this.registerHtmlHost(eid, host);
break;
}
}
@@ -1436,53 +1533,86 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
return undefined;
}
- /** Builds the DOM subtree for a node under an <htmlPaint>, props applied. */
- private materializeDom(node: DocumentNode, svg: boolean): void {
- if (node.text !== undefined) {
- node.dom = document.createTextNode(node.text);
- return;
- }
- const tag = node.tag!;
- const inSvg = svg || tag === "svg";
- const el = inSvg ? document.createElementNS(SVG_NS, tag) : document.createElement(tag);
- node.dom = el;
- for (const child of node.children) {
- this.materializeDom(child, inSvg && tag !== "foreignObject");
- el.appendChild(child.dom!);
- }
- for (const [name, value] of Object.entries(node.props)) setDomProperty(el, name, value);
- this.invokeRef(node, el);
- }
-
- public removeNode(parent: DocumentNode, node: DocumentNode) {
- parent.children = parent.children.filter((child) => child !== node);
- node.parent = undefined;
-
+ public removeNode(parent: HostNode, node: HostNode) {
this.track(() => {
- if (node.dom !== undefined) {
- node.dom.remove();
- } else if (node.text !== undefined) {
- if (this.isTextEntity(parent)) this.assignChars(parent);
- } else if (node.eid !== undefined && parent !== this.stage && parent.eid !== undefined) {
+ if (node instanceof Element || node instanceof Text) {
+ const owner = node.parentNode !== null ? this.nodeOwner.get(node.parentNode) : undefined;
+ node.remove();
+ if (owner !== undefined && this.isTextEntity(owner)) this.syncChars(owner);
+ const index = this.roots.indexOf(node);
+ if (index !== -1) this.roots.splice(index, 1);
+ return;
+ }
+ if (parent === STAGE) {
+ // Stage roots persist in the world past their mount — removal only
+ // forgets the renderer's bookkeeping.
+ const index = this.roots.indexOf(node);
+ if (index !== -1) this.roots.splice(index, 1);
+ return;
+ }
+ if (parent instanceof EntityNode) {
+ // A stale removal of an already-dead entity (the old graph of a
+ // superseded mount racing its dispose) must not detach or re-arm it.
+ if (hasComponent(this.world, node.eid, this.world.components.Deleted)) return;
removeChild(this.world, node.eid, parent.eid);
deleteEntity(this.world, node.eid);
+ this.managed.delete(node.eid);
+ this.removed.add(node.eid);
}
});
}
- public getParentNode(node: DocumentNode): DocumentNode | undefined {
- return node.parent;
+ public getParentNode(node: HostNode): HostNode | undefined {
+ if (node instanceof Element || node instanceof Text) {
+ const parent = node.parentNode;
+ if (parent === null) return undefined;
+ const owner = this.nodeOwner.get(parent);
+ if (owner !== undefined) return this.entity(owner);
+ return parent instanceof Element ? parent : undefined;
+ }
+ if (this.roots.includes(node)) return STAGE;
+ const parent = getParentEntity(this.world, node.eid);
+ return parent === null ? undefined : this.entity(parent);
+ }
+
+ public getFirstChild(node: HostNode): HostNode | undefined {
+ if (node instanceof Element) return node.firstChild as Element | Text | null ?? undefined;
+ if (node instanceof Text) return undefined;
+ if (node === STAGE) return this.roots[0];
+ const host = this.htmlHosts.get(node.eid);
+ if (host !== undefined) return host.element.firstChild as Element | Text | null ?? undefined;
+ if (this.isTextEntity(node.eid)) {
+ const c = this.world.components;
+ const textBox = hasComponent(this.world, node.eid, c.Data) ? c.Data[node.eid]?.textBox : undefined;
+ return textBox?.firstChild as Text | null ?? undefined;
+ }
+ const first = this.entityChildren(node.eid)[0];
+ return first === undefined ? undefined : this.entity(first);
}
- public getFirstChild(node: DocumentNode): DocumentNode | undefined {
- return node.children[0];
+ public getNextSibling(node: HostNode): HostNode | undefined {
+ if (node instanceof Element || node instanceof Text) {
+ return node.nextSibling as Element | Text | null ?? undefined;
+ }
+ const parent = getParentEntity(this.world, node.eid);
+ if (parent === null) {
+ const index = this.roots.indexOf(node);
+ return index === -1 ? undefined : this.roots[index + 1];
+ }
+ const siblings = this.entityChildren(parent);
+ const index = siblings.indexOf(node.eid);
+ const next = index === -1 ? undefined : siblings[index + 1];
+ return next === undefined ? undefined : this.entity(next);
}
- public getNextSibling(node: DocumentNode): DocumentNode | undefined {
- const siblings = node.parent?.children;
- if (siblings === undefined) return undefined;
- const index = siblings.indexOf(node);
- return index === -1 ? undefined : siblings[index + 1];
+ /**
+ * The renderer-visible entity children of `eid`: its ECS children filtered
+ * to this render's managed set, so internal sub-entities (a <Text>'s paint)
+ * and hand-added children stay out of Solid's reconciliation.
+ */
+ private entityChildren(eid: number): number[] {
+ const c = this.world.components;
+ return [...query(this.world, [ChildOf(eid), Not(c.Deleted)])].filter((child) => this.managed.has(child));
}
private findPlacement(width: number, height: number): { x: number; y: number } {
@@ -1494,13 +1624,10 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
}
/**
- * Attaches a resolved asset to a media node — shared by plain `src` values
- * (resolved during mount) and generated assets (landing after commit).
+ * Attaches a resolved asset to a media element — shared by plain `src`
+ * values (resolved during mount) and generated assets (landing after commit).
*/
- private async mountSource(node: DocumentNode, src: string) {
- if (node.eid === undefined) return;
- const eid = node.eid;
-
+ private async mountSource(eid: number, src: string) {
const asset = await resolveAsset(this.world, src);
const transcript = asset.type === 'TRANSCRIPT' ? await resolveTranscript(asset) : null;
@@ -1518,7 +1645,7 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
} else if (asset.type === 'IMAGE' || asset.type === 'VIDEO') {
const fid = createEntity(world);
setComponent(world, fid, c.Paint, asset.type === 'IMAGE' ? PaintType.IMAGE : PaintType.VIDEO);
- const objectFit = node.props.objectFit as keyof typeof SCALE_MODE_MAP | undefined;
+ const objectFit = this.props(eid)?.objectFit as keyof typeof SCALE_MODE_MAP | undefined;
setComponent(world, fid, c.ScaleMode, objectFit ? SCALE_MODE_MAP[objectFit] : ScaleMode.COVER);
setComponent(world, fid, c.AssetId, asset.id);
appendChild(world, fid, eid);
@@ -1535,7 +1662,7 @@ export class WorldDocument implements ProjectDocument<DocumentNode> {
}
/**
- * Prop assignment for DOM nodes inside <htmlPaint>: enough of Solid's DOM
+ * Prop assignment for DOM nodes inside <HtmlPaint>: enough of Solid's DOM
* conventions (style objects, class, classList, innerHTML) for drawn markup.
* Event handlers are dropped — the content is painted, not interactive.
*/
@@ -1544,8 +1671,11 @@ function setDomProperty(el: Element, name: string, value: unknown): void {
if (name === "style") {
const style = (el as HTMLElement).style;
- if (typeof value === "string") style.cssText = value;
- else if (typeof value === "object" && value !== null) Object.assign(style, value);
+ if (typeof value === "string") {
+ style.cssText = value;
+ } else if (typeof value === "object" && value !== null) {
+ Object.assign(style, value);
+ }
} else if (name === "class" || name === "className") {
el.setAttribute("class", String(value));
} else if (name === "classList") {
diff --git a/apps/web/src/utils/mount.ts b/apps/web/src/utils/mount.ts
index 97b14ee1..f7f44b9a 100644
--- a/apps/web/src/utils/mount.ts
+++ b/apps/web/src/utils/mount.ts
@@ -5,7 +5,7 @@
import { query, Not } from "bitecs";
import { renderProject } from "@diffusionstudio/jsx";
-import { WorldDocument, importProjectModule } from "@/utils/jsx";
+import { EntityNode, WorldDocument, importProjectModule } from "@/utils/jsx";
import { getAssetFile } from "@/components/engine/api/assets";
import { assert } from "@/utils";
@@ -29,8 +29,8 @@ export interface RealizedMount {
/** Root keys of a rendered mount (its top-level entities' `Key` values). */
export function documentRootKeys(world: EngineWorld, document: WorldDocument): string[] {
const keys: string[] = [];
- for (const node of document.stage.children) {
- if (node.eid === undefined) continue;
+ for (const node of document.roots) {
+ if (!(node instanceof EntityNode)) continue;
const key = world.components.Key[node.eid];
if (key !== undefined) keys.push(key);
}
@@ -65,7 +65,7 @@ export async function renderMount(
};
}
-/** MountPath -> entity id for one mount, so adopt can bind the re-run by key. */
+/** Creation ordinal (`MountPath.path`) -> entity id for one mount, so adopt can bind the re-run. */
export function buildAdoptIndex(world: EngineWorld, mountId: string): Map<string, number> {
const c = world.components;
const index = new Map<string, number>();
diff --git a/docs/cli.md b/docs/cli.md
index e464c434..51ea8ed4 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -60,7 +60,7 @@ dapi node insert <parentId> (<path> | --code <str>) [-i, --index <N>]
Same pipeline as `mount`, but inserts the rendered roots as children of an existing entity instead of mounting document roots. Roots take no `key`; every run inserts fresh nodes. `--index` sets the position among the parent's children (node roots only). Also how you extend sub-entities, e.g. adding a stop to a gradient:
```sh
-dapi node insert <paintId> --code '<colorStop offset={0.5} color="#FF0055" />'
+dapi node insert <paintId> --code '<ColorStop offset={0.5} color="#FF0055" />'
```
### `node patch`
diff --git a/docs/composition.md b/docs/composition.md
index 5caea9da..695297d6 100644
--- a/docs/composition.md
+++ b/docs/composition.md
@@ -3,15 +3,19 @@
Compositions are **Solid JSX modules**. `dapi mount` compiles the module, runs it in the app, and renders every JSX element into an editable node in the document: no hidden DOM, no CSS, no layout pass. All positioning is explicit pixels.
```tsx
+import { Scene } from "@diffusionstudio/jsx";
+
export default function Project() {
return (
- <scene key="intro" name="Intro" width={1920} height={1080} fill="black">
+ <Scene key="intro" name="Intro" width={1920} height={1080} fill="black">
{/* ... */}
- </scene>
+ </Scene>
);
}
```
+The element import is optional at runtime — the compiler auto-imports PascalCase elements used without an in-scope binding — but explicit imports make the file typecheck (`tsc` doesn't see the auto-import).
+
The module's default export is the project component. Solid's control flow (`<For>`, `<Show>`, …) and primitives (`createSignal`, `createMemo`, …) are available to *compose* the tree; the render is one-shot: after commit, the nodes belong to the document and signal changes no longer affect it. The update path is re-running the mount.
**Dependencies:** `solid-js` and `@diffusionstudio/jsx` are provided by the app; everything else you import (npm packages, local files, JSON) is bundled by the CLI. Libraries must be browser-compatible.
@@ -24,25 +28,25 @@ Every top-level element declares its identity with a `key`:
- Keyed nodes the render no longer produces are **deleted**; the mount owns its keyed roots. Unkeyed nodes (made by hand in the editor) are never touched.
- Keys must be unique within a render. Give roots a `name` too: the key identifies, the name labels.
-The first rendered root becomes the active scene. New roots are auto-placed on the canvas near the viewport center; `<scene>` has no `x`/`y` because canvas arrangement is an editor concern, not part of the composition.
+The first rendered root becomes the active scene. New roots are auto-placed on the canvas near the viewport center; `<Scene>` has no `x`/`y` because canvas arrangement is an editor concern, not part of the composition.
## Elements
| Element | What it makes |
| --- | --- |
-| `<scene>` | A scene; clips children to its `width`×`height`. Document root only; scenes don't nest. |
-| `<group>` | Container with a transform; give it `fill` to draw a rectangle. |
-| `<rect>` | A filled rectangle. |
-| `<text>` | Editable text. |
-| `<video>` / `<image>` | Media; `src` is required. |
-| `<audio>` | Sound only, no spatial props. |
-| `<sequence>` | Track container for back-to-back clips (positions are explicit); hosts transitions. |
-| `<captions>` | Styled captions: transcribes the scene's audio, or mounts a transcript given via `src`. |
-| `<html>` | A rectangle whose children are HTML/SVG, laid out by the browser at the node's box size and drawn into it. Equivalent to a `<rect>` with an `<htmlPaint>`. |
-| `<surface>` | A rectangle whose `ref` hands you a canvas to draw yourself (2d, webgl, webgpu); the bitmap is sampled into the box every frame. Equivalent to a `<rect>` with a `<surfacePaint>`. |
-| `<solidPaint>`, `<linearGradientPaint>`, `<radialGradientPaint>`, `<colorStop>` (aliases `<solid>`, `<linearGradient>`, `<radialGradient>`, `<stop>`) | Fills, declared as children; see [Paints](#paints). |
-
-User-defined components are ordinary Solid components; only intrinsic elements produce nodes.
+| `<Scene>` | A scene; clips children to its `width`×`height`. Document root only; scenes don't nest. |
+| `<Group>` | Container with a transform; give it `fill` to draw a rectangle. |
+| `<Rect>` | A filled rectangle. |
+| `<Text>` | Editable text. |
+| `<Video>` / `<Image>` | Media; `src` is required. |
+| `<Audio>` | Sound only, no spatial props. |
+| `<Sequence>` | Track container for back-to-back clips (positions are explicit); hosts transitions. |
+| `<Captions>` | Styled captions: transcribes the scene's audio, or mounts a transcript given via `src`. |
+| `<Html>` | A rectangle whose children are HTML/SVG, laid out by the browser at the node's box size and drawn into it. Equivalent to a `<Rect>` with an `<HtmlPaint>`. |
+| `<Surface>` | A rectangle whose `ref` hands you a canvas to draw yourself (2d, webgl, webgpu); the bitmap is sampled into the box every frame. Equivalent to a `<Rect>` with a `<SurfacePaint>`. |
+| `<SolidPaint>`, `<LinearGradientPaint>`, `<RadialGradientPaint>`, `<ColorStop>` | Fills, declared as children; see [Paints](#paints). |
+
+User-defined components are ordinary Solid components; only the built-in PascalCase elements produce nodes.
### Common props
@@ -56,26 +60,26 @@ User-defined components are ordinary Solid components; only intrinsic elements p
| `opacity` | `1` | `0`–`1`. Animatable. |
| `cornerRadius` | `0` | Px. Animatable. |
| `start`, `end`, `sourceIn`, `sourceOut` | see [Timing](#timing) | Temporal placement. |
-| `transition` | none | Cut into the next clip; `<sequence>` children only. See [Transitions](#transitions). |
+| `transition` | none | Cut into the next clip; `<Sequence>` children only. See [Transitions](#transitions). |
Animatable props also take a keyframe list — see [Animation](#animation).
**Every box defaults to its parent's box**, the JSX analog of `position: absolute; inset: 0`. So a centered full-frame title is just:
```tsx
-<text textAlign="center" textBaseline="middle" fontSize={128}>Hello</text>
+<Text textAlign="center" textBaseline="middle" fontSize={128}>Hello</Text>
```
### Per-element props
-- **`<scene>`**: `key`, `width`, `height` (all required), `name`, `fill`. No timing or transform props.
-- **`<rect>` / `<group>`**: `fill` (any CSS color; alpha is ignored, use `opacity`).
-- **`<video>`**: `src` (required), `objectFit` (`"cover"` | `"contain"` | `"fill"`, default `"cover"`), `volume` (dB; `0` = unity, negative attenuates), `muted`, `syncTo` (see [Audio sync](#audio-sync)).
-- **`<image>`**: `src` (required), `objectFit` (default `"contain"`).
-- **`<audio>`**: `src` (required), `volume` (dB; `0` = unity, negative attenuates), `muted`, `syncTo`, timing props.
-- **`<text>`**: string children (required), `fontFamily` (see `dapi fonts`), `fontSize`, `fontWeight`, `fontStyle`, `fill`, `textAlign`, `textBaseline`.
-- **`<html>`**: HTML/SVG children. Fully reactive: signals in attributes, styles, and text update the drawn content. Event handlers are dropped (the content is painted, not interactive).
-- **`<surface>`**: `ref` (required, callback form) receives the backing `HTMLCanvasElement` once at materialization; draw with any context type, create effects inside the ref to redraw from signals or the ticker.
+- **`<Scene>`**: `key`, `width`, `height` (all required), `name`, `fill`. No timing or transform props.
+- **`<Rect>` / `<Group>`**: `fill` (any CSS color; alpha is ignored, use `opacity`).
+- **`<Video>`**: `src` (required), `objectFit` (`"cover"` | `"contain"` | `"fill"`, default `"cover"`), `volume` (dB; `0` = unity, negative attenuates), `muted`, `syncTo` (see [Audio sync](#audio-sync)).
+- **`<Image>`**: `src` (required), `objectFit` (default `"contain"`).
+- **`<Audio>`**: `src` (required), `volume` (dB; `0` = unity, negative attenuates), `muted`, `syncTo`, timing props.
+- **`<Text>`**: string children (required), `fontFamily` (see `dapi fonts`), `fontSize`, `fontWeight`, `fontStyle`, `fill`, `textAlign`, `textBaseline`.
+- **`<Html>`**: HTML/SVG children. Fully reactive: signals in attributes, styles, and text update the drawn content. Event handlers are dropped (the content is painted, not interactive).
+- **`<Surface>`**: `ref` (required, callback form) receives the backing `HTMLCanvasElement` once at materialization; draw with any context type, create effects inside the ref to redraw from signals or the ticker.
These same props are what `dapi node patch` assigns on existing nodes.
@@ -88,7 +92,7 @@ These same props are what `dapi node patch` assigns on existing nodes.
- an **asset id**: an imported library asset (see `dapi asset tree`)
- an **`AssetRef`**: the value returned by a `generate.*` declaration
-To read a source's raw bytes inside an effect instead of mounting it as a node, pass the same input to `useFile`, which resolves it to a `File`. It returns Solid's `createResource` tuple (`[file, { mutate, refetch }]`): the `file` accessor reads `undefined` until it resolves, then the `File`. Useful for drawing a library image onto a `<surface>` or parsing a data file:
+To read a source's raw bytes inside an effect instead of mounting it as a node, pass the same input to `useFile`, which resolves it to a `File`. It returns Solid's `createResource` tuple (`[file, { mutate, refetch }]`): the `file` accessor reads `undefined` until it resolves, then the `File`. Useful for drawing a library image onto a `<Surface>` or parsing a data file:
```tsx
import { createSignal, createEffect } from "solid-js";
@@ -104,7 +108,7 @@ createEffect(async () => {
el.getContext("2d")!.drawImage(await createImageBitmap(f), 0, 0);
});
-// <surface ref={setCanvas} width={640} height={360} />
+// <Surface ref={setCanvas} width={640} height={360} />
```
## Timing
@@ -117,35 +121,35 @@ createEffect(async () => {
| `sourceIn` / `sourceOut` | The source window to play. Default: the source's natural extent. `end` and `sourceOut` are the same out edge in timeline vs. source time. |
```tsx
-<video src="/Movies/clip.mp4" start={5} sourceIn={10} sourceOut={20} />
+<Video src="/Movies/clip.mp4" start={5} sourceIn={10} sourceOut={20} />
// plays source seconds 10-20 (a 10 s clip), beginning at timeline second 5
-<rect start={2} end={5} fill="red" />
+<Rect start={2} end={5} fill="red" />
// a sourceless node placed straight on the timeline: on screen from 2 s to 5 s
```
-`<sequence>` groups a track of back-to-back clips and hosts clip [transitions](#transitions). It does not position clips at mount — give each an explicit `start` (the next clip's `start` is the previous clip's end). In the editor it keeps children from overlapping as you drag or regroup them.
+`<Sequence>` groups a track of back-to-back clips and hosts clip [transitions](#transitions). It does not position clips at mount — give each an explicit `start` (the next clip's `start` is the previous clip's end). In the editor it keeps children from overlapping as you drag or regroup them.
### Audio sync
`syncTo` computes a node's `start` by cross-correlating its audio against another element's audio (named by `key`), so two recordings of the same take coincide on the timeline: a lav track against camera audio, two cameras, two microphones. Any pairing with audio tracks works (audio-to-video, audio-to-audio, video-to-video). `muted` silences the side that shouldn't be heard; alignment reads source content regardless of `muted` or `volume`.
```tsx
-<video key="camera" src="/Movies/take-3.mp4" sourceOut={45} muted />
-<audio src="/Movies/lav.wav" syncTo="camera" />
+<Video key="camera" src="/Movies/take-3.mp4" sourceOut={45} muted />
+<Audio src="/Movies/lav.wav" syncTo="camera" />
```
`syncTo` and `start` are mutually exclusive; `sourceIn`/`sourceOut` stay yours, and when omitted the window defaults to the overlap with the target's window. Alignment runs after generated assets land (either side may be generated), locally and cached, and blocks the mount; an alignment too weak to trust fails the mount and the node keeps its default placement.
## Transitions
-A clip inside a `<sequence>` takes a `transition` prop rendering the cut into the clip that follows it:
+A clip inside a `<Sequence>` takes a `transition` prop rendering the cut into the clip that follows it:
```tsx
-<sequence>
- <video src="/Movies/a.mp4" start={0} end={8} transition={{ type: "fadeToBlack", duration: 0.5 }} />
- <video src="/Movies/b.mp4" start={8} />
-</sequence>
+<Sequence>
+ <Video src="/Movies/a.mp4" start={0} end={8} transition={{ type: "fadeToBlack", duration: 0.5 }} />
+ <Video src="/Movies/b.mp4" start={8} />
+</Sequence>
```
| Type | Effect |
@@ -157,7 +161,7 @@ A clip inside a `<sequence>` takes a `transition` prop rendering the cut into th
| `"fadeToWhite"` | Same, through white. |
- `duration` takes any [time format](cli.md#time-values) (default 1 s) and runs centered on the cut. Timing is untouched: the clips stay back-to-back and the renderer overlaps them only while the transition runs.
-- `transition` only renders on a direct child of `<sequence>` that has a clip after it. On the last clip it waits until one follows, matching the editor's inspector; outside a sequence the engine drops it.
+- `transition` only renders on a direct child of `<Sequence>` that has a clip after it. On the last clip it waits until one follows, matching the editor's inspector; outside a sequence the engine drops it.
- It's the same transition the inspector edits, and `dapi node patch` takes it like any other prop: a partial value merges into the clip's existing transition (`{ "id": 42, "transition": { "duration": 2 } }` keeps the type), and `"transition": null` removes it.
## Animation
@@ -165,7 +169,7 @@ A clip inside a `<sequence>` takes a `transition` prop rendering the cut into th
Animatable props (`x`, `y`, `width`, `height`, `rotation`, `opacity`, `cornerRadius`, `volume`, `color`, `offset`) accept a keyframe list in place of a static value:
```tsx
-<image
+<Image
src="/photo.jpg"
start={0} end={5}
x={[
@@ -192,18 +196,18 @@ Animatable props (`x`, `y`, `width`, `height`, `rotation`, `opacity`, `cornerRad
## Paints
-A node's fill is a **paint child**; the `fill` prop is shorthand for a solid paint. Declaring paints as children unlocks gradients and stacking (later paints render on top, including over the media paint of a `<video>` or `<image>`):
+A node's fill is a **paint child**; the `fill` prop is shorthand for a solid paint. Declaring paints as children unlocks gradients and stacking (later paints render on top, including over the media paint of a `<Video>` or `<Image>`):
```tsx
-<rect width={640} height={360} cornerRadius={24}>
- <linearGradientPaint rotation={90}>
- <colorStop offset={0} color="#FF0055" />
- <colorStop offset={1} color="#0055FF" />
- </linearGradientPaint>
-</rect>
+<Rect width={640} height={360} cornerRadius={24}>
+ <LinearGradientPaint rotation={90}>
+ <ColorStop offset={0} color="#FF0055" />
+ <ColorStop offset={1} color="#0055FF" />
+ </LinearGradientPaint>
+</Rect>
```
-`<solidPaint>` takes `color` (required) and `opacity`; gradient paints take `rotation` and `opacity` and only `<colorStop>` children (`offset` and `color` required). Colors are any CSS color; alpha is ignored, use `opacity`. Each paint tag has a short alias (`<solid>`, `<linearGradient>`, `<radialGradient>`, `<stop>`); the SVG name overlap is unambiguous because tags resolve by environment. `<htmlPaint>` draws browser-laid-out HTML/SVG children into the node's box; the `<html>` element is shorthand for a `<rect>` carrying one. `<surfacePaint>` draws a canvas your `ref` callback owns into the node's box; the `<surface>` element is likewise shorthand for a `<rect>` carrying one.
+`<SolidPaint>` takes `color` (required) and `opacity`; gradient paints take `rotation` and `opacity` and only `<ColorStop>` children (`offset` and `color` required). Colors are any CSS color; alpha is ignored, use `opacity`. `<HtmlPaint>` draws browser-laid-out HTML/SVG children into the node's box; the `<Html>` element is shorthand for a `<Rect>` carrying one. `<SurfacePaint>` draws a canvas your `ref` callback owns into the node's box; the `<Surface>` element is likewise shorthand for a `<Rect>` carrying one.
## Generated assets
@@ -230,10 +234,10 @@ Declarations are pure: nothing generates until the mount commits, and refs never
## Captions
-`<captions />` inside a scene transcribes that scene's audio into a styled, timed caption node. It runs after generated assets land and [audio sync](#audio-sync) resolves (so it can caption generated voice-over at its final placement), attaches asynchronously, and is cached against the scene's audible mix, so re-mounting with unchanged audio doesn't re-transcribe.
+`<Captions />` inside a scene transcribes that scene's audio into a styled, timed caption node. It runs after generated assets land and [audio sync](#audio-sync) resolves (so it can caption generated voice-over at its final placement), attaches asynchronously, and is cached against the scene's audible mix, so re-mounting with unchanged audio doesn't re-transcribe.
```tsx
-<captions preset="spotlight" colors={["#FF0055"]} />
+<Captions preset="spotlight" colors={["#FF0055"]} />
```
### Manual captions
@@ -241,7 +245,7 @@ Declarations are pure: nothing generates until the mount commits, and refs never
`src` supplies the transcript instead of transcribing: a path, URL, or asset id of an `.srt` or `.vtt` subtitle file, or a transcript `.json` (the `dapi transcribe` output format: `[{ text, words: [{ text, start, end }] }]`, times in seconds). Subtitle cues carry no word timings, so word-level presets highlight on timings synthesized within each cue.
```tsx
-<captions src="./subtitles.srt" preset="classic" />
+<Captions src="./subtitles.srt" preset="classic" />
```
Times are scene-relative; set `start` to shift the whole caption track when the transcript was written against a clip that begins later in the scene.
@@ -280,4 +284,4 @@ The CLI strips types without checking them; run `tsc --noEmit` for type safety.
## Errors
-Compile errors surface on stderr before the app is contacted. Evaluate/mount errors (invalid props, a root without `key`, nested `<scene>`, an unknown or cyclic `syncTo` key, …) abort with **nothing inserted**. Generation errors surface after all generations settle; the mounted tree stays committed and the affected placeholder is left without media. Audio-sync failures (no decodable audio, no reliable alignment) surface the same way; the node keeps its default placement. Runtime errors map back to your source via sourcemaps.
+Compile errors surface on stderr before the app is contacted. Evaluate/mount errors (invalid props, a root without `key`, nested `<Scene>`, an unknown or cyclic `syncTo` key, …) abort with **nothing inserted**. Generation errors surface after all generations settle; the mounted tree stays committed and the affected placeholder is left without media. Audio-sync failures (no decodable audio, no reliable alignment) surface the same way; the node keeps its default placement. Runtime errors map back to your source via sourcemaps.
diff --git a/docs/getting-started.md b/docs/getting-started.md
index b9fd4d89..906bb8dc 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -50,9 +50,9 @@ dapi asset tree # the media library as a folder tree
Compositions are Solid JSX modules rendered into the document with `dapi mount`. For a one-liner, pass code inline:
```sh
-dapi mount --code '<scene key="hello" name="Hello" width={1920} height={1080} fill="black">
- <text textAlign="center" textBaseline="middle" fontSize={120} fill="white">Hello World</text>
-</scene>'
+dapi mount --code '<Scene key="hello" name="Hello" width={1920} height={1080} fill="black">
+ <Text textAlign="center" textBaseline="middle" fontSize={120} fill="white">Hello World</Text>
+</Scene>'
```
The `key` is the scene's stable identity: re-running the mount rebuilds that scene in place instead of adding a copy. For anything real, put the module in a file (`dapi mount hero.tsx`) and see [Writing compositions](composition.md).
diff --git a/package.json b/package.json
index c922e5f4..16dbb2f6 100644
--- a/package.json
+++ b/package.json
@@ -15,6 +15,6 @@
"make": "npm run make --workspace=@diffusionstudio/desktop",
"release": "node scripts/release.mjs",
"lint": "npm run lint --workspaces --if-present",
- "check": "npm run check --workspaces --if-present"
+ "check": "npm run check --workspaces --if-present && tsc -p samples --noEmit"
}
}
diff --git a/packages/jsx/README.md b/packages/jsx/README.md
index 464cdbe2..9ec52922 100644
--- a/packages/jsx/README.md
+++ b/packages/jsx/README.md
@@ -7,19 +7,19 @@ with `dapi mount`; every JSX element becomes an editable node in the
composition — there is no hidden DOM, no CSS resolution, and no measuring pass.
```tsx
-import { generate } from "@diffusionstudio/jsx";
+import { Captions, Image, Scene, Text, generate } from "@diffusionstudio/jsx";
const hero = generate.image({ prompt: "A neon city at night, cinematic" });
export default function Project() {
return (
- <scene key="intro" name="Intro" width={1920} height={1080}>
- <image src={hero} />
- <text textAlign="center" textBaseline="middle" fontSize={128} fontWeight="bold">
+ <Scene key="intro" name="Intro" width={1920} height={1080}>
+ <Image src={hero} />
+ <Text textAlign="center" textBaseline="middle" fontSize={128} fontWeight="bold">
Hello World
- </text>
- <captions />
- </scene>
+ </Text>
+ <Captions />
+ </Scene>
);
}
```
diff --git a/packages/jsx/src/elements.ts b/packages/jsx/src/elements.ts
new file mode 100644
index 00000000..7a6891f9
--- /dev/null
+++ b/packages/jsx/src/elements.ts
@@ -0,0 +1,69 @@
+/* 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 composition elements, as PascalCase components. A capitalized JSX tag
+ * compiles to a component reference, so hosts receive PascalCase tags for
+ * composition elements and lowercase tags only for DOM content under
+ * `<HtmlPaint>` — `createElement` can tell them apart by case alone. The
+ * compile step lists these names as babel `builtIns`, so project files use
+ * them without imports.
+ */
+
+import { splitProps } from "solid-js";
+import { createElement, spread, use } from "./renderer";
+
+import type { JSX as SolidJSX } from "solid-js";
+import type {
+ AudioProps,
+ CaptionsProps,
+ ColorStopProps,
+ GradientPaintProps,
+ GroupProps,
+ HtmlPaintProps,
+ HtmlProps,
+ ImageProps,
+ RectProps,
+ SceneProps,
+ SequenceProps,
+ SolidPaintProps,
+ SurfacePaintProps,
+ SurfaceProps,
+ TextProps,
+ VideoProps,
+} from "./types";
+
+/**
+ * A component wrapping one host element: creates the node, routes `ref`
+ * through the renderer's `use` (so hosts with `applyRef` hand the callback
+ * the backing object, e.g. a surface's canvas), and spreads the remaining
+ * props and children reactively.
+ */
+function hostElement<P extends object>(tag: string): (props: P) => SolidJSX.Element {
+ return (props) => {
+ const el = createElement(tag);
+ const [local, rest] = splitProps(props as P & { ref?: unknown }, ["ref"]);
+ if (typeof local.ref === "function") use(local.ref as (target: unknown) => void, el);
+ spread(el, rest, false);
+ return el as SolidJSX.Element;
+ };
+}
+
+export const Scene = hostElement<SceneProps>("Scene");
+export const Group = hostElement<GroupProps>("Group");
+export const Rect = hostElement<RectProps>("Rect");
+export const Video = hostElement<VideoProps>("Video");
+export const Image = hostElement<ImageProps>("Image");
+export const Audio = hostElement<AudioProps>("Audio");
+export const Text = hostElement<TextProps>("Text");
+export const Sequence = hostElement<SequenceProps>("Sequence");
+export const Captions = hostElement<CaptionsProps>("Captions");
+export const SolidPaint = hostElement<SolidPaintProps>("SolidPaint");
+export const LinearGradientPaint = hostElement<GradientPaintProps>("LinearGradientPaint");
+export const RadialGradientPaint = hostElement<GradientPaintProps>("RadialGradientPaint");
+export const ColorStop = hostElement<ColorStopProps>("ColorStop");
+export const HtmlPaint = hostElement<HtmlPaintProps>("HtmlPaint");
+export const Html = hostElement<HtmlProps>("Html");
+export const SurfacePaint = hostElement<SurfacePaintProps>("SurfacePaint");
+export const Surface = hostElement<SurfaceProps>("Surface");
diff --git a/packages/jsx/src/index.ts b/packages/jsx/src/index.ts
index c9183355..8c7906f5 100644
--- a/packages/jsx/src/index.ts
+++ b/packages/jsx/src/index.ts
@@ -15,6 +15,25 @@ export type {
} from "./generate";
export { PATCH_PROP_KEYS } from "./types";
export { parseTime, TIME_FPS } from "./time";
+export {
+ Audio,
+ Captions,
+ ColorStop,
+ Group,
+ Html,
+ HtmlPaint,
+ Image,
+ LinearGradientPaint,
+ RadialGradientPaint,
+ Rect,
+ Scene,
+ Sequence,
+ SolidPaint,
+ Surface,
+ SurfacePaint,
+ Text,
+ Video,
+} from "./elements";
export { useTicker, useFile } from "./renderer";
export type { Ticker } from "./renderer";
export type {
diff --git a/packages/jsx/src/jsx-runtime.ts b/packages/jsx/src/jsx-runtime.ts
index d4a38861..44c28800 100644
--- a/packages/jsx/src/jsx-runtime.ts
+++ b/packages/jsx/src/jsx-runtime.ts
@@ -7,41 +7,18 @@
* compiled by babel-preset-solid (universal mode) against the renderer in
* "./renderer", so this module carries no runtime — only the JSX namespace
* TypeScript resolves element and prop types from.
+ *
+ * Composition elements are the PascalCase components in "./elements";
+ * intrinsic (lowercase) tags are exclusively DOM vocabulary for `<HtmlPaint>`
+ * content, so the case of a tag decides its environment.
*/
import type { JSX as SolidJSX } from "solid-js";
-import type {
- AudioProps,
- CaptionsProps,
- ColorStopProps,
- GradientPaintProps,
- GroupProps,
- HtmlPaintProps,
- HtmlProps,
- ImageProps,
- RectProps,
- SceneProps,
- SequenceProps,
- SolidPaintProps,
- SurfacePaintProps,
- SurfaceProps,
- TextProps,
- VideoProps,
-} from "./types";
-// "audio", "video" and "html" are dropped because in composition context those
-// tags mean the node elements, not DOM tags. "canvas" is dropped for a separate
-// reason: a DOM canvas's content doesn't survive drawElementImage, so it is
-// useless inside a paint host (draw with <surface> instead).
-type HtmlElementTags = Omit<SolidJSX.HTMLElementTags, "audio" | "video" | "html" | "canvas">;
-
-// SVG vocabulary for <htmlPaint> content. Tags the editor also declares keep
-// their composition types below; the runtime resolves the actual meaning by
-// environment, the type system approximates with the composition side.
-type SvgElementTags = Omit<
- SolidJSX.SVGElementTags,
- "image" | "linearGradient" | "radialGradient" | "rect" | "stop" | "text"
->;
+// "canvas" is dropped: a DOM canvas's content doesn't survive
+// drawElementImage, so it is useless inside a paint host (draw with
+// <Surface> instead).
+type HtmlElementTags = Omit<SolidJSX.HTMLElementTags, "canvas">;
export declare namespace JSX {
// Solid's Element type keeps Solid's control flow (<For>, <Show>, …) and
@@ -52,27 +29,5 @@ export declare namespace JSX {
children: unknown;
}
- export interface IntrinsicElements extends HtmlElementTags, SvgElementTags {
- scene: SceneProps;
- group: GroupProps;
- rect: RectProps;
- video: VideoProps;
- image: ImageProps;
- audio: AudioProps;
- text: TextProps;
- sequence: SequenceProps;
- captions: CaptionsProps;
- solidPaint: SolidPaintProps;
- solid: SolidPaintProps;
- linearGradientPaint: GradientPaintProps;
- linearGradient: GradientPaintProps;
- radialGradientPaint: GradientPaintProps;
- radialGradient: GradientPaintProps;
- colorStop: ColorStopProps;
- stop: ColorStopProps;
- htmlPaint: HtmlPaintProps;
- html: HtmlProps;
- surfacePaint: SurfacePaintProps;
- surface: SurfaceProps;
- }
+ export interface IntrinsicElements extends HtmlElementTags, SolidJSX.SVGElementTags {}
}
diff --git a/packages/jsx/src/renderer.ts b/packages/jsx/src/renderer.ts
index 9ba4b9f6..b4dbc20f 100644
--- a/packages/jsx/src/renderer.ts
+++ b/packages/jsx/src/renderer.ts
@@ -134,7 +134,7 @@ export function useTicker(): Ticker {
* if (!el || !f) return;
* el.getContext("2d")!.drawImage(await createImageBitmap(f), 0, 0);
* });
- * // <surface ref={setCanvas} width={640} height={360} />
+ * // <Surface ref={setCanvas} width={640} height={360} />
* ```
*/
export function useFile(src: AssetInput): ResourceReturn<File> {
diff --git a/packages/jsx/src/types.ts b/packages/jsx/src/types.ts
index 650703f6..bc100094 100644
--- a/packages/jsx/src/types.ts
+++ b/packages/jsx/src/types.ts
@@ -132,7 +132,7 @@ export type PatchProps = {
height?: Animatable<number>;
/** Rotation in degrees. Animatable. */
rotation?: Animatable<number>;
- /** Opacity, 0–1. Animatable. */
+ /** Opacity, 0–1 (out-of-range values clamp, like CSS). Animatable. */
opacity?: Animatable<number>;
/** Uniform corner radius, px. Animatable. */
cornerRadius?: Animatable<number>;
@@ -152,7 +152,7 @@ export type PatchProps = {
syncTo?: string;
/**
* Transition into the next clip, rendered centered on the cut, set on the
- * outgoing clip. Only on direct children of `<sequence>`; a partial value
+ * outgoing clip. Only on direct children of `<Sequence>`; a partial value
* merges into the clip's existing transition, `null` removes it.
*/
transition?: TransitionSpec | null;
@@ -164,12 +164,12 @@ export type PatchProps = {
/** Any CSS color, applied to the node's solid fill (created if absent); alpha is ignored — use `opacity`. */
fill?: string;
/**
- * Path, URL, asset id, or a `generate.*` declaration. On `<captions>` a
+ * Path, URL, asset id, or a `generate.*` declaration. On `<Captions>` a
* transcript source (.srt, .vtt, or transcript .json) mounted instead of
* transcribing the scene; `generate.*` is not accepted there.
*/
src?: string | AssetRef;
- /** How the source maps into the box. Default "cover" on `<video>`, "contain" on `<image>`. */
+ /** How the source maps into the box. Default "cover" on `<Video>`, "contain" on `<Image>`. */
objectFit?: Fit;
/** Decibels: 0 = unity gain, negative attenuates (-6 ≈ half as loud), -Infinity = silence. Use `muted` to silence. Animatable. */
volume?: Animatable<number>;
@@ -182,7 +182,7 @@ export type PatchProps = {
/** CSS weights 100–900, or "normal" / "bold". */
fontWeight?: number | "normal" | "bold";
fontStyle?: "normal" | "italic";
- /** Any CSS color: the glyph color on `<text>`, the paint color on paints and color stops. Animatable. */
+ /** Any CSS color: the glyph color on `<Text>`, the paint color on paints and color stops. Animatable. */
color?: Animatable<string>;
/** Horizontal alignment of glyphs within the box. Default "left". */
textAlign?: "left" | "center" | "right";
@@ -190,7 +190,7 @@ export type PatchProps = {
textBaseline?: "top" | "middle" | "bottom";
/** Position along the gradient, 0–1. Animatable. */
offset?: Animatable<number>;
- /** Caption style preset — `<captions>` only. Default "classic". */
+ /** Caption style preset — `<Captions>` only. Default "classic". */
preset?: CaptionPreset;
/** Fills the caption preset's color slots in order; any CSS color, alpha is ignored. */
colors?: string[];
@@ -262,7 +262,7 @@ export type GroupProps = CommonProps & Pick<PatchProps, "fill"> & {
};
export type RectProps = CommonProps & Pick<PatchProps, "fill"> & {
- /** Paint children (`<solidPaint>`, `<linearGradientPaint>`, `<radialGradientPaint>`). */
+ /** Paint children (`<SolidPaint>`, `<LinearGradientPaint>`, `<RadialGradientPaint>`). */
children?: SolidJSX.Element;
};
@@ -271,7 +271,7 @@ export type SolidPaintProps = Required<Pick<PatchProps, "color">> & Pick<PatchPr
export type GradientPaintProps = Pick<PatchProps, "opacity"> & {
/** Gradient rotation in degrees. Defaults to 0 (left to right). */
rotation?: number;
- /** `<colorStop>` children — the gradient's color stops. */
+ /** `<ColorStop>` children — the gradient's color stops. */
children?: SolidJSX.Element;
};
@@ -295,7 +295,7 @@ export type HtmlPaintProps = Pick<PatchProps, "opacity"> & {
children?: SolidJSX.Element;
};
-/** `<html>` — a rectangle carrying an `<htmlPaint>` with the given children. */
+/** `<Html>` — a rectangle carrying an `<HtmlPaint>` with the given children. */
export type HtmlProps = CommonProps & Pick<HtmlPaintProps, "children">;
// HTMLCanvasElement without requiring the DOM lib (this package also
@@ -314,7 +314,7 @@ export type SurfacePaintProps = Pick<PatchProps, "opacity"> & {
ref: (canvas: HostCanvas) => void;
};
-/** `<surface>` — a rectangle carrying a `<surfacePaint>` with the given ref. */
+/** `<Surface>` — a rectangle carrying a `<SurfacePaint>` with the given ref. */
export type SurfaceProps = CommonProps & Pick<SurfacePaintProps, "ref">;
export type AudioProps = TimingProps &
diff --git a/samples/reconciler/01-static-tree.tsx b/samples/reconciler/01-static-tree.tsx
index 606c7885..d0bab0a5 100644
--- a/samples/reconciler/01-static-tree.tsx
+++ b/samples/reconciler/01-static-tree.tsx
@@ -11,23 +11,25 @@
* Re-mounting replaces the scene in place (same key, same position).
*/
+import { ColorStop, Group, LinearGradientPaint, Rect, Scene, Text } from "@diffusionstudio/jsx";
+
export default () => (
- <scene key="sample-static" name="Static tree" width={960} height={540} fill="#101014">
- <group x={40} y={40}>
- <rect width={200} height={120} cornerRadius={16} fill="#ff4466" />
- <rect x={220} width={200} height={120} rotation={8} opacity={0.8}>
- <linearGradient>
- <stop offset={0} color="#22ccff" />
- <stop offset={1} color="#7744ff" opacity={0.5} />
- </linearGradient>
- </rect>
- </group>
+ <Scene key="sample-static" name="Static tree" width={960} height={540} fill="#101014">
+ <Group x={40} y={40}>
+ <Rect width={200} height={120} cornerRadius={16} fill="#ff4466" />
+ <Rect x={220} width={200} height={120} rotation={8} opacity={0.8}>
+ <LinearGradientPaint>
+ <ColorStop offset={0} color="#22ccff" />
+ <ColorStop offset={1} color="#7744ff" opacity={0.5} />
+ </LinearGradientPaint>
+ </Rect>
+ </Group>
- <text x={40} y={220} fontSize={48} fontFamily="Inter" fontWeight={700}>
+ <Text x={40} y={220} fontSize={48} fontFamily="Inter" fontWeight={700}>
sum = {6 * 7}
- </text>
+ </Text>
- <rect
+ <Rect
x={40}
y={320}
width={160}
@@ -37,5 +39,5 @@ export default () => (
end={3}
animations={[{ type: "fade", phase: "in", duration: 0.5 }]}
/>
- </scene>
+ </Scene>
);
diff --git a/samples/reconciler/02-live-signals.tsx b/samples/reconciler/02-live-signals.tsx
index 8a2b374f..734283db 100644
--- a/samples/reconciler/02-live-signals.tsx
+++ b/samples/reconciler/02-live-signals.tsx
@@ -12,13 +12,14 @@
*/
import { Show, createSignal } from "solid-js";
+import { Rect, Scene, Text } from "@diffusionstudio/jsx";
const [n, setN] = createSignal(0);
setInterval(() => setN(n() + 1), 400);
export default () => (
- <scene key="sample-live" name="Live signals" width={960} height={540} fill="#101014">
- <rect
+ <Scene key="sample-live" name="Live signals" width={960} height={540} fill="#101014">
+ <Rect
x={40 + (n() * 24) % 700}
y={60}
width={120}
@@ -27,13 +28,13 @@ export default () => (
fill={n() % 2 === 0 ? "#2288ff" : "#22ccff"}
/>
- <text x={40} y={260} fontSize={64} fontFamily="Inter">
+ <Text x={40} y={260} fontSize={64} fontFamily="Inter">
tick {n()}
- </text>
+ </Text>
<Show when={n() % 4 < 2}>
- <rect x={40} y={380} width={80} height={80} fill="#44dd88" />
- <text x={140} y={400} fontSize={36}>on air</text>
+ <Rect x={40} y={380} width={80} height={80} fill="#44dd88" />
+ <Text x={140} y={400} fontSize={36}>on air</Text>
</Show>
- </scene>
+ </Scene>
);
diff --git a/samples/reconciler/03-live-list.tsx b/samples/reconciler/03-live-list.tsx
index 6117379b..be84b4f2 100644
--- a/samples/reconciler/03-live-list.tsx
+++ b/samples/reconciler/03-live-list.tsx
@@ -10,6 +10,7 @@
*/
import { For, createSignal } from "solid-js";
+import { Group, Rect, Scene, Text } from "@diffusionstudio/jsx";
const COLORS: Record<string, string> = {
A: "#ff4466",
@@ -27,16 +28,16 @@ setInterval(() => {
}, 4000);
export default () => (
- <scene key="sample-list" name="Live list" width={960} height={540} fill="#101014">
+ <Scene key="sample-list" name="Live list" width={960} height={540} fill="#101014">
<For each={items()}>
{(label, i) => (
- <group x={40 + i() * 180} y={180}>
- <rect width={150} height={150} cornerRadius={16} fill={COLORS[label]} />
- <text x={55} y={45} fontSize={56} fontFamily="Inter" fontWeight={700}>
+ <Group x={40 + i() * 180} y={180}>
+ <Rect width={150} height={150} cornerRadius={16} fill={COLORS[label]} />
+ <Text x={55} y={45} fontSize={56} fontFamily="Inter" fontWeight={700}>
{label}
- </text>
- </group>
+ </Text>
+ </Group>
)}
</For>
- </scene>
+ </Scene>
);
diff --git a/samples/reconciler/04-ticker.tsx b/samples/reconciler/04-ticker.tsx
index 0d09f044..e82df504 100644
--- a/samples/reconciler/04-ticker.tsx
+++ b/samples/reconciler/04-ticker.tsx
@@ -9,14 +9,14 @@
*/
import { Show } from "solid-js";
-import { useTicker } from "@diffusionstudio/jsx";
+import { Rect, Scene, Text, useTicker } from "@diffusionstudio/jsx";
export default () => {
const { time, frame, playing } = useTicker();
return (
- <scene key="sample-ticker" name="Ticker" width={960} height={540} fill="#101014">
- <rect
+ <Scene key="sample-ticker" name="Ticker" width={960} height={540} fill="#101014">
+ <Rect
x={420 + Math.round(Math.cos(time() * 2) * 300)}
y={220 + Math.round(Math.sin(time() * 2) * 150)}
width={100}
@@ -25,13 +25,13 @@ export default () => {
fill="#ffaa22"
/>
- <text x={40} y={40} fontSize={40} fontFamily="Inter">
+ <Text x={40} y={40} fontSize={40} fontFamily="Inter">
t = {time().toFixed(2)}s / frame {frame()}
- </text>
+ </Text>
<Show when={playing()}>
- <text x={40} y={460} fontSize={36} fontWeight={700}>PLAYING</text>
+ <Text x={40} y={460} fontSize={36} fontWeight={700}>PLAYING</Text>
</Show>
- </scene>
+ </Scene>
);
};
diff --git a/samples/reconciler/05-html-paint.tsx b/samples/reconciler/05-html-paint.tsx
index ba7d3c24..ae8ed67d 100644
--- a/samples/reconciler/05-html-paint.tsx
+++ b/samples/reconciler/05-html-paint.tsx
@@ -1,31 +1,30 @@
/* @jsxImportSource @diffusionstudio/jsx */
-/* Environment split: the same tags mean different things per context.
+/* Environment split: tag case decides the environment.
*
* dapi mount samples/reconciler/05-html-paint.tsx
*
* Requires the html-in-canvas API (chrome://flags/#canvas-draw-element;
* not available in Electron 35, so use a supporting build): without it the
- * mount fails cleanly at <html> materialization.
+ * mount fails cleanly at <Html> materialization.
*
- * The left <rect> is an ECS entity. <html> is a node too (a rect carrying an
- * <htmlPaint>), but its children are browser DOM: <rect> inside it is an SVG
- * element (namespace inherited from <svg>), <div> is plain HTML, and the
- * counter text updates reactively in the drawn DOM. Note the type-level
- * approximation: shared tag names keep their composition prop types
- * everywhere, so the SVG <rect> below sticks to numeric props that satisfy
- * both sides.
+ * The left <Rect> is an ECS entity. <Html> is a node too (a rect carrying an
+ * <HtmlPaint>), but its children are browser DOM: PascalCase tags are
+ * composition elements, lowercase tags are always DOM — the <rect> inside
+ * <svg> below is the SVG element, <div> is plain HTML, and the counter text
+ * updates reactively in the drawn DOM.
*/
import { createSignal } from "solid-js";
+import { Html, Rect, Scene } from "@diffusionstudio/jsx";
const [n, setN] = createSignal(0);
setInterval(() => setN(n() + 1), 500);
export default () => (
- <scene key="sample-html" name="HTML paint" width={960} height={540} fill="#101014">
- <rect x={40} y={120} width={200} height={300} cornerRadius={16} fill="#22ccff" />
+ <Scene key="sample-html" name="HTML paint" width={960} height={540} fill="#101014">
+ <Rect x={40} y={120} width={200} height={300} cornerRadius={16} fill="#22ccff" />
- <html x={280} y={60} width={640} height={420}>
+ <Html x={280} y={60} width={640} height={420}>
<div style={{ color: "white", "font-family": "Inter", "font-size": "28px", padding: "16px" }}>
DOM counter: {n()}
</div>
@@ -34,6 +33,6 @@ export default () => (
<circle cx={140 + (n() % 3) * 15} cy={35} r={20} fill="#44dd88" />
<path d="M 10 80 H 190" stroke="#ffaa22" stroke-width={4} />
</svg>
- </html>
- </scene>
+ </Html>
+ </Scene>
);
diff --git a/samples/reconciler/06-anime-timeline.tsx b/samples/reconciler/06-anime-timeline.tsx
index 275966de..d4394945 100644
--- a/samples/reconciler/06-anime-timeline.tsx
+++ b/samples/reconciler/06-anime-timeline.tsx
@@ -7,14 +7,14 @@
* timeline tweens plain-object targets; a createEffect seeks it to the
* scene playhead (looping over the timeline length) and mirrors the values
* into a store. The same values drive an ECS chip on the canvas and a DOM
- * card drawn via <html>, so scrubbing or playing keeps both in lockstep,
+ * card drawn via <Html>, so scrubbing or playing keeps both in lockstep,
* including the shared hue. Deterministic: same playhead, same picture.
*/
import { createEffect } from "solid-js";
import { createStore } from "solid-js/store";
import { createTimeline } from "animejs";
-import { useTicker } from "@diffusionstudio/jsx";
+import { Html, Rect, Scene, useTicker } from "@diffusionstudio/jsx";
const chip = { x: -160, y: 190, rotation: -90, cornerRadius: 12, opacity: 0 };
const card = { rise: 90, opacity: 0, progress: 0, hue: 210 };
@@ -40,8 +40,8 @@ export default () => {
const hue = () => Math.round(v.card.hue);
return (
- <scene key="sample-anime" name="Anime timeline" width={960} height={540} fill="#101014">
- <rect
+ <Scene key="sample-anime" name="Anime timeline" width={960} height={540} fill="#101014">
+ <Rect
x={v.chip.x}
y={v.chip.y}
width={160}
@@ -52,7 +52,7 @@ export default () => {
fill={`hsl(${hue()} 90% 60%)`}
/>
- <html x={380} y={120} width={500} height={300}>
+ <Html x={380} y={120} width={500} height={300}>
<div
style={{
"font-family": "Inter",
@@ -82,7 +82,7 @@ export default () => {
{Math.round(v.card.progress)}% through the loop
</div>
</div>
- </html>
- </scene>
+ </Html>
+ </Scene>
);
};
diff --git a/samples/reconciler/07-anime-mini.tsx b/samples/reconciler/07-anime-mini.tsx
index a972a210..2788690a 100644
--- a/samples/reconciler/07-anime-mini.tsx
+++ b/samples/reconciler/07-anime-mini.tsx
@@ -4,7 +4,7 @@
*/
import { createEffect, createSignal } from "solid-js";
import { createTimeline } from "animejs";
-import { useTicker } from "@diffusionstudio/jsx";
+import { Html, Rect, Scene, useTicker } from "@diffusionstudio/jsx";
const box = { x: 60, spin: 0, pct: 0 };
@@ -22,14 +22,14 @@ export default function HtmlInCanvasDemo() {
});
return (
- <scene key="sample-anime-mini" name="Anime mini" width={960} height={540} fill="#101014">
- <rect x={v().x} y={280} width={140} height={140} rotation={v().spin} cornerRadius={28} fill="#22ccff" />
+ <Scene key="sample-anime-mini" name="Anime mini" width={960} height={540} fill="#101014">
+ <Rect x={v().x} y={280} width={140} height={140} rotation={v().spin} cornerRadius={28} fill="#22ccff" />
- <html x={60} y={90} width={840} height={120} name="Live HTML">
+ <Html x={60} y={90} width={840} height={120} name="Live HTML">
<div style="color: white; font-family: Inter; font-size: 60px; font-weight: 700">
Timeline at <span style="color: #22ccff">{Math.round(v().pct)}%</span>
</div>
- </html>
- </scene>
+ </Html>
+ </Scene>
);
};
diff --git a/samples/reconciler/08-surface-paint.tsx b/samples/reconciler/08-surface-paint.tsx
index 2dbbb0d8..b4a5dfd6 100644
--- a/samples/reconciler/08-surface-paint.tsx
+++ b/samples/reconciler/08-surface-paint.tsx
@@ -1,5 +1,5 @@
/* @jsxImportSource @diffusionstudio/jsx */
-/* Ref-provided canvas: the <surface> element hands its backing bitmap to the
+/* Ref-provided canvas: the <Surface> element hands its backing bitmap to the
* ref callback, which owns it from then on.
*
* dapi mount samples/reconciler/08-surface-paint.tsx
@@ -7,11 +7,11 @@
* The ref runs once at materialization, inside the mount's reactive owner:
* the effect below redraws from a signal and the playhead ticker, and the
* engine samples the bitmap into the node's box every frame. The standalone
- * <surfacePaint> on the right stacks over a solid fill inside a plain <rect>.
+ * <SurfacePaint> on the right stacks over a solid fill inside a plain <Rect>.
*/
import { createEffect, createSignal } from "solid-js";
-import { useTicker } from "@diffusionstudio/jsx";
+import { Scene, Surface, useTicker } from "@diffusionstudio/jsx";
export default () => {
const { time } = useTicker();
@@ -37,8 +37,8 @@ export default () => {
});
return (
- <scene key="sample-surface" name="Surface paint" width={960} height={540} fill="#101014">
- <surface
+ <Scene key="sample-surface" name="Surface paint" width={960} height={540} fill="#101014">
+ <Surface
x={40}
y={60}
width={520}
@@ -46,6 +46,6 @@ export default () => {
cornerRadius={16}
ref={setCanvas}
/>
- </scene>
+ </Scene>
);
};
diff --git a/samples/reconciler/09-three-helmet.tsx b/samples/reconciler/09-three-helmet.tsx
index 3d1c28e7..bfa155e8 100644
--- a/samples/reconciler/09-three-helmet.tsx
+++ b/samples/reconciler/09-three-helmet.tsx
@@ -1,9 +1,9 @@
/* @jsxImportSource @diffusionstudio/jsx */
-/* Three.js owning a <surface>: a glTF helmet spun by the playhead.
+/* Three.js owning a <Surface>: a glTF helmet spun by the playhead.
*
* dapi mount samples/reconciler/09-three-helmet.tsx
*
- * The <surface> ref hands three.js a detached HTMLCanvasElement to render into;
+ * The <Surface> ref hands three.js a detached HTMLCanvasElement to render into;
* the engine samples that bitmap into the node's box every frame, so a WebGL
* scene composites like any other paint (needs preserveDrawingBuffer so the
* per-frame readback doesn't come back blank). One clock drives everything:
@@ -17,7 +17,7 @@
*/
import { createEffect, createSignal, onCleanup } from "solid-js";
-import { useTicker } from "@diffusionstudio/jsx";
+import { Scene, Surface, useTicker } from "@diffusionstudio/jsx";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
@@ -96,8 +96,8 @@ export default () => {
};
return (
- <scene key="sample-three" name="Three helmet" width={960} height={540} fill="#0b0d12">
- <surface x={0} y={0} width={960} height={540} ref={setup} />
- </scene>
+ <Scene key="sample-three" name="Three helmet" width={960} height={540} fill="#0b0d12">
+ <Surface x={0} y={0} width={960} height={540} ref={setup} />
+ </Scene>
);
};
diff --git a/samples/reconciler/README.md b/samples/reconciler/README.md
index d21bd8e4..4fbd03f6 100644
--- a/samples/reconciler/README.md
+++ b/samples/reconciler/README.md
@@ -9,11 +9,11 @@ Run from the repo root with the editor open:
| [02-live-signals.tsx](02-live-signals.tsx) | `dapi mount samples/reconciler/02-live-signals.tsx` | reactive props, replaceText, Show insert/remove |
| [03-live-list.tsx](03-live-list.tsx) | `dapi mount samples/reconciler/03-live-list.tsx` | \<For\> moves (reorder without recreate), list insert/remove |
| [04-ticker.tsx](04-ticker.tsx) | `dapi mount samples/reconciler/04-ticker.tsx` | useTicker playhead reactivity (press play) |
-| [05-html-paint.tsx](05-html-paint.tsx) | `dapi mount samples/reconciler/05-html-paint.tsx` | DOM/SVG materialization under \<html\>; needs html-in-canvas |
-| [06-anime-timeline.tsx](06-anime-timeline.tsx) | `dapi mount samples/reconciler/06-anime-timeline.tsx` | anime.js timeline seeked from useTicker, driving an ECS node and \<html\> content in lockstep |
+| [05-html-paint.tsx](05-html-paint.tsx) | `dapi mount samples/reconciler/05-html-paint.tsx` | DOM/SVG materialization under \<Html\>; needs html-in-canvas |
+| [06-anime-timeline.tsx](06-anime-timeline.tsx) | `dapi mount samples/reconciler/06-anime-timeline.tsx` | anime.js timeline seeked from useTicker, driving an ECS node and \<Html\> content in lockstep |
| [07-anime-mini.tsx](07-anime-mini.tsx) | `dapi mount samples/reconciler/07-anime-mini.tsx` | minimal anime.js + useTicker sync, sized for a social post |
-| [08-surface-paint.tsx](08-surface-paint.tsx) | `dapi mount samples/reconciler/08-surface-paint.tsx` | ref-provided canvas: \<surface\> element and \<surfacePaint\> child, effect-driven redraws |
-| [09-three-helmet.tsx](09-three-helmet.tsx) | `dapi mount samples/reconciler/09-three-helmet.tsx` | three.js WebGL renderer owning a \<surface\>, glTF model loaded over the network, rotation seeked from useTicker |
+| [08-surface-paint.tsx](08-surface-paint.tsx) | `dapi mount samples/reconciler/08-surface-paint.tsx` | ref-provided canvas: \<Surface\> element and \<SurfacePaint\> child, effect-driven redraws |
+| [09-three-helmet.tsx](09-three-helmet.tsx) | `dapi mount samples/reconciler/09-three-helmet.tsx` | three.js WebGL renderer owning a \<Surface\>, glTF model loaded over the network, rotation seeked from useTicker |
Each root scene carries a stable key, so re-mounting a sample replaces its
scene in place. Inspect results with `dapi node tree`; entity ids in sample 03
diff --git a/samples/tsconfig.json b/samples/tsconfig.json
new file mode 100644
index 00000000..3d6c076a
--- /dev/null
+++ b/samples/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "../tsconfig.base.json",
+ "compilerOptions": {
+ "jsx": "preserve",
+ "jsxImportSource": "@diffusionstudio/jsx",
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
+ "types": []
+ },
+ "include": ["reconciler"]
+}