create-dreamer-app 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,6 +23,7 @@ Open the local URL printed by Vite. The development server uses port `3000` by d
23
23
  - **Vite** for local development and production builds.
24
24
  - **Source aliases** so you can import from `@/` instead of navigating relative paths.
25
25
  - A full-page canvas with basic styles.
26
+ - `DISCO_DREAMER_REFERENCE.md`, a practical guide to the Disco Dreamer API.
26
27
 
27
28
  ## Make it yours
28
29
 
@@ -46,6 +47,7 @@ import { Message } from "@/components/Message";
46
47
 
47
48
  ```text
48
49
  my-dreamer-app/
50
+ ├── DISCO_DREAMER_REFERENCE.md
49
51
  ├── src/
50
52
  │ ├── assets/
51
53
  │ │ └── disco-dreamer.svg
@@ -75,16 +77,34 @@ Run these inside your generated project:
75
77
  ## CLI options
76
78
 
77
79
  ```sh
78
- npx create-dreamer-app@latest [directory] [--skip-install]
80
+ npx create-dreamer-app@latest [directory] [options]
79
81
  ```
80
82
 
81
- Omit the directory to choose a name interactively. The destination must be a new or empty directory.
83
+ Omit the directory to choose a name interactively when creating an app. The app destination must be a new or empty directory.
82
84
 
83
85
  | Option | Description |
84
86
  | --- | --- |
85
87
  | `--skip-install` | Create the project without installing dependencies. |
88
+ | `-ro`, `--ref-only` | Copy only `DISCO_DREAMER_REFERENCE.md`, without installing dependencies. Defaults to the current directory. |
89
+ | `-er`, `--exclude-reference` | Create the app without `DISCO_DREAMER_REFERENCE.md`. |
86
90
  | `-h`, `--help` | Show usage information. |
87
91
 
92
+ To add just the reference to an existing project, run this inside the project:
93
+
94
+ ```sh
95
+ npx create-dreamer-app@latest --ref-only
96
+ ```
97
+
98
+ You can also specify a destination, such as `npx create-dreamer-app@latest docs -ro`.
99
+ Reference-only mode allows existing directories but refuses to overwrite an existing reference file.
100
+ The `--ref-only` and `--exclude-reference` options cannot be used together.
101
+
102
+ To create an app without the reference:
103
+
104
+ ```sh
105
+ npx create-dreamer-app@latest my-dreamer-app -er
106
+ ```
107
+
88
108
  To install dependencies yourself:
89
109
 
90
110
  ```sh
package/index.js CHANGED
@@ -4,18 +4,26 @@ const fs = require("node:fs/promises");
4
4
  const path = require("node:path");
5
5
  const readline = require("node:readline/promises");
6
6
  const { spawnSync } = require("node:child_process");
7
+ const { constants } = require("node:fs");
7
8
 
8
- const usage = `Usage: create-dreamer-app [directory] [--skip-install]
9
+ const referenceFile = "DISCO_DREAMER_REFERENCE.md";
10
+
11
+ const usage = `Usage: create-dreamer-app [directory] [options]
9
12
 
10
13
  Create a Disco Dreamer app and install its dependencies.
11
14
  If no directory is supplied, you will be prompted for one.
15
+ With --ref-only, the directory defaults to the current directory.
12
16
 
13
17
  Options:
14
- --skip-install Create the project without running npm install
15
- -h, --help Show this help message
18
+ --skip-install Create the project without running npm install
19
+ -ro, --ref-only Copy only the reference, without installing dependencies
20
+ -er, --exclude-reference Create the project without the reference
21
+ -h, --help Show this help message
16
22
 
17
- Example:
18
- npx create-dreamer-app my-dreamer-app`;
23
+ Examples:
24
+ npx create-dreamer-app my-dreamer-app
25
+ npx create-dreamer-app --ref-only
26
+ npx create-dreamer-app my-dreamer-app --exclude-reference`;
19
27
 
