@tioniq/sceniq 0.0.0-stage → 0.1.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,38 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2026-12-06
9
+
10
+ The first release.
11
+
12
+ ### Added
13
+
14
+ - **Scene graph.** `Scene` (one `<canvas>`, kept at the device pixel ratio), `Surface` (an area with its own
15
+ `Camera`), `Layer` (an offscreen bitmap reused while nothing in it changed) and `View`.
16
+ - **Reactive views.** Every changing option takes a value or an [eventiq](https://npmjs.com/package/@tioniq/eventiq)
17
+ variable; views subscribe only while shown, and disposing a scene, surface or layer lets go of everything.
18
+ - **Frames on demand.** A shared `FrameScheduler` draws only scenes and layers that changed, and stops when
19
+ nothing moves. Errors in views, animations and frame listeners go to `onError` without stopping the frame.
20
+ - **Views.** Rounded rectangles, hexagons, triangles, lines, `PathView` (polylines and Bézier curves with
21
+ dashes, arrowheads and stroke hit testing), `TextView`, `ImageView`, `ButtonView`, `CachedView`,
22
+ `ZoomLevelView`, `LevelOfDetailView`, `AsyncView`, and layouts (`LinearLayout`, `HorizontalLayout`, `VerticalLayout`, `ViewContainer`).
23
+ - **Text.** Wrapping with `Intl.Segmenter`, long-word breaking, right-to-left text, `maxLines` with an
24
+ ellipsis, and a new layout when a web font finishes loading.
25
+ - **Many shapes.** `ShapeBatch` keeps hundreds of thousands of shapes in typed arrays, draws and hit-tests
26
+ through a spatial grid, and updates one item at a time.
27
+ - **Labels.** `LabelPlacer` and `placeLabels` place labels by priority where they have room, off other
28
+ items' marks.
29
+ - **Input and camera.** Pointer Events with capture (mouse, touch, pen), pinch, wheel and keyboard zoom and
30
+ pan, kinetic panning, double-click zoom, `fitBounds`, `flyTo` and zoom limits through `attachZoomPan`.
31
+ - **Animation.** `tween` for numbers, points, colours and anything with `lerp`, with easing functions;
32
+ reduced motion is respected.
33
+ - **Export and diagnostics.** `scene.toBlob` / `toDataURL` at any scale, `scene.onFrame` and
34
+ `FrameStatsMonitor`.
35
+ - **Entry points.** `@tioniq/sceniq`, `@tioniq/sceniq/svg` (SVG parsing and drawing) and
36
+ `@tioniq/sceniq/react` (`useScene`, `<SceneCanvas>`); ESM and CommonJS with types, tree-shakeable.
37
+
38
+ [0.1.0]: https://github.com/tioniq/sceniq/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present Timoniann <timoniann@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ 'Software'), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,472 @@
1
- # Temporary Holding Version
1
+ # Sceniq
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ![npm version](https://img.shields.io/npm/v/@tioniq/sceniq)
4
+ ![license](https://img.shields.io/npm/l/@tioniq/sceniq)
5
+ ![types](https://badgen.net/npm/types/@tioniq/sceniq)
6
+ ![tree-shakeable](https://badgen.net/bundlephobia/tree-shaking/@tioniq/sceniq)
7
+
8
+ **Sceniq** is a reactive, retained-mode 2D canvas library for TypeScript. You build a scene of views
9
+ (shapes, text, images, paths, layouts) once, bind their properties to
10
+ [eventiq](https://npmjs.com/package/@tioniq/eventiq) variables, and change the variables. The library works
11
+ out what has to be drawn again, and draws a frame only when something changed.
12
+
13
+ ![The animation demo](docs/screenshots/animation.gif)
14
+
15
+ - **Reactive.** Every property of a view (location, size, colour, text, alpha, scale, rotation, visibility)
16
+ takes a plain value or a variable. Set a variable and the views bound to it are marked changed; only the
17
+ layers that hold them repaint. Views subscribe to their variables only while they are shown, so a view
18
+ taken out of a layer holds nothing and can be collected, and disposing a scene lets go of everything.
19
+ - **Frames on demand.** A frame is requested only when something changed or an animation is running. An idle
20
+ scene costs nothing: no loop, no redraws.
21
+ - **Layers and caching.** A scene composites surfaces, a surface composites layers, and each layer is an
22
+ offscreen bitmap reused while nothing in it changed. A camera move redraws only the layers that follow the
23
+ camera. `CachedView` keeps a complicated view as a bitmap at the resolution it is shown at.
24
+ - **Level of detail.** `ZoomLevelView` swaps a view for a simpler one when it gets small on screen,
25
+ `LevelOfDetailView` builds an expensive view only while it is big enough to need it, and layers can skip
26
+ laying out views that are far off screen.
27
+ - **Many small objects.** `ShapeBatch` holds tens or hundreds of thousands of shapes as rows of typed arrays
28
+ (about 50 bytes each instead of a view's 2 KB), draws only those on screen through a spatial grid, hit-tests
29
+ through it, and updates one item at a time. 200,000 tiles take 9 MB.
30
+ - **Labels that fit.** `LabelPlacer` places labels every frame only where they have room, by priority
31
+ (selected, hovered, important, the rest), keeping them off other items' marks.
32
+ - **Input and camera.** Mouse, touch and pen through Pointer Events with pointer capture, two-finger pinch, wheel
33
+ and keyboard zoom and pan, kinetic panning and double-click zoom, `fitBounds` and animated flights, hover and
34
+ click per view, hit testing that follows scale and rotation, and stroke hit testing for curves.
35
+ - **Export and diagnostics.** `scene.toBlob({ scale })` draws the scene again at more pixels for a sharp
36
+ picture; `scene.onFrame` and `FrameStatsMonitor` report fps, frame time and the layers that redrew.
37
+ - **Text.** Wrapping with `Intl.Segmenter` (Chinese, Japanese and Thai wrap too), long words broken, right to
38
+ left, line limits with an ellipsis, never squashed; laid out again when a web font finishes loading.
39
+ - **Sharp and sturdy.** The bitmap matches the screen's device pixels, at 125% and 150% too; a view or animation
40
+ that throws is reported and skipped, and the rest of the frame is drawn.
41
+
42
+ ## Installation
43
+
44
+ ```bash
45
+ npm install @tioniq/sceniq @tioniq/eventiq @tioniq/disposiq
46
+ ```
47
+
48
+ `@tioniq/eventiq` and `@tioniq/disposiq` are peer dependencies: your code shares their variables and
49
+ disposables with the library. React is an optional peer, needed only for `@tioniq/sceniq/react` (npm only:
50
+ the JSR package has the core and `/svg`).
51
+
52
+ The package is tree-shakeable ESM and CommonJS with types for both. Minified and gzipped (peers excluded,
53
+ `npm run size`): `Scene` alone 15 kB, a typical app (scene, shapes, text, paths, zoom-pan) 24 kB, `placeLabels`
54
+ alone 2 kB, everything 44 kB; `/svg` 11 kB and `/react` 16 kB, the scene included.
55
+
56
+ ## Quick start
57
+
58
+ ```html
59
+ <canvas id="canvas" style="width: 100%; height: 400px"></canvas>
60
+ ```
61
+
62
+ ```typescript
63
+ import {
64
+ animationInterpolators,
65
+ attachZoomPan,
66
+ Point,
67
+ RoundedRectangleView,
68
+ Scene,
69
+ Size,
70
+ TextView,
71
+ tween,
72
+ } from "@tioniq/sceniq"
73
+ import { createVar } from "@tioniq/eventiq"
74
+
75
+ const canvas = document.getElementById("canvas") as HTMLCanvasElement
76
+ const scene = new Scene(canvas.getContext("2d")!)
77
+ const surface = scene.createSurface()
78
+ const layer = surface.createLayer()
79
+
80
+ // Plain values and variables mix freely.
81
+ const size = createVar(80)
82
+ const hovered = createVar(false)
83
+
84
+ const box = new RoundedRectangleView({
85
+ location: new Point(40, 40),
86
+ size: new Size(80, 80),
87
+ scale: size.map(s => s / 80),
88
+ radius: 16,
89
+ fillColor: hovered.map(h => (h ? "#ff7aa8" : "#6aa8ff")),
90
+ hoverCursor: "pointer",
91
+ onClick: () => tween(size, size.value === 80 ? 120 : 80, { duration: 500, easing: animationInterpolators.overshoot }),
92
+ })
93
+ box.hovered.subscribe(h => (hovered.value = h))
94
+ layer.add(box)
95
+
96
+ layer.add(
97
+ new TextView({
98
+ text: size.map(s => `Click the square (${Math.round(s)} px)`),
99
+ location: new Point(40, 180),
100
+ font: { size: 16, family: "system-ui, sans-serif" },
101
+ color: "#333",
102
+ }),
103
+ )
104
+
105
+ // Drag to pan, wheel or pinch to zoom, + and - keys.
106
+ const controls = attachZoomPan(scene, surface, { wheel: "zoom", minZoom: 0.25, maxZoom: 8 })
107
+
108
+ // Later: controls.dispose() removes the controls alone; scene.dispose() removes every listener (the
109
+ // controls' too), detaches every view and releases the layers' bitmaps.
110
+ ```
111
+
112
+ Nothing above draws in a loop. Hovering sets one variable; clicking runs a tween for half a second; between
113
+ those the page draws no frames.
114
+
115
+ ## Examples
116
+
117
+ Five demo apps live in [`example/`](example). Each page shows its own source (the *Show source* button), and
118
+ uses only the package's public entry points.
119
+
120
+ ```bash
121
+ npm install
122
+ npm run example:dev # http://localhost:5296
123
+ npm run example:build # a static site in example/dist
124
+ ```
125
+
126
+ | | |
127
+ |---|---|
128
+ | [![Node graph](docs/screenshots/graph.png)](example/graph/main.ts) | **[Node graph](example/graph/main.ts)**: 500 nodes and about 700 curved edges in a live force layout. Hover lights up a node's neighbours, click selects and centres it, drag moves it; labels appear by level of detail. `PathView`, derived variables, `attachZoomPan`, hit testing. |
129
+ | [![50k-shape map](docs/screenshots/map.png)](example/map/main.ts) | **[50k-shape map](example/map/main.ts)**: a procedural island of 50,000 tiles in one `ShapeBatch`: drawn through a spatial grid, glyphs over large tiles, a bitmap when far out; hover outlines a tile, a click recolours it. Landmarks build their illustrations on demand, and a minimap (a second surface) follows the camera. `ShapeBatch`, `LevelOfDetailView`, `skipOffscreenLayout`. |
130
+ | [![Overview of the map](docs/screenshots/map-overview.png)](example/map/main.ts) | **The same map zoomed out**: all 50,000 tiles on screen. The top bar's frame counter reads *idle*: nothing is drawn until something moves. |
131
+ | [![Time-series chart](docs/screenshots/chart.png)](example/chart/main.ts) | **[Time-series chart](example/chart/main.ts)**: three years of daily data. The visible range is one variable; lines, grid, tick labels, crosshair and tooltip derive from it. The legend is a `LinearLayout` of clickable rows. |
132
+ | [![Text playground](docs/screenshots/text.png)](example/text/main.tsx) | **[Text playground](example/text/main.tsx)**: wrapping widths, alignment, right-to-left Hebrew and Arabic, Japanese and Chinese without spaces, long words, line limits and ellipsis, edited live. Built with React and `<SceneCanvas>`. |
133
+ | [![Animations](docs/screenshots/animation.png)](example/animation/main.ts) | **[Animations](example/animation/main.ts)**: about sixty objects moved by `tween`: the interpolators side by side, waves of scale, rotation and colour, an overshooting entrance, procedurally drawn planets. |
134
+
135
+ `npm run screenshots` rebuilds the demos and captures these pictures with Playwright (see the comment at the
136
+ top of [`example/screenshots.mjs`](example/screenshots.mjs)).
137
+
138
+ ## Concepts
139
+
140
+ ### Scene, surface, layer
141
+
142
+ ```
143
+ Scene owns the <canvas>: size, device pixel ratio, pointer and keyboard input
144
+ └─ Surface an offscreen area placed in the scene, with its own Camera
145
+ └─ Layer an offscreen bitmap of views and drawables, in order
146
+ └─ View / Drawable
147
+ ```
148
+
149
+ - A **`Scene`** wraps one `<canvas>`. It keeps the bitmap matched to the element's CSS size and the device
150
+ pixel ratio, turns pointer and keyboard events into input for its views, and composites its surfaces.
151
+ - A **`Surface`** (`scene.createSurface({ order, rect })`) covers the whole scene or a rectangle of it. It has
152
+ a `Camera`. A minimap or a fixed overlay is a second surface.
153
+ - A **`Layer`** (`surface.createLayer(order, { attachCamera, skipOffscreenLayout })`) holds views. A layer
154
+ with `attachCamera: false` stays fixed to the screen and its units are CSS pixels: use it for axes, legends,
155
+ tooltips and HUDs.
156
+
157
+ ### Views and variables
158
+
159
+ A `View` is a rectangle with a location, a `ViewBox` (its size rules), alpha, scale, rotation and hover state.
160
+ Shapes (`RoundedRectangleView`, `PathView`, `LineView`, `HexagonView`, `TriangleView`), `TextView`,
161
+ `ImageView` and the layouts are all views. A custom view overrides `doDraw`:
162
+
163
+ ```typescript
164
+ class Star extends View {
165
+ protected override doDraw(context: CanvasRenderingContext2D, state: DrawState) {
166
+ const { width, height } = state.localBounds // draw in the view's own coordinates
167
+ // …
168
+ }
169
+ }
170
+ ```
171
+
172
+ Every option that can change takes `VarOrVal<T>`: a value, or an eventiq variable the view follows. A view
173
+ also exposes its properties as variables (`view.location`, `view.hovered`, `view.alpha`…) and setters
174
+ (`view.location = new Point(…)`). When a variable changes, the view raises `onChanged`, its layer marks
175
+ itself dirty, and the next frame repaints that layer only. Derived variables (`a.map(…)`, `a.with(b).map(…)`)
176
+ make most bindings one line.
177
+
178
+ A view subscribes to its variables only while it is in a layer. A detached view holds no subscriptions, so
179
+ it cannot leak, and a hidden layout does not even follow its children. Removing or disposing a layer, or
180
+ disposing its surface or scene, detaches its views (their `onMounted` cleanups run) and releases its bitmap.
181
+
182
+ Hovering and pressing a view repaint nothing unless its picture depends on them: a `hoverScale`, a read of
183
+ `hovered` or `pressed` while laying out or drawing (detected for you), or `repaintOnPointerState()` called by
184
+ a custom view that shows its hover some other way.
185
+
186
+ ### Frames on demand: the scheduler
187
+
188
+ All drawing runs on a `FrameScheduler`. It requests an animation frame only when something is scheduled,
189
+ then draws every scene that changed (a scene with nothing new is not even composited), and stops. Scenes
190
+ share `defaultScheduler`; pass `scheduler` in the options to give one its own (for example to drive it by
191
+ hand in tests).
192
+
193
+ An error thrown by a view's layout or drawing, an animation step or a frame listener goes to
194
+ `scheduler.onError` (`console.error` by default; set it, or pass `onError` to the constructor). The rest of
195
+ the frame is drawn, and an animation that threw is stopped, so one broken view never freezes the page or keeps
196
+ it drawing.
197
+
198
+ - `tween(variable, to, { duration, easing })` animates a variable: numbers, `Point`s and `Color`s blend by
199
+ themselves, anything else with a `lerp`. A new tween of the same variable takes over from where it is.
200
+ For a user whose system asks for reduced motion, tweens and camera animations jump to their end
201
+ (`ignoreReducedMotion: true` for a change that is not motion).
202
+ - `scheduler.animate(progress => …, { duration })` calls you once per frame.
203
+ - `scheduler.acquireAutoUpdate()` keeps frames coming until you call the release it returns: for a
204
+ simulation or anything continuous.
205
+ - Easings: `animationInterpolators.linear`, `easeIn`, `easeOut`, `easeInOut`, `bounce`, `overshoot`, or
206
+ your own `AnimationInterpolator` or function.
207
+
208
+ ### Layout
209
+
210
+ A parent hands each child a `ViewBox` to fit in. Per axis, a box is a number, `"min"` (fit the content) or
211
+ `"max"` (fill the parent), within limits: `ViewBox.strictSize(size)`, `ViewBox.wrap()`,
212
+ `ViewBox.stretch()`, `ViewBox.fromOptional(width, height, minWidth, …)`.
213
+
214
+ - `Layout` stacks its children, sizes itself to the largest, and aligns them (`horizontalAlign`,
215
+ `verticalAlign`: `"start" | "center" | "end"`) inside its `padding`.
216
+ - `LinearLayout` (and `HorizontalLayout`, `VerticalLayout`) lays them out in a row or column with a `gap`;
217
+ `"max"` children share the space left.
218
+ - `Container` holds one child. A layout's `background` view covers its content box, so a card is a
219
+ `Container` with a background around a padded layout.
220
+
221
+ A layer in which nothing changed, whose camera did not move and in which no font finished loading, is not laid
222
+ out at all. A layer that changed lays out its views each frame it is drawn, except those `skipOffscreenLayout`
223
+ lets keep their last layout.
224
+
225
+ ### Level of detail
226
+
227
+ - **`skipOffscreenLayout: true`** on a layer: a view that has not changed and lies well off screen keeps its
228
+ last layout instead of being laid out every frame.
229
+ - **`ZoomLevelView({ detailed, simplified, referenceWidth, simplifiedBelow })`** draws `simplified` while
230
+ `referenceWidth` units are fewer than `simplifiedBelow` device pixels on screen, with hysteresis, and the
231
+ pick is shared by every view of the surface so neighbours agree.
232
+ - **`LevelOfDetailView({ low, createHigh, lowResolutionWidth })`** always has the cheap `low` view, builds
233
+ `high` as the view approaches the size where `low` would look poor, draws `low` until `high` is ready, and
234
+ releases `high` when zoomed out. A `LevelOfDetailRegistry` caps how many are alive.
235
+ - **`CachedView({ child })`** draws its child once into a bitmap and reuses it until the child changes. The
236
+ bitmap follows the device pixel ratio and the camera's zoom (in steps of √2), so it stays sharp.
237
+
238
+ ### Many small objects: `ShapeBatch`
239
+
240
+ A view is a reactive object of its own (about 2 KB), which is right for nodes, cards and labels, and wrong for
241
+ fifty thousand map tiles. A `ShapeBatch` is one view holding many plain items: position, size, shape
242
+ (`rect`, `roundRect`, `circle`, `diamond`, `triangle`, `hexagon`), fill, stroke and an optional label.
243
+
244
+ ```typescript
245
+ import { ShapeBatch, shapeKinds } from "@tioniq/sceniq"
246
+
247
+ const tiles = new ShapeBatch({ radius: 4, hoverCursor: "pointer", lod: { simplifyBelow: 8 } })
248
+ tiles.addMany(cells.map(cell => ({ x: cell.x, y: cell.y, width: 22, height: 22, kind: "roundRect", fill: cell.color })))
249
+ // or, for the fastest start, parallel typed arrays: fill holds indices from tiles.style("#6fae5a")
250
+ tiles.addArrays({ x, y, width, height, kind, fill })
251
+
252
+ tiles.onItemClick.subscribe(({ index }) => tiles.set(index, { fill: "#ff5d73" })) // one item changes
253
+ tiles.hoveredIndex.subscribe(index => showTooltip(index)) // -1 when none
254
+ layer.add(tiles)
255
+ overlay.add(tiles.createHighlight({ stroke: "#fff", strokeWidth: 2 })) // a layer of its own
256
+ ```
257
+
258
+ - **Drawing** reads only the items in view from a uniform grid and groups them by fill, so a frame sets each
259
+ colour once (`preserveOrder: true` keeps index order instead).
260
+ - **Level of detail** (`lod`), by an item's size on screen in device pixels: below `simplifyBelow` a plain
261
+ rectangle, below `strokeBelow` no stroke, below `hideBelow` nothing; above `detailAbove` your
262
+ `drawDetail(context, item)` adds detail; labels show when they fit. While the average item is under
263
+ `cacheBelow` pixels, the whole batch is drawn once into a bitmap and panning costs one image.
264
+ - **Input** goes through the same grid: `hoveredIndex`, `onItemClick`, `indexAt(point)`, `query(rect)`. Hovering
265
+ does not repaint the batch; `createHighlight` draws the hovered item in another layer.
266
+ - **Updates**: `set(index, patch)`, `move`, `remove`, `add`. Moving an item re-indexes that item alone.
267
+
268
+ Measured with `npm run bench` (headless Chromium, 1280 × 800, device pixel ratio 1, tiles 22 units on a
269
+ 24-unit grid; frame times are the scene's draw call, medians of 60 frames after a 3-pixel pan):
270
+
271
+ | | 50,000 views | `ShapeBatch`, 50,000 | `ShapeBatch`, 200,000 |
272
+ |---|---|---|---|
273
+ | Memory (JS heap and typed arrays, after GC) | 107 MB (2.2 KB each) | 2.4 MB (51 B each) | 9.1 MB (48 B each) |
274
+ | Building | 180 ms | 14 ms | 29 ms |
275
+ | Frame, all on screen | 125 ms | 2.6 ms (cached bitmap; 26 ms uncached) | 2.9 ms (cached; 100 ms uncached) |
276
+ | Frame, zoomed in (864 tiles on screen) | 11 ms | 3.8 ms | 3.3 ms |
277
+ | Hit test (pointer move) | | 0.7 µs | 1.1 µs |
278
+ | `set(index, …)` | | 2 µs, then one 5 to 7 ms frame | |
279
+
280
+ The uncached figure is what the first frame at a new zoom step costs, and every frame while items change
281
+ when zoomed out that far.
282
+
283
+ ### Input
284
+
285
+ - Views: `onClick`, `hovered` and `pressed` variables, `hoverScale`, `hoverCursor`, `hittable`, `enabled`.
286
+ Hit testing follows the view's scale and rotation and its parents'. `PathView` is hit along its stroke,
287
+ with a tolerance in screen pixels; a `RoundedRectangleView` with `onClick` or `hoverCursor` is hit inside its
288
+ rounded corners. A custom `hitTest` gets the view's laid-out `localBounds`. A press that moves more than
289
+ `clickSlop` CSS pixels (scene option, default 5) is not a click.
290
+ - `scene.pointerObserver`: `onPointerDown`, `onPointerMove`, `onPointerUp`, `onWheel`… with positions in CSS
291
+ pixels, pointer ids and types, and per-pointer movement. Only the primary pointer reaches views; a second
292
+ finger starts a gesture.
293
+ - `scene.keyboardObserver`: `onKeyDown`, `onKeyUp`. Nothing is prevented unless a handler calls
294
+ `event.preventDefault()`, so Tab and browser shortcuts keep working on a focused canvas.
295
+ - `attachZoomPan(scene, surface, options)`: drag to pan (it carries on outside the canvas), pinch,
296
+ `wheel: "pan" | "zoom"`, `ctrlWheel`, `minZoom`, `maxZoom`, `keys`, and `shouldPanStart` /
297
+ `shouldHandleWheel` to leave some presses to your own handlers. Optional: `inertia: true` (a drag released
298
+ while moving glides on and slows down) and `doubleClickZoom: true` (double-click or double-tap zooms in about
299
+ the pointer, Shift zooms out). Touching the view stops a glide or a camera animation. On a surface placed by
300
+ `rect` (a minimap), positions are mapped into the surface, and where a surface with controls of its own lies
301
+ on top, it takes the events.
302
+ - Clicks and double-clicks: with `doubleClickZoom` the scene holds a view's click back for a moment
303
+ (`scene.clickDelay`, 350 ms), so a double-click only zooms and does not also click what is under the pointer
304
+ twice; `doubleClickZoom: { suppressClicks: false }` keeps clicks immediate. A view that raises its own click
305
+ events calls `event.deliverClick(dispatch)` to take part.
306
+
307
+ ### Labels that fit: `LabelPlacer`
308
+
309
+ In a zoomable scene, labels collide. `LabelPlacer` decides each frame which labels to show: candidates are
310
+ sorted by tier (`"selected"`, `"hovered"`, `"important"`, `"normal"`) and `rank`, each is tried at its
311
+ `placements` in order (`"right"`, `"left"`, `"top"`, `"bottom"`, `"center"`), and kept only where its box
312
+ overlaps no label kept before and no obstacle (other items' marks; an item's own mark is skipped by `id`).
313
+ Selected and hovered labels are always shown. A uniform grid of screen cells keeps it cheap: 5,000 candidates
314
+ among 5,000 obstacles take a few milliseconds, and the placer reuses its buffers between frames.
315
+
316
+ ```typescript
317
+ const placer = new LabelPlacer()
318
+ // in a screen-fixed view's doDraw, every frame:
319
+ const placed = placer.place(
320
+ nodes.map(n => ({ x: n.screenX, y: n.screenY, gap: n.radius + 3, width: widthOf(n), height: 14,
321
+ placements: ["right", "left"], tier: n === selected ? "selected" : n.hub ? "important" : "normal",
322
+ rank: n.degree, id: n.id })),
323
+ { obstacles: nodes.map(n => ({ ...boxOf(n), id: n.id })), bounds: { x0: 0, y0: 0, x1: width, y1: height } },
324
+ )
325
+ for (const label of placed) drawText(nodes[label.index].name, label.x, label.y)
326
+ ```
327
+
328
+ The node-graph demo labels its 500 nodes this way. `placeLabels(candidates, options)` is the same for a single
329
+ call. The test suite checks that it reproduces, label for label, the hand-written placement it was modelled on.
330
+
331
+ ### The camera
332
+
333
+ `surface.camera` is the transform from world units to the surface's pixels. At zoom 1 one world unit is one
334
+ CSS pixel; the device pixel ratio is included in `camera.matrix` for you and is never part of
335
+ `currentZoom`.
336
+
337
+ ```typescript
338
+ camera.zoomTo(2) // about the origin
339
+ camera.zoom(1.5, camera.getScreenCenterWorld()) // relative, about a world point
340
+ camera.panCenterTo(new Point(500, 300))
341
+ camera.panCenterToAnimated(target, { duration: 600, interpolator: animationInterpolators.easeInOut })
342
+ camera.zoomToAnimated(4, { duration: 400 })
343
+ camera.fitBounds(rect, { padding: 24, animate: true }) // fit a world rectangle, flying there
344
+ camera.flyTo(center, 3, { duration: 600 }) // centre and zoom together, zoom changing evenly
345
+ camera.setView(center, 3) // the same at once
346
+ camera.stopAnimation() // one animation at a time; a new one takes over
347
+ const world = camera.cssToWorld(pointerEvent.viewportPosition) // CSS pixels → world (also deviceToWorld,
348
+ // worldToCss, worldToDevice)
349
+ camera.currentZoom.subscribe(zoom => …) // a variable: bind label sizes to it
350
+ camera.addZoomInterceptor(createMinMaxZoomInterceptor(0.1, 10))
351
+ ```
352
+
353
+ Every way of zooming respects the zoom interceptors (`attachZoomPan`'s `minZoom` and `maxZoom`): `zoom`,
354
+ `zoomTo`, `setMatrix`, the animations and `fitBounds`.
355
+
356
+ ### Export and diagnostics
357
+
358
+ ```typescript
359
+ const blob = await scene.toBlob({ scale: 2, background: "#fff" }) // or toDataURL, type, quality
360
+ const monitor = new FrameStatsMonitor(scene) // fps, frameMs, maxFrameMs, redrawnLayers
361
+ monitor.stats.subscribe(s => (readout.textContent = `${s.fps} fps · ${s.frameMs} ms`))
362
+ scene.onFrame.subscribe(frame => console.log(frame.time, frame.redrawnLayers))
363
+ ```
364
+
365
+ An export draws the scene again with the device pixel ratio multiplied by `scale`, so text, strokes and cached
366
+ bitmaps are sharp, then puts the canvas back before returning; the scale shrinks if the browser could not
367
+ hold a canvas that large. `FrameStatsMonitor.stats` changes on a timer (every 500 ms) and only when a figure
368
+ changed, so it can be shown inside the scene itself without causing frames. The demos' top bar uses it.
369
+
370
+ ## API overview
371
+
372
+ The complete reference is generated by typedoc: `npm run docs` writes it into `docs/api` (not committed; it is
373
+ built again before each publish).
374
+
375
+ | Area | Exports |
376
+ |---|---|
377
+ | Core | `Scene`, `Surface`, `Layer`, `FrameScheduler`, `defaultScheduler`, `LiveObject`, `TimeSlicedQueue` |
378
+ | Camera | `Camera` (`fitBounds`, `flyTo`, `setView`, `cssToWorld`), `attachZoomPan`, `createMinMaxZoomInterceptor` |
379
+ | Input | `PointerObserver`, `KeyboardObserver`, `PointerActionEvent`, `pinchStep`, `wheelZoomFactor` |
380
+ | Views | `View`, `Drawable`, `TextView`, `ImageView`, `PathView` (`CurveView`), `RoundedRectangleView`, `LineView`, `HexagonView`, `TriangleView`, `ArrowView`, `ButtonView`, `AsyncView`, `BlurredView`, `StrokeRectangleView` |
381
+ | Level of detail | `CachedView`, `ZoomLevelView`, `LevelOfDetailView`, `LevelOfDetailRegistry` |
382
+ | Many objects | `ShapeBatch`, `shapeKinds` |
383
+ | Labels | `LabelPlacer`, `placeLabels` |
384
+ | Diagnostics | `Scene.onFrame`, `FrameStatsMonitor`, `scene.toBlob`, `scene.toDataURL` |
385
+ | Layout | `Layout`, `LinearLayout`, `HorizontalLayout`, `VerticalLayout`, `Container`, `ViewContainer`, `ViewBox`, `LayoutContext` |
386
+ | Animation | `tween`, `lerpNumber`, `lerpPoint`, `lerpColor`, `AnimationInterpolator`, `animationInterpolators`, `prefersReducedMotion` |
387
+ | Text | `TextFont`, `wrapText`, `truncateText`, `relayoutAllViews` |
388
+ | Geometry | `Point`, `Size`, `RectBounds`, `Line`, `Color`, path helpers (`polylinePath`, `quadraticPath`, `cubicPath`, `flattenPath`, `distanceToPolylines`) |
389
+ | Images | `ImageSource`, `staticImageSource`, `SharedLoads`, `DrawableImage` |
390
+ | `@tioniq/sceniq/svg` | `parseSvg`, `SvgContainerView`, `drawItems`, `itemToRawSvg` |
391
+ | `@tioniq/sceniq/react` | `SceneCanvas`, `useScene` |
392
+
393
+ ## React
394
+
395
+ ```tsx
396
+ import { attachZoomPan, Point, TextView } from "@tioniq/sceniq"
397
+ import { SceneCanvas } from "@tioniq/sceniq/react"
398
+ import { createVar } from "@tioniq/eventiq"
399
+ import { useEffect } from "react"
400
+
401
+ const label = createVar("Hello")
402
+
403
+ export function Greeting({ name }: { name: string }) {
404
+ // React sets the variable; the canvas follows it without re-rendering or rebuilding the scene.
405
+ useEffect(() => {
406
+ label.value = `Hello, ${name}`
407
+ }, [name])
408
+
409
+ return (
410
+ <div style={{ height: 300 }}>
411
+ <SceneCanvas
412
+ setup={scene => {
413
+ const surface = scene.createSurface()
414
+ surface.createLayer().add(new TextView({ text: label, location: new Point(20, 20) }))
415
+ return attachZoomPan(scene, surface) // disposed with the scene
416
+ }}
417
+ />
418
+ </div>
419
+ )
420
+ }
421
+ ```
422
+
423
+ `<SceneCanvas>` renders a focusable `<canvas>` that fills its parent, creates a scene on mount, calls `setup`,
424
+ and disposes both on unmount; `deps` sets it up again on a new scene, `options` are the scene's options, and
425
+ `sceneRef` / `canvasRef` hand you the scene and the element. Other props go to the `<canvas>`. For your own
426
+ canvas element there is the hook: `useScene(ref, setup, deps, options)`. Mounting twice (StrictMode, hot reload)
427
+ leaves nothing behind: the first scene and everything bound in it are disposed. The entry is marked
428
+ `"use client"`, so it imports from a Next.js server component file.
429
+
430
+ ## Limitations
431
+
432
+ - **A view costs a couple of kilobytes.** Every view is a reactive object with its own variables (about 2.4 KB,
433
+ 3 KB while shown), so 50,000 views take some 110 to 150 MB and lay out slowly. For tens of thousands of
434
+ shapes use a `ShapeBatch` (about 50 bytes an item), as the map demo does, or draw many shapes per custom view.
435
+ - **A batch is flat.** Items of a `ShapeBatch` are boxes with one of six shapes, colours and a label; anything
436
+ richer goes in `drawDetail` or in views. Overlapping items of different fills draw in style order unless
437
+ `preserveOrder` is set, and the topmost item for hit testing is the one with the highest index.
438
+ - **Memory per layer.** Every surface and every layer is a full-size offscreen bitmap: at 4K with a device
439
+ pixel ratio of 2, each one is about 33 MB. Use few layers, and split them by how often they change.
440
+ - **Whole-layer repaints.** A change repaints its whole layer; there are no dirty rectangles. Put things that
441
+ change often (hover highlights, animations) in their own layer, away from large static content.
442
+ - **Linear hit testing of views.** Pointer input walks a layer's views from the top; only `ShapeBatch` items
443
+ have a spatial index. Thousands of hittable views per layer are fine, hundreds of thousands are not.
444
+ - **2D canvas only.** No WebGL, no workers, no `OffscreenCanvas` rendering, and no server-side rendering.
445
+ Every entry imports in plain Node (for server-rendered apps and tests), but a `Scene` needs a DOM document.
446
+ - **Labels are greedy.** `LabelPlacer` keeps the first label that fits and never moves it to make room for two
447
+ others; a label can only sit at the placements it is given.
448
+ - **Measured on one machine.** The `ShapeBatch` figures come from headless Chromium on a desktop PC; a browser
449
+ with a GPU-backed canvas draws shapes at a different cost. Run `npm run bench` on yours.
450
+ - **Uniform camera.** The camera zooms both axes together. A chart that zooms only its time axis, like the
451
+ chart demo, keeps its own range variable and draws in a screen-fixed layer.
452
+ - **Browsers.** Chrome and Edge 99+, Firefox 116+, Safari 16+ (`roundRect`, `fontBoundingBoxAscent`, Pointer
453
+ Events). Without `Intl.Segmenter` text wraps at spaces only. `BlurredView` and `toBlurred` need canvas
454
+ `filter`, which some Safari versions lack; there they draw unblurred. The exact device-pixel bitmap size
455
+ needs `devicePixelContentBoxSize` (Chrome, Firefox); elsewhere it is the CSS size times the ratio.
456
+ - **0.x.** The API may still change before 1.0; see [CHANGELOG.md](CHANGELOG.md).
457
+
458
+ ## Development
459
+
460
+ ```bash
461
+ npm test # vitest
462
+ npm run lint # biome
463
+ npm run typecheck # the sources, the tests and the demos
464
+ npm run test:smoke # build, then import the built package in a browser-like and a plain Node environment
465
+ npm run check:package # build, then publint and arethetypeswrong (ESM, CommonJS and every subpath)
466
+ npm run size # build, then the gzip size of typical imports, against budgets
467
+ npm run bench # ShapeBatch against one view per tile, in Chromium (needs Playwright)
468
+ ```
469
+
470
+ ## License
471
+
472
+ [MIT](LICENSE)