20
28
  async function main() {
21
29
  const args = process.argv.slice(2);
@@ -24,12 +32,19 @@ async function main() {
24
32
  return;
25
33
  }
26
34
 
27
- const unknownOption = args.find((arg) => arg.startsWith("-") && arg !== "--skip-install");
35
+ const options = new Set(["--skip-install", "--ref-only", "-ro", "--exclude-reference", "-er"]);
36
+ const unknownOption = args.find((arg) => arg.startsWith("-") && !options.has(arg));
28
37
  if (unknownOption) throw new Error(`Unknown option: ${unknownOption}\n\n${usage}`);
29
- const directories = args.filter((arg) => arg !== "--skip-install");
38
+ const refOnly = args.includes("--ref-only") || args.includes("-ro");
39
+ const excludeReference = args.includes("--exclude-reference") || args.includes("-er");
40
+ if (refOnly && excludeReference) {
41
+ throw new Error("--ref-only (-ro) and --exclude-reference (-er) cannot be used together.");
42
+ }
43
+ const directories = args.filter((arg) => !options.has(arg));
30
44
  if (directories.length > 1) throw new Error(`Supply only one project directory.\n\n${usage}`);
31
45
 
32
46
  let directory = directories[0];
47
+ if (directory === undefined && refOnly) directory = ".";
33
48
  if (directory === undefined) {
34
49
  if (!process.stdin.isTTY) throw new Error(`Supply a project directory.\n\n${usage}`);
35
50
  const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
@@ -42,6 +57,18 @@ async function main() {
42
57
  if (!directory.trim()) throw new Error("The project directory cannot be empty.");
43
58
 
44
59
  const destination = path.resolve(directory);
60
+ if (refOnly) {
61
+ await fs.mkdir(destination, { recursive: true });
62
+ const referencePath = path.join(destination, referenceFile);
63
+ try {
64
+ await fs.copyFile(path.join(__dirname, "template", referenceFile), referencePath, constants.COPYFILE_EXCL);
65
+ } catch (error) {
66
+ if (error.code === "EEXIST") throw new Error(`Reference already exists: ${referencePath}`);
67
+ throw error;
68
+ }
69
+ console.log(`Copied ${referenceFile} to ${destination}.`);
70
+ return;
71
+ }
45
72
  const name = path.basename(destination).toLowerCase().replace(/[^a-z0-9._-]+/g, "-");
46
73
  if (!/^[a-z0-9][a-z0-9._-]*$/.test(name) || name.length > 214 || ["node_modules", "favicon.ico"].includes(name)) {
47
74
  throw new Error("Choose a directory whose name starts with a letter or number and can be used as an npm package name.");
@@ -62,7 +89,8 @@ async function main() {
62
89
  recursive: true,
63
90
  force: false,
64
91
  errorOnExist: true,
65
- filter: (source) => ![".DS_Store", "node_modules", "dist"].includes(path.basename(source)),
92
+ filter: (source) => ![".DS_Store", "node_modules", "dist"].includes(path.basename(source))
93
+ && !(excludeReference && path.basename(source) === referenceFile),
66
94
  });
67
95
  const packagePath = path.join(destination, "package.json");
68
96
  const manifest = JSON.parse(await fs.readFile(packagePath, "utf8"));
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "create-dreamer-app",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "The scaffolding application for using Disco Dreamer.",
5
5
  "main": "index.js",
6
6
  "bin": {
7
7
  "create-dreamer-app": "index.js"
8
8
  },
9
+ "scripts": {
10
+ "test": "node --test"
11
+ },
9
12
  "engines": {
10
13
  "node": "^20.19.0 || >=22.12.0"
11
14
  },
@@ -0,0 +1,473 @@
1
+ # Disco Dreamer reference
2
+
3
+ A practical guide to building browser games with `discodreamer`. Examples use the public API in version 1.0.2 and TypeScript with JSX.
4
+
5
+ ## How a game runs
6
+
7
+ Disco Dreamer draws a tree of game objects onto a 2D canvas. Components are functions that return game objects; hooks provide state, input, animation, and other game behavior.
8
+
9
+ Your root function runs again on every animation frame. Each frame, the engine builds the tree, solves collisions, manages sound, draws the tree, and cleans up. A state setter updates stored data immediately; it does not schedule a separate render.
10
+
11
+ - Coordinates use CSS pixels, with `(0, 0)` at the canvas's top-left, positive `x` to the right, and positive `y` downward.
12
+ - Child positions are relative to their parent `Scene` or `RigidBody2D`.
13
+ - Siblings draw in ascending `z` order; higher values appear later, on top. This is local to each parent, not a global depth order.
14
+ - Update times and interpolation durations are in milliseconds. Convert `dt` to seconds for movement expressed in units per second.
15
+ - Import components and hooks from `discodreamer`.
16
+
17
+ ## First game
18
+
19
+ In a generated app, use its existing entry point and canvas. Replace the game tree or component there; keep a single `registerRoot` call.
20
+
21
+ For a custom setup, the HTML must contain a canvas with `id="c"` before registration. Give it a visible CSS size, for example:
22
+
23
+ ```html
24
+ <canvas id="c" style="display: block; width: 800px; height: 450px;"></canvas>
25
+ ```
26
+
27
+ This entry point moves a square with the arrow keys:
28
+
29
+ ```tsx
30
+ import {
31
+ registerRoot,
32
+ Scene,
33
+ Rect,
34
+ Text,
35
+ gameState,
36
+ gameUpdate,
37
+ gameEvent,
38
+ } from "discodreamer";
39
+
40
+ function Game() {
41
+ const [, setPosition, getPosition] = gameState("player.position", {
42
+ x: 100,
43
+ y: 100,
44
+ });
45
+
46
+ gameUpdate((dt) => {
47
+ const step = 200 * dt / 1000;
48
+ gameEvent("key", ({ key }) => {
49
+ setPosition((prev) => ({
50
+ x: prev.x + (key === "ArrowRight" ? step : key === "ArrowLeft" ? -step : 0),
51
+ y: prev.y + (key === "ArrowDown" ? step : key === "ArrowUp" ? -step : 0),
52
+ }));
53
+ });
54
+ });
55
+
56
+ const position = getPosition();
57
+ return (
58
+ <Scene>
59
+ <Rect {...position} width={32} height={32} style={{ fill: "#ff69b4" }} />
60
+ <Text x={16} y={16} fontSize={20} value="Move with the arrow keys" />
61
+ </Scene>
62
+ );
63
+ }
64
+
65
+ registerRoot(Game);
66
+ ```
67
+
68
+ The generated app handles the JSX factory automatically; no factory import or manual JSX configuration is needed.
69
+
70
+ Use `.tsx` files for JSX. Arrays and conditional children are supported, such as `{visible && <Rect width={20} height={20} />}`. Components can also be called directly without JSX: `Scene({ children: [Rect({ width: 20, height: 20 })] })`.
71
+
72
+ The examples below are independent excerpts; add their named imports from `discodreamer` to your game file. Asset paths such as `/player.png` are examples: supply files at URLs your app serves.
73
+
74
+ ## State and keys
75
+
76
+ ### `gameState(key, initialValue)`
77
+
78
+ Returns `[value, setValue, getValue, resolvedKey]`:
79
+
80
+ ```ts
81
+ const [score, setScore, getScore] = gameState("score", 0);
82
+ setScore((previous) => previous + 1);
83
+ // score is the value read earlier in this frame.
84
+ // getScore() reads the latest stored value, including the increment.
85
+ ```
86
+
87
+ `initialValue` initializes a new state slot; changing it on later frames does not reset existing state. Setters accept either a replacement or a function of the previous value. Replace objects rather than mutating them.
88
+
89
+ Keys identify persistent data across frames. Give each stateful hook and each body instance a stable, descriptive key. For repeated entities, include an entity ID, such as `` `enemy.${id}.health` ``.
90
+
91
+ Internally, consecutive stateful calls using the same key receive numbered slots. Their order must stay consistent. Reusing a key after a different key starts its numbering again, which can alias an earlier slot. The simplest application pattern is to use a distinct key for each hook and avoid sharing keys with component internals. Keep stateful hook calls in a consistent order each frame.
92
+
93
+ State that is no longer used is removed during frame cleanup. If an entity disappears for a frame and returns later, expect its state to initialize again.
94
+
95
+ ### `createDynamicId()`
96
+
97
+ Returns a fresh string ID. Generate it when spawning an entity, store it with that entity, and reuse it across frames. Calling it on every render would give the entity a new identity every frame.
98
+
99
+ ## Drawing components
100
+
101
+ ### `Scene`
102
+
103
+ Groups children and adds a positional offset. Props: `x`, `y`, `z` (all default to `0`) and `children` (default `[]`).
104
+
105
+ ```tsx
106
+ <Scene x={100} y={80}>
107
+ <Rect width={100} height={40} />
108
+ <Text y={48} fontSize={18} value="Hello!" />
109
+ </Scene>
110
+ ```
111
+
112
+ ### `Rect` and `Circ`
113
+
114
+ Both accept `x`, `y`, `z` (default `0`) and `style: { fill?, stroke? }`. Colors are canvas color strings. With no style, shapes have a white fill and black stroke. Passing a style replaces that default, so `{ stroke: "red" }` draws only a stroke.
115
+
116
+ | Component | Geometry | Origin |
117
+ | --- | --- | --- |
118
+ | `Rect` | `width`, `height`, each default `0` | Top-left corner |
119
+ | `Circ` | `rad`, default `0` | Center |
120
+
121
+ ```tsx
122
+ <Scene>
123
+ <Rect x={20} y={20} width={100} height={60} style={{ fill: "orange" }} />
124
+ <Circ x={180} y={50} rad={30} style={{ stroke: "cyan" }} />
125
+ </Scene>
126
+ ```
127
+
128
+ These shapes are visual only. Use `Bounds` inside a `RigidBody2D` for collision geometry.
129
+
130
+ ### `Sprite`
131
+
132
+ Displays an image or a sprite-sheet animation. Supply exactly one of `src` or `animation`.
133
+
134
+ | Prop | Behavior |
135
+ | --- | --- |
136
+ | `src` | Image URL for a static sprite |
137
+ | `animation` | Result of `gameAnimation` |
138
+ | `x`, `y`, `z` | Position and sibling draw order; default `0` |
139
+ | `width`, `height` | Display size; defaults to image dimensions or animation frame size |
140
+ | `rotation` | Degrees around the image center; default `0` |
141
+
142
+ ```tsx
143
+ <Sprite src="/player.png" x={100} y={80} width={64} height={64} />
144
+ ```
145
+
146
+ The sprite's position is its unrotated top-left corner. Images are cached by URL, and a sprite draws nothing until its image is ready. Rotation affects drawing, not physics bounds.
147
+
148
+ ### `Text`
149
+
150
+ Draws white, left-aligned, top-aligned text. Uses `sans-serif` unless a font family is supplied.
151
+
152
+ | Prop | Default | Purpose |
153
+ | --- | --- | --- |
154
+ | `value` | Required | Text string to draw |
155
+ | `x`, `y`, `z` | `0` | Position and sibling draw order |
156
+ | `fontSize` | `25` | Font size in pixels |
157
+ | `font` | `""` (renders as `sans-serif`) | Font family name, such as a name registered with `addCustomFont` |
158
+ | `width` | `Infinity` | Maximum canvas text draw width |
159
+
160
+ A finite `width` limits the canvas text draw width; it does not create wrapping lines. `font` is a string, not a font file URL. Missing or empty font names use `sans-serif`; a named font that is not yet available uses the browser's fallback until it loads. Fonts already available through CSS or installed on the user's device can also be selected without calling `addCustomFont`.
161
+
162
+ ```tsx
163
+ <Text x={16} y={16} value="Score: 10" fontSize={24} />
164
+ <Text x={16} y={48} value="Custom font" font="PixelFont" fontSize={32} />
165
+ ```
166
+
167
+ ## Custom fonts
168
+
169
+ ### `addCustomFont(name, fontFile)`
170
+
171
+ Starts loading a font from a URL string and registers it with the browser under `name`. Loading is asynchronous internally, but the helper returns `void`, not a promise. Call it once per font during setup, outside the root function or game loop. Text does not require custom font registration unless you want to load a font file yourself.
172
+
173
+ ```ts
174
+ import { addCustomFont } from "discodreamer";
175
+
176
+ addCustomFont("PixelFont", "/fonts/pixel.woff2");
177
+ ```
178
+
179
+ Supply a URL your app serves. In Vite, you can also import the asset to obtain its URL:
180
+
181
+ ```ts
182
+ import pixelFontUrl from "./assets/pixel.woff2";
183
+
184
+ addCustomFont("PixelFont", pixelFontUrl);
185
+ ```
186
+
187
+ For TypeScript asset imports in a Vite app, include `"types": ["vite/client"]` in that app's `compilerOptions`.
188
+
189
+ The helper uses `FontFace.load()` and adds the loaded face to `document.fonts`. Failed loads are logged to the console and recorded as `"error"`. Registration is not deduplicated: repeated calls with the same name start new loads, so avoid calling it every frame.
190
+
191
+ ### `getFontStatus(name)` and `isFontLoaded(name)`
192
+
193
+ These helpers read the custom font registry immediately; they do not start loading or wait for a font.
194
+
195
+ | `getFontStatus(name)` | Meaning | `isFontLoaded(name)` |
196
+ | --- | --- | --- |
197
+ | `"unknown"` | No registration for this name | `false` |
198
+ | `"loading"` | Font loading is in progress | `false` |
199
+ | `"ready"` | Font loaded and was added to the document | `true` |
200
+ | `"error"` | Font loading or registration failed | `false` |
201
+
202
+ These statuses describe fonts registered through `addCustomFont`, not all fonts available on the device or through CSS. `FontStatus` is an internal type and is not a public named export.
203
+
204
+ You can check readiness each frame to show a loading message instead of drawing with a fallback font:
205
+
206
+ ```tsx
207
+ import {
208
+ addCustomFont,
209
+ getFontStatus,
210
+ isFontLoaded,
211
+ registerRoot,
212
+ Text,
213
+ } from "discodreamer";
214
+
215
+ addCustomFont("PixelFont", "/fonts/pixel.woff2");
216
+
217
+ function FontExample() {
218
+ if (getFontStatus("PixelFont") === "error") {
219
+ return <Text value="Could not load the font." />;
220
+ }
221
+ if (!isFontLoaded("PixelFont")) {
222
+ return <Text value="Loading font..." />;
223
+ }
224
+ return <Text value="Score: 100" font="PixelFont" fontSize={32} />;
225
+ }
226
+
227
+ registerRoot(FontExample);
228
+ ```
229
+
230
+ As with the other examples, a custom JSX setup must configure and import the JSX factory. Font readiness does not guarantee that the file supplies every character; the glyphs and character coverage depend on the font itself.
231
+
232
+ ## Physics components and contact hooks
233
+
234
+ ### `RigidBody2D`
235
+
236
+ A stateful moving body. Put drawing components and one or more `Bounds` inside it.
237
+
238
+ | Prop | Default | Purpose |
239
+ | --- | --- | --- |
240
+ | `key` | Required | Stable body identity; also used by contact hooks |
241
+ | `x`, `y`, `z` | `0` | Initial local position and draw order |
242
+ | `velocity` | `{ x: 0, y: 0 }` | Initial velocity in world units per second |
243
+ | `mass` | `1` | Kilograms; `0` creates a static body |
244
+ | `gravity` | `1` | Multiplier of downward acceleration, `981` units/s²; `0` disables gravity |
245
+ | `forces` | `[]` | Force vectors in newtons, applied each frame |
246
+ | `drag` | `0` | Exponential velocity damping per second |
247
+ | `restitution` | `1` | Bounce factor; `0` removes bounce; a pair uses the lower factor |
248
+ | `layer` | Unset | Layer name used by other bodies' filters |
249
+ | `collidesWith` | `[]` | Layers eligible for physical collision |
250
+ | `hitsWith` | `[]` | Layers to report overlap with, without requiring physical response |
251
+ | `ref` | Unset | Key returned by `gameRef` |
252
+ | `onChange` | Unset | Callback receiving `{ position, velocity }` |
253
+ | `children` | `[]` | Visuals and bounds attached to the body |
254
+
255
+ Physics treats one world unit as one centimeter. The renderer displays one unit as one CSS pixel.
256
+
257
+ Keep `x`, `y`, `velocity`, and `mass` props stable to let the simulation evolve. Changing any of these inputs resets the body's stored position, velocity, and mass to the currently supplied values. For movement that does not reset the body, use forces. `onChange` runs initially and on tracked changes; velocity comparisons use a threshold of `1` unit/s, while position changes also trigger it.
258
+
259
+ ### `Bounds`
260
+
261
+ Defines collision geometry owned by its containing body. Choose either rectangle dimensions or a circle radius:
262
+
263
+ ```tsx
264
+ // Rectangle:
265
+ <Bounds width={32} height={48} />;
266
+ // Or circle:
267
+ <Bounds radius={16} position={{ x: 16, y: 16 }} />;
268
+ ```
269
+
270
+ Rectangle bounds use their top-left corner; circle bounds use their center. `position` is a local offset (default `{ x: 0, y: 0 }`). Optional `outline` displays the geometry for debugging; `style` controls its fill/stroke and `z` controls its visual sibling order. Bounds are invisible by default. Standalone bounds outside a body do not participate in physics.
271
+
272
+ ### `gameCollision(key, handler)` and `gameHit(key, handler)`
273
+
274
+ Call these each frame with the body's public `key`. The handler receives the other body's public key once per reported body pair per frame.
275
+
276
+ - Physical collisions require both bodies to include each other's `layer` in `collidesWith`.
277
+ - Hits are directional: only the observing body's `hitsWith` needs to include the other body's layer.
278
+ - Hits alone do not separate bodies or change their velocities.
279
+ - Hooks read the previous frame's contact results because the current collision pass happens after tree construction. Contacts are reported repeatedly while detected; these are not enter/exit events.
280
+
281
+ ```tsx
282
+ function PhysicsExample() {
283
+ gameCollision("ball", (otherKey) => {
284
+ if (otherKey === "floor") console.log("Ball contacted floor");
285
+ });
286
+
287
+ return (
288
+ <Scene>
289
+ <RigidBody2D key="ball" x={100} y={40}
290
+ layer="ball" collidesWith={["world"]} restitution={0.6}>
291
+ <Bounds radius={16} outline style={{ fill: "hotpink" }} />
292
+ </RigidBody2D>
293
+ <RigidBody2D key="floor" y={350} mass={0}
294
+ layer="world" collidesWith={["ball"]} restitution={0.6}>
295
+ <Bounds width={800} height={30} outline style={{ fill: "gray" }} />
296
+ </RigidBody2D>
297
+ </Scene>
298
+ );
299
+ }
300
+ ```
301
+
302
+ ### `gameRef<RigidBody2DSnapshot>(key)`
303
+
304
+ Reads a body's live stored state. Pass the returned `key` to the body's `ref`, and check `ready` before calling `snapshot()`:
305
+
306
+ ```tsx
307
+ function TrackedBody() {
308
+ const body = gameRef<RigidBody2DSnapshot>("player.ref");
309
+ if (body.ready) {
310
+ const { position, velocity, mass } = body.snapshot();
311
+ // Use the snapshot for game logic or a HUD.
312
+ }
313
+
314
+ return (
315
+ <RigidBody2D key="player.body" ref={body.key} gravity={0}>
316
+ <Bounds width={32} height={32} outline />
317
+ </RigidBody2D>
318
+ );
319
+ }
320
+ ```
321
+
322
+ Import `RigidBody2DSnapshot` with `import type`. The ref normally becomes ready on a later frame after the body attaches. A snapshot contains local position, velocity, and mass; it is a read interface, not a setter.
323
+
324
+ ## Update, effect, and input hooks
325
+
326
+ ### `gameUpdate(handler)`
327
+
328
+ Calls `handler(dt, frame, viewport)` immediately whenever the hook is evaluated. Used once in a component that runs every frame, it runs once per frame. `frame` starts at `0`; `dt` starts at `0` and then reflects the interval measured at the previous cleanup. `viewport` contains `{ width, height }` in CSS pixels.
329
+
330
+ ```ts
331
+ gameUpdate((dt, frame, viewport) => {
332
+ // Integrate movement with dt / 1000, or run other per-frame logic.
333
+ });
334
+ ```
335
+
336
+ ### `gameEffect(key, handler, dependencies)`
337
+
338
+ Runs immediately on first use and when dependencies change. The callback receives the same arguments as `gameUpdate`. Dependencies can be strings, numbers, booleans, or values wrapped in `createComparator`.
339
+
340
+ ```ts
341
+ gameEffect("score.log", () => {
342
+ console.log("Score changed", score);
343
+ }, [score]);
344
+
345
+ gameEffect("speed.log", () => {
346
+ console.log("Speed changed enough", speed);
347
+ }, [createComparator<number>(speed, (previous, next) => Math.abs(next - previous) >= 1)]);
348
+ ```
349
+
350
+ Ordinary dependencies use `Object.is`. A comparator returns `true` when the effect should run; its previous value comes from the last effect run. An empty dependency array runs once for the lifetime of that state slot. Effects do not have a cleanup callback.
351
+
352
+ ### `gameEvent(type, listener)`
353
+
354
+ Reads current input; call it each frame. It invokes the listener immediately for matching input, rather than installing a persistent subscription.
355
+
356
+ | Type | Listener payload | When reported |
357
+ | --- | --- | --- |
358
+ | `key` | `{ key: string }` | Each frame for each held key |
359
+ | `keyDown` | `{ key: string }` | New key presses; ignores browser repeat |
360
+ | `keyUp` | `{ key: string }` | Key releases |
361
+ | `touch` | `{ x, y }` | Each frame while the primary pointer is held |
362
+ | `touchStart` | `{ x, y }` | Primary pointer press on the canvas |
363
+ | `touchEnd` | `{ x, y }` | Primary pointer release or cancellation |
364
+
365
+ Key names use `KeyboardEvent.key`, for example `"ArrowLeft"`, `"a"`, or `" "` for space. Despite the `touch` names, pointer input supports mouse, touch, and pen, tracking one active pointer. Positions are relative to the canvas content area in CSS pixels.
366
+
367
+ ```ts
368
+ gameEvent("keyDown", ({ key }) => {
369
+ if (key === " ") sendMessage("player.jump", null);
370
+ });
371
+ gameEvent("touchStart", ({ x, y }) => {
372
+ console.log("Pressed canvas at", x, y);
373
+ });
374
+ ```
375
+
376
+ ### `gameViewport()`
377
+
378
+ Returns the canvas's current CSS size as `{ width, height }`. Use this for responsive placement; the engine handles the canvas backing resolution for device pixel ratio.
379
+
380
+ ```ts
381
+ const { width, height } = gameViewport();
382
+ ```
383
+
384
+ ## Animation and image hooks
385
+
386
+ ### `gameAnimation(key, animations, config)`
387
+
388
+ Creates an animation descriptor for `Sprite`. `animations` is an ordered array of `[condition, frames, options?]`; the first true condition wins. A condition can be a boolean or a function returning a boolean. Frame numbers are zero-based, counted left to right and then top to bottom across the sheet.
389
+
390
+ Config requires `src` and `size` (the square frame size in source pixels). Optional `fps` defaults to `24`; `loop` defaults to `true`. A frame group's `{ loop }` overrides that default. Switching the selected group restarts its timing.
391
+
392
+ ```tsx
393
+ function AnimatedPlayer({ moving }: { moving: boolean }) {
394
+ const animation = gameAnimation("player.animation", [
395
+ [moving, [4, 5, 6, 7]],
396
+ [true, [0, 1, 2, 3]],
397
+ ], { src: "/player-sheet.png", size: 32, fps: 8 });
398
+
399
+ return <Sprite animation={animation} width={64} height={64} />;
400
+ }
401
+ ```
402
+
403
+ Use a final `true` condition as a fallback. A non-looping group holds its final frame. Call `animation.onAnimationFinish(handler)` each frame to handle its completion transition; it is not a persistent listener. Keep the source URL unchanged for an animation key, and use a positive frame size that fits the sheet.
404
+
405
+ ### `gameImage(src)`
406
+
407
+ Returns a cached `HTMLImageElement` when loaded, otherwise `null`. Useful for checking dimensions or readiness. `Sprite` and `gameAnimation` already use it internally.
408
+
409
+ ```ts
410
+ const image = gameImage("/background.png");
411
+ if (image) {
412
+ const imageWidth = image.naturalWidth;
413
+ }
414
+ ```
415
+
416
+ ### `gameLerp(key, from, to, duration)`
417
+
418
+ Interpolates a number over `duration` milliseconds, returning `{ value, reset, update }`. Progress clamps at the target; a non-positive duration returns the target immediately.
419
+
420
+ ```tsx
421
+ function SlidingPanel() {
422
+ const slide = gameLerp("panel.slide", -200, 20, 500);
423
+ gameEvent("keyDown", ({ key }) => {
424
+ if (key === "r") slide.reset();
425
+ if (key === "h") {
426
+ slide.update(() => ({ from: slide.value, to: -200, duration: 300 }));
427
+ }
428
+ });
429
+ return <Rect x={slide.value} y={50} width={180} height={100} />;
430
+ }
431
+ ```
432
+
433
+ The initial arguments initialize stored interpolation data. Use `reset()` to restart that interpolation or `update(previous => ({ from?, to?, duration? }))` to change it and restart its clock. Timing uses wall-clock time. An update is reflected in the value returned on the next evaluation.
434
+
435
+ ## Messages
436
+
437
+ ### `sendMessage(type, value)` and `gameMessage(handler, types?)`
438
+
439
+ Send data between components without passing callbacks through the tree. Messages sent during a frame become available on the next frame, and each listener can read them. Call `gameMessage` every frame to receive them. The optional array filters by message type.
440
+
441
+ ```ts
442
+ // In a sender:
443
+ sendMessage("score.add", 10);
444
+
445
+ // In a receiver, evaluated each frame:
446
+ gameMessage((type, value) => {
447
+ if (type === "score.add" && typeof value === "number") {
448
+ setScore((previous) => previous + value);
449
+ }
450
+ }, ["score.add"]);
451
+ ```
452
+
453
+ Messages are cloned with `structuredClone`, so payloads must be cloneable data. Sending on every frame sends a new message every frame; use input or an effect when you want a single event.
454
+
455
+ ## Sound
456
+
457
+ ### `Sound`
458
+
459
+ Include a sound in the tree to play it. Props: required `key` and `src`; optional `loop` (default `false`), `volume` (default `1`), `onLoad`, and `onComplete`.
460
+
461
+ ```tsx
462
+ <Sound key="music" src="/music.ogg" loop volume={0.4} />
463
+ ```
464
+
465
+ A sound key must be unique across the entire tree. Keeping the same key and source preserves playback; changing volume or loop updates it. Removing the node stops playback. A completed one-shot does not restart merely because it remains in the tree: remove it for a frame and add it again, or use a new key. Changing the source also replaces playback.
466
+
467
+ `onLoad` runs once when the buffer is ready for that playback instance. `onComplete` runs once after natural playback completion, not when the node is removed. Browser audio may wait for a native pointer or keyboard gesture before becoming audible.
468
+
469
+ ## Public API scope
470
+
471
+ The public components are `Scene`, `Sprite`, `Text`, `Rect`, `Circ`, `RigidBody2D`, `Bounds`, and `Sound`. The hooks described above, `DreamFactory`, `registerRoot`, `createComparator`, `createDynamicId`, `sendMessage`, `addCustomFont`, `getFontStatus`, and `isFontLoaded` are also exported.
472
+
473
+ Public type exports are `SceneProps`, `GameObject`, `Viewport`, `Vector2d`, `RigidBody2DSnapshot`, `GameRef`, `GameRefResult`, and `EventType`. Other implementation files, including `Img`, `Txt`, and the unfinished global helpers, are not public package exports.
@@ -22,6 +22,6 @@
22
22
  "vite": "^8.3.2"
23
23
  },
24
24
  "dependencies": {
25
- "discodreamer": "^1.0.2"
25
+ "discodreamer": "^1.0.3"
26
26
  }
27
27
  }
@@ -0,0 +1,106 @@
1
+ const assert = require("node:assert/strict");
2
+ const fs = require("node:fs/promises");
3
+ const os = require("node:os");
4
+ const path = require("node:path");
5
+ const { spawnSync } = require("node:child_process");
6
+ const { test } = require("node:test");
7
+
8
+ const cli = path.resolve(__dirname, "../index.js");
9
+ const reference = "DISCO_DREAMER_REFERENCE.md";
10
+
11
+ async function workspace(t) {
12
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "dreamer-cli-"));
13
+ t.after(() => fs.rm(directory, { recursive: true, force: true }));
14
+ return directory;
15
+ }
16
+
17
+ function run(cwd, args) {
18
+ const result = spawnSync(process.execPath, [cli, ...args], {
19
+ cwd,
20
+ encoding: "utf8",
21
+ timeout: 10000,
22
+ });
23
+ assert.ifError(result.error);
24
+ return result;
25
+ }
26
+
27
+ test("default app includes the reference and updates the package name", async (t) => {
28
+ const cwd = await workspace(t);
29
+ const result = run(cwd, ["my-app", "--skip-install"]);
30
+ assert.equal(result.status, 0, result.stderr);
31
+ assert.equal(await fs.readFile(path.join(cwd, "my-app", reference), "utf8"),
32
+ await fs.readFile(path.resolve(__dirname, "../template", reference), "utf8"));
33
+ const manifest = JSON.parse(await fs.readFile(path.join(cwd, "my-app/package.json"), "utf8"));
34
+ assert.equal(manifest.name, "my-app");
35
+ });
36
+
37
+ for (const flag of ["--ref-only", "-ro"]) {
38
+ test(`${flag} copies only the reference into the current existing project`, async (t) => {
39
+ const cwd = await workspace(t);
40
+ await fs.writeFile(path.join(cwd, "package.json"), '{"name":"existing"}\n');
41
+ const result = run(cwd, [flag]);
42
+ assert.equal(result.status, 0, result.stderr);
43
+ assert.deepEqual((await fs.readdir(cwd)).sort(), [reference, "package.json"]);
44
+ assert.equal(await fs.readFile(path.join(cwd, "package.json"), "utf8"), '{"name":"existing"}\n');
45
+ assert.doesNotMatch(result.stdout, /npm install|npm run dev|Installing dependencies/);
46
+ });
47
+
48
+ test(`${flag} supports a new nested destination without npm name restrictions`, async (t) => {
49
+ const cwd = await workspace(t);
50
+ const result = run(cwd, ["docs/Reference Notes", flag]);
51
+ assert.equal(result.status, 0, result.stderr);
52
+ assert.deepEqual(await fs.readdir(path.join(cwd, "docs/Reference Notes")), [reference]);
53
+ });
54
+ }
55
+
56
+ for (const flag of ["--exclude-reference", "-er"]) {
57
+ test(`${flag} excludes the reference while copying the app`, async (t) => {
58
+ const cwd = await workspace(t);
59
+ const result = run(cwd, [flag, "my-app", "--skip-install"]);
60
+ assert.equal(result.status, 0, result.stderr);
61
+ await assert.rejects(fs.access(path.join(cwd, "my-app", reference)), { code: "ENOENT" });
62
+ await fs.access(path.join(cwd, "my-app/package.json"));
63
+ await fs.access(path.join(cwd, "my-app/src/index.tsx"));
64
+ });
65
+ }
66
+
67
+ test("reference-only refuses to overwrite an existing reference", async (t) => {
68
+ const cwd = await workspace(t);
69
+ await fs.writeFile(path.join(cwd, reference), "custom reference");
70
+ const result = run(cwd, ["--ref-only"]);
71
+ assert.equal(result.status, 1);
72
+ assert.match(result.stderr, /Reference already exists/);
73
+ assert.equal(await fs.readFile(path.join(cwd, reference), "utf8"), "custom reference");
74
+ });
75
+
76
+ test("conflicting modes fail before creating files for all aliases", async (t) => {
77
+ const cwd = await workspace(t);
78
+ for (const refFlag of ["--ref-only", "-ro"]) {
79
+ for (const excludeFlag of ["--exclude-reference", "-er"]) {
80
+ const result = run(cwd, ["my-app", refFlag, excludeFlag]);
81
+ assert.equal(result.status, 1);
82
+ assert.match(result.stderr, /cannot be used together/);
83
+ }
84
+ }
85
+ assert.deepEqual(await fs.readdir(cwd), []);
86
+ });
87
+
88
+ test("existing app safeguards and argument validation still apply", async (t) => {
89
+ const cwd = await workspace(t);
90
+ await fs.writeFile(path.join(cwd, "keep.txt"), "keep");
91
+ for (const args of [[".", "--skip-install"], [".", "-er", "--skip-install"]]) {
92
+ const result = run(cwd, args);
93
+ assert.equal(result.status, 1);
94
+ assert.match(result.stderr, /not an empty directory/);
95
+ }
96
+ assert.match(run(cwd, ["--unknown"]).stderr, /Unknown option/);
97
+ assert.match(run(cwd, ["a", "b", "-ro"]).stderr, /only one project directory/);
98
+ assert.deepEqual(await fs.readdir(cwd), ["keep.txt"]);
99
+ });
100
+
101
+ test("help documents both reference modes and aliases", async (t) => {
102
+ const result = run(await workspace(t), ["--help"]);
103
+ assert.equal(result.status, 0, result.stderr);
104
+ assert.match(result.stdout, /-ro, --ref-only/);
105
+ assert.match(result.stdout, /-er, --exclude-reference/);
106
+ });