@vielzeug/codex 26.11.23 → 26.11.24
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/data/catalog.json +56 -53
- package/data/llms-full.txt +325 -57
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/atlas.json +15 -4
- package/data/packages/ink.json +15 -6
- package/data/packages/stage.json +14 -13
- package/data/packages/wire.json +21 -6
- package/data/refine.json +208 -204
- package/package.json +2 -2
package/data/packages/atlas.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
|
-
"apiSource": "// Public root surface of @vielzeug/atlas. Every public export goes through this file.\n\nexport {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';\nexport { AtlasConfigError, AtlasError } from './errors.js';\nexport { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';\nexport { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';\nexport {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';\nexport type { Matrix, Point, Rect, Size } from './shapes.js';\nexport {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';\nexport {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';\n",
|
|
2
|
+
"apiSource": "// Public root surface of @vielzeug/atlas. Every public export goes through this file.\n\nexport {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';\nexport { AtlasConfigError, AtlasError } from './errors.js';\nexport {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';\nexport { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';\nexport { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';\nexport {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';\nexport type { Matrix, Point, Rect, Size } from './shapes.js';\nexport {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';\nexport {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Atlas: Spatial Math for 2D Canvases'\ndescription: Camera transforms, matrix and rect math, polygon hit-testing, and a dynamic R-tree spatial index for infinite 2D canvases.\npackage: atlas\ncategory: utilities\nkeywords:\n [\n camera,\n viewport,\n zoom,\n pan,\n matrix,\n rect,\n aabb,\n hit-testing,\n r-tree,\n spatial-index,\n culling,\n marquee,\n geometry,\n canvas,\n ]\nexports: [createCamera, createSpatialIndex, multiply, invert, rectsIntersect, pointInPolygon, snapRect]\nrelated: [gesture, ink, wire]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"atlas\" />\n\n## Why Atlas?\n\nEvery infinite canvas re-implements the same three things badly: a camera that keeps the point under your cursor fixed while zooming, a hit-test that stops being O(n) once the scene grows, and selection and snapping math for moving rects. Atlas ships them as pure, headless primitives: a viewport-centred camera with anchor-preserving transforms and injectable animation scheduling, matrix/rect math, exact polygon narrow-phase, and a dynamic R-tree for O(log n) queries.\n\n```ts\n// Before\n// Hand-rolled transform stacks, linear scans on every pointermove, and\n// selection boxes that drift while zooming.\n\n// After\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\nconst camera = createCamera();\ncamera.zoomAt({ x: 400, y: 300 }, 1.2); // world point under (400,300) stays put\n\nconst index = createSpatialIndex();\nindex.set('shape-1', { height: 40, width: 60, x: 12, y: 8 });\nconst hits = index.queryRect(camera.visibleRect); // viewport culling, returns ids\n```\n\n| Feature | Atlas | Ad-hoc math | Full scene libraries |\n| ------------------------------------- | -------------------------------------------- | ----------- | -------------------- |\n| Bundle size | <PackageInfo package=\"atlas\" type=\"size\" /> | n/a | Typically 20–100 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a | Varies |\n| Anchor-preserving zoom/rotate | Built in | Drifts | Yes |\n| Dynamic R-tree hit-testing | Built in | O(n) scans | Yes |\n| Headless: no DOM, canvas, or renderer | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies | Usually coupled |\n\n<div class=\"decision-callout\">\n\n**Use Atlas when** you own the render loop and scene model but want correct, tested camera, geometry, and spatial-query math without writing it yourself.\n\n**Consider a full canvas engine when** you want a retained scene graph, built-in rendering, and event routing wholesale instead of headless primitives.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/atlas\n```\n\n```sh [npm]\nnpm install @vielzeug/atlas\n```\n\n```sh [yarn]\nyarn add @vielzeug/atlas\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\n// state.x/y is the world point at the viewport centre\nconst camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });\ncamera.resize({ height: 600, width: 800 });\ncamera.panBy(20, 0); // content follows the drag\ncamera.fitBounds({ height: 400, width: 600, x: -50, y: -50 }, { padding: 40 });\n\nconst index = createSpatialIndex();\nindex.set('a', { height: 10, width: 10, x: 0, y: 0 });\nindex.queryPoint({ x: 5, y: 5 }); // ['a']\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createCamera()`: viewport-centred state, pan, anchor-preserving zoom/rotate, `fitBounds()`, rotated `visibleRect`, and `animateTo()` with an injectable frame scheduler\n- `createSpatialIndex()`: dynamic R-tree (Guttman quadratic split) with `set`/`delete`/`get`/`queryRect`/`queryPoint` over ids\n- Matrix helpers: `multiply`, `invert`, `apply`, `translate`, `scale`, `rotate`, `around`, `scaleOf`, `toCssMatrix` in Canvas2D element order\n- Rect math: union, closed-interval intersection, containment, inflation, and bounds-from-points\n- Snapping: `snapRect()` alignment/grid/equal-gap guides with `kind`-tagged targets, plus pure `alignRects()`/`distributeRects()`\n- Narrow-phase geometry: `pointInPolygon`, `distanceToPolyline`, `pointNearPolygon` for exact stroke and polygon hit-testing\n- `AtlasError` / `AtlasConfigError`: typed errors; the camera follows the Vielzeug disposal contract\n- Zero runtime dependencies, no DOM requirement: works in Node, Workers, and SSR\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Gesture](/gesture/): pinch and wheel handles feed `zoomAt()` and `panBy()` directly.\n- [Ink](/ink/): stroke geometry whose bounds and outlines Atlas hit-tests.\n- [Wire](/wire/): edge routing for node editors sharing the same world coordinates.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Atlas: API Reference'\ndescription: API reference for the Atlas camera, spatial index, matrix, rect, and narrow-phase geometry helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ------------------------------------ | -------------------------------------------------------- | --------- | --------------------------------------------------------- |\n| `createCamera()` | Pan/zoom/rotate camera with anchor-preserving transforms | Sync | `x`/`y` is the world point at the viewport centre |\n| `createSpatialIndex()` | Dynamic R-tree over world-space rects | Sync | Broad-phase only: bounds overlap, not exact shape hits |\n| `multiply()` etc. | Canvas2D-order matrix composition | Sync | Element order is `[a,b,c,d,e,f]`, not row-major 3×3 |\n| `rectFromPoints()` | AABB of a point set | Sync | Returns `null` only for iterable input that may be empty |\n| `pointInPolygon()` | Even-odd ray-cast containment | Sync | Boundary points are implementation-defined; add tolerance |\n| `distanceToPolyline()` | Distance to the nearest segment | Sync | Returns `Infinity` for empty paths |\n| `snapRect()` | Alignment, grid, and equal-gap snapping with guides | Sync | Each axis resolves independently; alignment wins |\n| `alignRects()` | Align rects to a shared edge or center | Sync | Pure: returns new rects, input untouched |\n| `distributeRects()` | Equalize gaps along one axis | Sync | Needs 3+ rects; outermost rects stay fixed |\n| `AtlasError` | Base class for all atlas errors | Sync | Narrow with `instanceof AtlasError` |\n| `AtlasConfigError` | Invalid options and negative tolerances | Sync | Thrown at call time |\n| `Point` / `Rect` / `Size` / `Matrix` | Structural shapes shared across the canvas toolkit | Sync | All readonly; treat as values |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ---------------------- | ---------------------------------------------------------------------- |\n| `@vielzeug/atlas` | Camera, spatial index, matrix/rect/geometry helpers, types, and errors |\n| `@vielzeug/atlas/grid` | Square-tile math, recursive shadowcasting FOV, and fog-of-war state |\n\n---\n\n## Core Types\n\n```ts\ntype Point = Readonly<{ x: number; y: number }>;\ntype Size = Readonly<{ width: number; height: number }>;\ntype Rect = Readonly<{ x: number; y: number; width: number; height: number }>;\n/** Canvas2D/DOMMatrix element order: [a, b, c, d, e, f]. */\ntype Matrix = readonly [number, number, number, number, number, number];\n```\n\n---\n\n## `createCamera()`\n\n```ts\nfunction createCamera(options?: CameraOptions): Camera;\n```\n\nCreates a mutable camera. `state.x`/`state.y` name the world point at the **centre** of the viewport, so a saved state renders the same view on any screen size.\n\n| Parameter | Type | Description |\n| --------- | --------------- | ----------------------------------------------------------------------------------- |\n| `options` | `CameraOptions` | `initial` state, `viewport` size in CSS px, `minZoom`/`maxZoom` clamps, `scheduler` |\n\n**Returns:** `Camera` handle.\n\n**Example**\n\n```ts\nimport { createCamera } from '@vielzeug/atlas';\n\nconst camera = createCamera({\n initial: { zoom: 1.5 },\n maxZoom: 8,\n minZoom: 0.1,\n viewport: { height: 600, width: 800 },\n});\ncamera.zoomAt({ x: 400, y: 300 }, 1.2);\n```\n\nWithout `viewport` the camera starts at 0×0, where the centre is the origin; call `camera.resize()` once the real size is known (a `ResizeObserver` on the viewport element is the usual source).\n\nThrows `AtlasConfigError` when clamps violate `0 < minZoom <= maxZoom` or initial coordinates are non-finite.\n\n### Camera members\n\n| Member | Description |\n| ---------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `state` | Current `{ x, y, zoom, rotation }` (readonly snapshot) |\n| `viewport` | Current viewport `Size` in CSS px |\n| `matrix` / `inverse` | world → screen / screen → world matrices; `inverse` is always defined |\n| `toScreen(p)` / `toWorld(p)` | Point transforms |\n| `set(target)` | Jump to a partial state immediately, cancelling any animation |\n| `resize(size)` | Change the viewport size, keeping the world centre fixed |\n| `panBy(dx, dy)` | Screen-space pan; content follows the delta |\n| `zoomAt(screenPoint, factor)` | Multiplicative zoom holding the world point under `screenPoint` fixed |\n| `rotateAt(screenPoint, delta)` | Rotation (radians) holding the world point under `screenPoint` fixed |\n| `fitBounds(bounds, { padding? })` | Frame `bounds` in the current viewport at current rotation |\n| `visibleRect` | World AABB of the rotated viewport, for culling (getter) |\n| `animateTo(target, options?)` | Animate `{ x, y, zoom, rotation }`; replaces any running animation |\n| `stop()` | Cancel the running animation without completing it |\n| `subscribe(listener, options?)` | State-change listener; returns an unsubscribe function |\n| `dispose()` / `disposed` / `disposalSignal` / `[Symbol.dispose]` | Vielzeug disposal contract; disposal aborts animations |\n\nDirect manipulation (`set`, `resize`, `panBy`, `zoomAt`, `rotateAt`, `fitBounds`) cancels a running `animateTo` first, so user input is never overwritten by the next animation frame. After `dispose`, every mutating method is a no-op and `subscribe` returns a no-op unsubscribe.\n\n`AnimationOptions`: `duration` (ms, default 250), `easing` (default ease-in-out), `signal` (abort mid-flight; the animation stops where it is). Zoom interpolates in log space; rotation takes the shortest angular path and lands normalized to `(-π, π]`. A zoom-only animation keeps the viewport centre fixed.\n\n`FrameScheduler`: `{ requestFrame, cancelFrame, now }`. Defaults to `requestAnimationFrame`/`performance.now()`; inject a fake one in tests.\n\n---\n\n## `createSpatialIndex()`\n\n```ts\nfunction createSpatialIndex<K = string>(options?: SpatialIndexOptions): SpatialIndex<K>;\n```\n\nCreates a dynamic R-tree (Guttman, quadratic split) keyed by ids. The index stores only ids and rects — you keep your data in your own `Map` and look it up from returned ids — so stored values can never go stale.\n\n| Parameter | Type | Description |\n| --------- | --------------------- | -------------------------------------------- |\n| `options` | `SpatialIndexOptions` | `maxEntriesPerNode` (integer ≥ 4, default 8) |\n\n**Returns:** `SpatialIndex<K>` handle.\n\n**Example**\n\n```ts\nimport { createSpatialIndex } from '@vielzeug/atlas';\n\nconst shapes = new Map<string, Shape>();\nconst index = createSpatialIndex();\nindex.set('a', { height: 10, width: 10, x: 0, y: 0 });\nconst hits = index.queryRect(marquee); // string[] of ids\nconst shape = shapes.get(hits[0]);\n```\n\n### SpatialIndex members\n\n| Member | Description |\n| ----------------------------------- | ----------------------------------------------------------------------------------- |\n| `set(id, rect)` | Insert, or move an existing id; a no-op when the rect is unchanged |\n| `delete(id)` | `true` when removed, `false` when unknown |\n| `get(id)` | The current `Rect` for an id, or `undefined` |\n| `has(id)` | Membership test |\n| `queryRect(rect)` | Ids whose bounds overlap **or touch** `rect` (closed intervals) |\n| `queryPoint(point, { tolerance? })` | Ids within `tolerance` of `point` (default 0, inclusive); throws on negative values |\n| `clear()` / `size` / `bounds` | Reset, entry count, aggregate bounds (`null` when empty) |\n\nClosed-interval semantics mean zero-area rects (lines, points) are findable: a horizontal line entry is returned by any query rect that crosses it. The index owns no resources, so it has no disposal contract — drop the reference when done.\n\n---\n\n## Matrix Functions\n\nAll matrices use Canvas2D element order `[a, b, c, d, e, f]`; composition `multiply(a, b)` applies `a` first, then `b` (same order as chained `ctx.transform()` calls).\n\n| Function | Description |\n| ------------------------ | ------------------------------------------------- |\n| `IDENTITY` | Frozen identity matrix |\n| `multiply(a, b)` | Compose two matrices |\n| `apply(matrix, point)` | Transform a point |\n| `translate(tx, ty)` | Translation builder |\n| `scale(sx, sy?)` | Scale builder (`sy` defaults to `sx`) |\n| `rotate(radians)` | Rotation builder; positive is clockwise on screen |\n| `invert(matrix)` | Inverse; `null` for zero determinant |\n| `around(anchor, matrix)` | `translate(anchor) · matrix · translate(-anchor)` |\n| `scaleOf(matrix)` | Average axis scale (0 for degenerate matrices) |\n| `toCssMatrix(matrix)` | `matrix(...)` CSS value |\n\n---\n\n## Rect Functions\n\n| Function | Description |\n| ----------------------------------------------------------- | ------------------------------------------------------------------------------ |\n| `rectFromPoints(points)` | AABB of a point set; `null` for iterable input, non-null for a non-empty tuple |\n| `rectRight(rect)` / `rectBottom(rect)` / `rectCenter(rect)` | Edge and center accessors |\n| `unionRect(a, b)` | Smallest rect containing both |\n| `intersectRect(a, b)` | Overlap rect; `null` only when disjoint; touching yields a zero-area rect |\n| `rectsIntersect(a, b)` | Overlap-or-touch test (closed intervals) |\n| `containsRect(outer, inner)` / `containsPoint(rect, point)` | Inclusive containment tests |\n| `inflateRect(rect, amount)` | Grow every edge by `amount` |\n\n`rectFromPoints` has two overloads: pass a literal non-empty tuple (`rectFromPoints([a, b])`) for a guaranteed `Rect`, or any `Iterable<Point>` for `Rect | null`.\n\n---\n\n## Geometry Functions\n\n| Function | Description |\n| --------------------------------------------- | --------------------------------------------------------------------------- |\n| `pointInPolygon(polygon, point)` | Even-odd ray-cast containment |\n| `distanceToPolyline(path, point)` | Distance to the nearest segment; `Infinity` for empty paths |\n| `pointNearPolygon(polygon, point, tolerance)` | Inside the polygon OR within `tolerance` of its outline; throws on negative |\n\n---\n\n## Snapping Functions\n\n| Function | Description |\n| ------------------------------ | ---------------------------------------------------------------------------------------------- |\n| `snapRect(rect, options)` | Snapped `{ delta, guides }` against candidate rects, grid lines, and equal gaps |\n| `alignRects(rects, edge)` | Copies aligned to a shared `left`/`horizontal-center`/`right`/`top`/`vertical-center`/`bottom` |\n| `distributeRects(rects, axis)` | Copies with equalized gaps along `'x'` or `'y'` |\n\n`snapRect` options: `candidates` (rects to snap to; the moving rect itself must not be included), `grid` (`{ x?, y? }` line spacing), `spacing` (enable equal-gap centering, default `false`), `threshold` (max snap distance; throws `AtlasConfigError` when negative). Each axis resolves independently to its nearest target within `threshold` (inclusive) among candidate anchors (left/center/right, top/center/bottom) and grid lines; the guide's `kind` reports which one engaged. When no target engaged on an axis, `spacing: true` centers the rect between its nearest neighbors when the two gaps can be made equal within `threshold`. A candidate counts as a neighbor only when it overlaps the moving rect on the perpendicular axis, and both sides need one.\n\nA `SnapGuide` is `{ axis, kind, position, from, to, marks? }`: `axis` is the axis the guide line is perpendicular to, `kind` is `'grid'`, `'object'`, or `'spacing'` (what the snap engaged, for dashed vs solid rendering), `position` is the world coordinate of the line, and `from`/`to` span the line along the other axis. Spacing guides sit at the position the rect actually occupies after both axes snapped, and carry `marks`: the centers of the two equal gaps, to draw as × markers. `alignRects` and `distributeRects` are pure; distribution keeps the outermost rects fixed and returns input copies unchanged for fewer than three rects.\n\n---\n\n## Grid Functions\n\nFrom the `@vielzeug/atlas/grid` subpath:\n\n| Function | Returns |\n| -------------------------------------- | ----------------------------------------------------------------------------------------------- |\n| `worldToTile(point, grid)` | `TileCoord` (`{ col, row }`) containing the point (floor division) |\n| `tileToRect(coord, grid)` | World `Rect` of the tile |\n| `tileCenter(coord, grid)` | World `Point` at the tile's centre |\n| `visibleTileRange(view, grid)` | `TileRange` (`minCol/maxCol/minRow/maxRow`) intersecting a world rect |\n| `iterateTileRange(range)` | Generator over every `TileCoord` in a range |\n| `tileKey(coord)` | Stable `\"col:row\"` string |\n| `computeFov(origin, radius, options?)` | `Set<string>` of visible `tileKey`s (8-octant recursive shadowcasting) |\n| `createFog()` | Three-state fog tracker over tile keys: `update`/`state`/`visible`, `exportState`/`importState` |\n\n`grid` is `{ tileSize }` (positive; `worldToTile`/`tileToRect`/`tileCenter`/`visibleTileRange` throw `AtlasConfigError` otherwise, as does a negative/non-integer FOV `radius`). `computeFov` options: `blocks(coord)` returns true when sight cannot pass through the tile; blocking tiles within range are themselves visible. The origin is always in the result. `TileCoord` is `{ col, row }`. `createFog()` stores `tileKey` strings, so a `computeFov` result feeds `fog.update()` directly: one call demotes the previously visible tiles to `seen` and marks the new keys `visible`. `fog.visible` is a `ReadonlySet<string>`.\n\n---\n\n## Errors\n\n| Class | Thrown when |\n| ------------------ | ------------------------------------------------------------ |\n| `AtlasError` | Base class; catch-all via `instanceof AtlasError` |\n| `AtlasConfigError` | Invalid options/clamps and negative snap or query tolerances |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Atlas: Usage Guide'\ndescription: Drive a camera, index shapes in an R-tree, and hit-test points, marquee rects, and polygons with Atlas.\n---\n\n[[toc]]\n\n## Basic Usage\n\nAtlas is headless: it never touches the DOM or a canvas. You feed it input events and scene rectangles, and it answers where things are.\n\n```ts\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\n// Camera: (x, y) is the world point shown at the viewport centre.\nconst camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });\ncamera.resize({ height: viewport.clientHeight, width: viewport.clientWidth });\n\n// Screen → world for input handling.\nconst world = camera.toWorld({ x: event.offsetX, y: event.offsetY });\n\n// World → screen for positioning DOM overlays.\nconst screen = camera.toScreen(shape.position);\n```\n\n## Coordinate Spaces\n\nAtlas works in three spaces and never guesses between them:\n\n- **Client space**: `PointerEvent.clientX/Y`. Subtract the viewport's `getBoundingClientRect()` offset before handing coordinates to the camera.\n- **Screen space**: CSS pixels from the viewport element's top-left. `toWorld()` and `zoomAt()` take screen points. The camera learns this size through `resize()` — a `ResizeObserver` on the viewport element is the usual source.\n- **World space**: your scene coordinates. `camera.matrix` maps world → screen; `zoom` is screen pixels per world unit.\n\nPositive `rotation` is clockwise on screen (y grows downward) and is kept normalized to `(-π, π]`. `camera.matrix` uses Canvas2D element order `[a, b, c, d, e, f]`, so you can hand it straight to `ctx.setTransform()` (multiply by DPR first) or hand it to `toCssMatrix()` for DOM overlays. The getter is a cached composite recomputed only when the camera changes.\n\n## Zooming to the Cursor\n\n`zoomAt()` keeps the world point under a screen point fixed while the zoom changes — the standard infinite-canvas feel:\n\n```ts\nwheelElement.addEventListener('wheel', (event) => {\n const factor = Math.exp(-event.deltaY * 0.0015);\n camera.zoomAt({ x: event.offsetX, y: event.offsetY }, factor);\n});\n```\n\n`rotateAt()` does the same for rotation. Both clamp against `minZoom`/`maxZoom` and still hold the anchor exactly at the clamp.\n\n## Panning and Fitting\n\n`panBy(dx, dy)` takes a screen-space delta; content follows the drag. `fitBounds()` frames a world rect inside the current viewport with optional padding, preserving the current rotation:\n\n```ts\ncamera.panBy(event.movementX, event.movementY);\ncamera.fitBounds(selectionBounds, { padding: 48 });\n```\n\nBecause `state.x`/`state.y` is the world point at the viewport centre, a saved camera state re-frames the same view on any screen size, and a zoom-only `animateTo({ zoom })` keeps the view centred where the user is looking.\n\n## Animating the Camera\n\n`animateTo()` interpolates position linearly and zoom in log space (multiplicative zoom feels linear to the eye). Rotation takes the shortest angular path. Pass an injectable scheduler to drive animations from your render loop or tests:\n\n```ts\ncamera.animateTo(\n { x: 250, y: 100, zoom: 2 },\n {\n duration: 300,\n signal: controller.signal, // abort mid-flight; the animation stops where it is\n },\n);\n```\n\n## Indexing the Scene\n\n`createSpatialIndex()` is a dynamic R-tree keyed by ids. Index every shape by its world-space bounding box, then answer three questions fast: what is under this point, what does this marquee rect touch, and what is inside the viewport:\n\n```ts\nconst index = createSpatialIndex(); // keys default to string\n\nindex.set(shape.id, shape.bounds); // insert, and again after every move\nindex.delete(shape.id); // on delete\n\n// Viewport culling each frame.\nconst visibleIds = index.queryRect(camera.visibleRect);\n\n// Marquee selection — the index returns ids; your own Map holds the data.\nconst selected = index.queryRect(marquee).map((id) => shapes.get(id));\n\n// Hover: tolerance widens the point into a box for fat-finger targets.\nconst hovered = index.queryPoint(worldPoint, { tolerance: 4 / camera.state.zoom });\n```\n\nThe index stores only ids and rects, so it can never hand back a stale copy of your data — call `set()` with the new rect after each committed move. Queries use closed intervals: touching edges count, and zero-area rects (lines, points) are findable. The R-tree is broad-phase only: it answers \"bounding boxes overlap or touch\". For exact hits on polygonal shapes, follow up with the narrow-phase helpers below.\n\n## Exact Hit-Testing\n\n```ts\nimport { pointNearPolygon, pointInPolygon } from '@vielzeug/atlas';\n\npointInPolygon(polygon, worldPoint); // even-odd ray cast\npointNearPolygon(polygon, worldPoint, 2); // inside OR within 2 units of the outline\n```\n\nBuild the polygon from the shape's actual corners (rotate each point yourself with `apply()` if needed) and index its axis-aligned hull in the R-tree. `pointNearPolygon` is what a vector tool needs to hit-test a stroked (unfilled) shape: the outline band plus the interior both count.\n\n## Snapping and Alignment\n\nWhile a shape moves, one `snapRect()` call snaps it to nearby shapes, grid lines, and equal gaps, and returns the guides to draw on an overlay:\n\n```ts\nimport { snapRect } from '@vielzeug/atlas';\n\nconst snap = snapRect(dragRect, {\n candidates: otherSelectedOutRects,\n grid: { x: 50, y: 50 },\n spacing: true, // opt into equal-gap spacing between neighbors\n threshold: 8,\n});\nconst snapped = { ...dragRect, x: dragRect.x + snap.delta.x, y: dragRect.y + snap.delta.y };\n// snap.guides: [{ axis, kind, position, from, to, marks? }] in world coordinates — draw them through the camera.\n```\n\nEach axis resolves independently to its nearest target within `threshold` among candidate anchors (left/center/right, top/center/bottom) and grid lines; the guide's `kind` says which one engaged. With `spacing: true`, an axis that found no target at all falls back to img.ly-style equal-gap centering: the rect centers itself between its nearest neighbors when the two gaps can be made equal within `threshold`. A candidate only counts as a neighbor when it overlaps the moving rect on the perpendicular axis, and both sides need one, so a lone shape never spacing-snaps.\n\nEvery guide carries `kind: 'grid' | 'object' | 'spacing'` so you can style them apart (dashed for grid, solid for objects, × marks at `marks` for spacing). `axis` is the axis the line is perpendicular to: an `axis: 'x'` guide is a vertical line at `position`, running from `from` to `to`. Spacing guides sit at the position the rect actually occupies after both axes snapped, so the marker lines up with the shape. On drop, commit `snapped` to your model so undo history records the final position, not the raw pointer position.\n\nAfter a multi-select, align or distribute with the pure helpers and record one command:\n\n```ts\nimport { alignRects, distributeRects } from '@vielzeug/atlas';\n\nconst aligned = alignRects(selectedRects, 'horizontal-center'); // copies, same order\nconst spread = distributeRects(selectedRects, 'x'); // equal gaps, outermost fixed\n```\n\n## Matrix Helpers\n\nFor custom transforms, the matrix functions use Canvas2D order and compose left-to-right like `ctx.transform()`:\n\n```ts\nimport {\n apply,\n around,\n IDENTITY,\n invert,\n multiply,\n rotate,\n scale,\n scaleOf,\n toCssMatrix,\n translate,\n} from '@vielzeug/atlas';\n\nconst transform = multiply(multiply(scale(2), rotate(Math.PI / 4)), translate(10, 5));\napply(transform, { x: 1, y: 0 }); // transformed point\ninvert(transform); // null for degenerate matrices\naround({ x: 100, y: 100 }, scale(2)); // scale about a point, not the origin\nscaleOf(transform); // average axis scale\ntoCssMatrix(transform); // 'matrix(...)' for CSS transforms\n```\n\n## Tile Grids\n\nTile and map editors live on a square grid. The `@vielzeug/atlas/grid` subpath converts between world coordinates and tile coordinates, and enumerates only the tiles a viewport can see:\n\n```ts\nimport { iterateTileRange, tileCenter, tileKey, tileToRect, visibleTileRange, worldToTile } from '@vielzeug/atlas/grid';\n\nconst grid = { tileSize: 32 };\n\nworldToTile({ x: 40, y: -1 }, grid); // { col: 1, row: -1 }\ntileToRect({ col: 1, row: -1 }, grid); // { x: 32, y: -32, width: 32, height: 32 }\ntileCenter({ col: 1, row: -1 }, grid); // { x: 48, y: -16 }\n\n// Render loop: iterate the tiles intersecting the camera's world rect.\nfor (const coord of iterateTileRange(visibleTileRange(camera.visibleRect, grid))) {\n drawTile(coord);\n}\n```\n\n`tileKey(coord)` yields the stable `\"col:row\"` string used by the FOV and fog APIs (and convenient as a `Map` key).\n\n## Field of View and Fog\n\n`computeFov()` runs recursive shadowcasting over the eight octants and returns the set of `tileKey` strings a viewer can see within a radius. Blocking tiles are visible but cast shadows behind themselves:\n\n```ts\nimport { computeFov, createFog } from '@vielzeug/atlas/grid';\n\nconst fov = computeFov({ col: 10, row: 8 }, 6, { blocks: (c) => walls.has(`${c.col}:${c.row}`) });\n\nconst fog = createFog();\nfog.update(fov); // demotes the previous frame's visible tiles to 'seen'\nfog.state(tileKey({ col: 10, row: 8 })); // 'visible' | 'seen' | 'unseen'\nsaveGame(fog.exportState()); // serializable { seen, visible } key lists\n```\n\n`computeFov()` is pure and costs O(radius²) worst case; walls prune the walk. `createFog()` owns the three-state bookkeeping (`unseen` → `visible` → `seen`) over `tileKey` strings and round-trips through `exportState()`/`importState()` for save files. One `update(visibleKeys)` call per frame replaces the whole visible set — demote-then-reveal ordering is handled for you — and `fog.visible` is a `ReadonlySet<string>` of the current keys.\n\n## Best Practices\n\n- Subtract the viewport rect once at the input boundary; never mix client and screen coordinates inside camera calls.\n- Call `camera.resize()` from a `ResizeObserver` on the viewport element; the camera cannot anchor zooms to the centre without knowing its size.\n- Call `index.set(id, rect)` after every committed move — stale bounds silently break marquee and culling queries.\n- Use `camera.visibleRect` (the world AABB of the rotated viewport) for culling; it is conservative by design, so no visible shape is ever dropped.\n- Snap against the pre-move rect each pointer move (not the last snapped rect) so the delta stays relative to the raw pointer and snapping never drifts cumulatively.\n- Dispose the camera when the editor unmounts; disposal aborts in-flight animations and turns every mutating method into a no-op. The spatial index owns no resources, so it needs no disposal.\n",
|
|
4
|
+
"index": "---\ntitle: 'Atlas: Spatial Math for 2D Canvases'\ndescription: Camera transforms, matrix and rect math, polygon hit-testing, and a dynamic R-tree spatial index for infinite 2D canvases.\npackage: atlas\ncategory: utilities\nkeywords:\n [\n camera,\n viewport,\n zoom,\n pan,\n matrix,\n rect,\n aabb,\n hit-testing,\n r-tree,\n spatial-index,\n culling,\n marquee,\n geometry,\n canvas,\n ]\nexports: [createCamera, createSpatialIndex, multiply, invert, rectsIntersect, pointInPolygon, snapRect]\nrelated: [gesture, ink, wire]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"atlas\" />\n\n## Why Atlas?\n\nEvery infinite canvas re-implements the same three things badly: a camera that keeps the point under your cursor fixed while zooming, a hit-test that stops being O(n) once the scene grows, and selection and snapping math for moving rects. Atlas ships them as pure, headless primitives: a viewport-centred camera with anchor-preserving transforms and injectable animation scheduling, matrix/rect math, exact polygon narrow-phase, and a dynamic R-tree for O(log n) queries.\n\n```ts\n// Before\n// Hand-rolled transform stacks, linear scans on every pointermove, and\n// selection boxes that drift while zooming.\n\n// After\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\nconst camera = createCamera();\ncamera.zoomAt({ x: 400, y: 300 }, 1.2); // world point under (400,300) stays put\n\nconst index = createSpatialIndex();\nindex.set('shape-1', { height: 40, width: 60, x: 12, y: 8 });\nconst hits = index.queryRect(camera.visibleRect); // viewport culling, returns ids\n```\n\n| Feature | Atlas | Ad-hoc math | Full scene libraries |\n| ------------------------------------- | -------------------------------------------- | ----------- | -------------------- |\n| Bundle size | <PackageInfo package=\"atlas\" type=\"size\" /> | n/a | Typically 20–100 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a | Varies |\n| Anchor-preserving zoom/rotate | Built in | Drifts | Yes |\n| Dynamic R-tree hit-testing | Built in | O(n) scans | Yes |\n| Headless: no DOM, canvas, or renderer | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies | Usually coupled |\n\n<div class=\"decision-callout\">\n\n**Use Atlas when** you own the render loop and scene model but want correct, tested camera, geometry, and spatial-query math without writing it yourself.\n\n**Consider a full canvas engine when** you want a retained scene graph, built-in rendering, and event routing wholesale instead of headless primitives.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/atlas\n```\n\n```sh [npm]\nnpm install @vielzeug/atlas\n```\n\n```sh [yarn]\nyarn add @vielzeug/atlas\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\n// state.x/y is the world point at the viewport centre\nconst camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });\ncamera.resize({ height: 600, width: 800 });\ncamera.panBy(20, 0); // content follows the drag\ncamera.fitBounds({ height: 400, width: 600, x: -50, y: -50 }, { padding: 40 });\n\nconst index = createSpatialIndex();\nindex.set('a', { height: 10, width: 10, x: 0, y: 0 });\nindex.queryPoint({ x: 5, y: 5 }); // ['a']\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createCamera()`: viewport-centred state, pan, anchor-preserving zoom/rotate, `fitBounds()`, rotated `visibleRect`, and `animateTo()` with an injectable frame scheduler\n- `createSpatialIndex()`: dynamic R-tree (Guttman quadratic split) with `set`/`delete`/`get`/`queryRect`/`queryPoint` over ids\n- Matrix helpers: `multiply`, `invert`, `apply`, `translate`, `scale`, `rotate`, `around`, `scaleOf`, `toCssMatrix` in Canvas2D element order\n- Rect math: union, closed-interval intersection, containment, inflation, and bounds-from-points\n- Snapping: `snapRect()` alignment/grid/equal-gap guides with `kind`-tagged targets, plus pure `alignRects()`/`distributeRects()`\n- Narrow-phase geometry: `pointInPolygon`, `distanceToPolyline`, `pointNearPolygon` for exact stroke and polygon hit-testing\n- Frames: `frameMatrix()` local→world placement, `boundsOfFrame()` world AABBs, and `resizeRect()` editor resize math with min and aspect locks\n- `AtlasError` / `AtlasConfigError`: typed errors; the camera follows the Vielzeug disposal contract\n- Zero runtime dependencies, no DOM requirement: works in Node, Workers, and SSR\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Gesture](/gesture/): pinch and wheel handles feed `zoomAt()` and `panBy()` directly.\n- [Ink](/ink/): stroke geometry whose bounds and outlines Atlas hit-tests.\n- [Wire](/wire/): edge routing for node editors sharing the same world coordinates.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Atlas: API Reference'\ndescription: API reference for the Atlas camera, spatial index, matrix, rect, frame, and narrow-phase geometry helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ------------------------------------ | ---------------------------------------------------------- | --------- | ----------------------------------------------------------- |\n| `createCamera()` | Pan/zoom/rotate camera with anchor-preserving transforms | Sync | `x`/`y` is the world point at the viewport centre |\n| `createSpatialIndex()` | Dynamic R-tree over world-space rects | Sync | Broad-phase only: bounds overlap, not exact shape hits |\n| `multiply()` etc. | Canvas2D-order matrix composition | Sync | Element order is `[a,b,c,d,e,f]`, not row-major 3×3 |\n| `rectFromPoints()` | AABB of a point set | Sync | Returns `null` only for iterable input that may be empty |\n| `pointInPolygon()` | Even-odd ray-cast containment | Sync | Boundary points are implementation-defined; add tolerance |\n| `distanceToPolyline()` | Distance to the nearest segment | Sync | Returns `Infinity` for empty paths |\n| `snapRect()` | Alignment, grid, and equal-gap snapping with guides | Sync | Each axis resolves independently; alignment wins |\n| `alignRects()` | Align rects to a shared edge or center | Sync | Pure: returns new rects, input untouched |\n| `distributeRects()` | Equalize gaps along one axis | Sync | Needs 3+ rects; outermost rects stay fixed |\n| `frameMatrix()` | Local→world matrix for a positioned, rotated, scaled frame | Sync | `origin` is a world pivot; defaults to `{ x, y }` |\n| `boundsOfFrame()` | AABB of a rect under a frame matrix | Sync | Grows the bounds for rotation; not a tight oriented box |\n| `resizeRect()` | Resize a rect by dragging named edges | Sync | `aspect` is width/height; corner drags derive the free axis |\n| `AtlasError` | Base class for all atlas errors | Sync | Narrow with `instanceof AtlasError` |\n| `AtlasConfigError` | Invalid options and negative tolerances | Sync | Thrown at call time |\n| `Point` / `Rect` / `Size` / `Matrix` | Structural shapes shared across the canvas toolkit | Sync | All readonly; treat as values |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ---------------------- | ---------------------------------------------------------------------- |\n| `@vielzeug/atlas` | Camera, spatial index, matrix/rect/geometry helpers, types, and errors |\n| `@vielzeug/atlas/grid` | Square-tile math, recursive shadowcasting FOV, and fog-of-war state |\n\n---\n\n## Core Types\n\n```ts\ntype Point = Readonly<{ x: number; y: number }>;\ntype Size = Readonly<{ width: number; height: number }>;\ntype Rect = Readonly<{ x: number; y: number; width: number; height: number }>;\n/** Canvas2D/DOMMatrix element order: [a, b, c, d, e, f]. */\ntype Matrix = readonly [number, number, number, number, number, number];\n```\n\n---\n\n## `createCamera()`\n\n```ts\nfunction createCamera(options?: CameraOptions): Camera;\n```\n\nCreates a mutable camera. `state.x`/`state.y` name the world point at the **centre** of the viewport, so a saved state renders the same view on any screen size.\n\n| Parameter | Type | Description |\n| --------- | --------------- | ----------------------------------------------------------------------------------- |\n| `options` | `CameraOptions` | `initial` state, `viewport` size in CSS px, `minZoom`/`maxZoom` clamps, `scheduler` |\n\n**Returns:** `Camera` handle.\n\n**Example**\n\n```ts\nimport { createCamera } from '@vielzeug/atlas';\n\nconst camera = createCamera({\n initial: { zoom: 1.5 },\n maxZoom: 8,\n minZoom: 0.1,\n viewport: { height: 600, width: 800 },\n});\ncamera.zoomAt({ x: 400, y: 300 }, 1.2);\n```\n\nWithout `viewport` the camera starts at 0×0, where the centre is the origin; call `camera.resize()` once the real size is known (a `ResizeObserver` on the viewport element is the usual source).\n\nThrows `AtlasConfigError` when clamps violate `0 < minZoom <= maxZoom` or initial coordinates are non-finite.\n\n### Camera members\n\n| Member | Description |\n| ---------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `state` | Current `{ x, y, zoom, rotation }` (readonly snapshot) |\n| `viewport` | Current viewport `Size` in CSS px |\n| `matrix` / `inverse` | world → screen / screen → world matrices; `inverse` is always defined |\n| `toScreen(p)` / `toWorld(p)` | Point transforms |\n| `set(target)` | Jump to a partial state immediately, cancelling any animation |\n| `resize(size)` | Change the viewport size, keeping the world centre fixed |\n| `panBy(dx, dy)` | Screen-space pan; content follows the delta |\n| `zoomAt(screenPoint, factor)` | Multiplicative zoom holding the world point under `screenPoint` fixed |\n| `rotateAt(screenPoint, delta)` | Rotation (radians) holding the world point under `screenPoint` fixed |\n| `fitBounds(bounds, { padding? })` | Frame `bounds` in the current viewport at current rotation |\n| `visibleRect` | World AABB of the rotated viewport, for culling (getter) |\n| `animateTo(target, options?)` | Animate `{ x, y, zoom, rotation }`; replaces any running animation |\n| `stop()` | Cancel the running animation without completing it |\n| `subscribe(listener, options?)` | State-change listener; returns an unsubscribe function |\n| `dispose()` / `disposed` / `disposalSignal` / `[Symbol.dispose]` | Vielzeug disposal contract; disposal aborts animations |\n\nDirect manipulation (`set`, `resize`, `panBy`, `zoomAt`, `rotateAt`, `fitBounds`) cancels a running `animateTo` first, so user input is never overwritten by the next animation frame. After `dispose`, every mutating method is a no-op and `subscribe` returns a no-op unsubscribe.\n\n`AnimationOptions`: `duration` (ms, default 250), `easing` (default ease-in-out), `signal` (abort mid-flight; the animation stops where it is). Zoom interpolates in log space; rotation takes the shortest angular path and lands normalized to `(-π, π]`. A zoom-only animation keeps the viewport centre fixed.\n\n`FrameScheduler`: `{ requestFrame, cancelFrame, now }`. Defaults to `requestAnimationFrame`/`performance.now()`; inject a fake one in tests.\n\n---\n\n## `createSpatialIndex()`\n\n```ts\nfunction createSpatialIndex<K = string>(options?: SpatialIndexOptions): SpatialIndex<K>;\n```\n\nCreates a dynamic R-tree (Guttman, quadratic split) keyed by ids. The index stores only ids and rects — you keep your data in your own `Map` and look it up from returned ids — so stored values can never go stale.\n\n| Parameter | Type | Description |\n| --------- | --------------------- | -------------------------------------------- |\n| `options` | `SpatialIndexOptions` | `maxEntriesPerNode` (integer ≥ 4, default 8) |\n\n**Returns:** `SpatialIndex<K>` handle.\n\n**Example**\n\n```ts\nimport { createSpatialIndex } from '@vielzeug/atlas';\n\nconst shapes = new Map<string, Shape>();\nconst index = createSpatialIndex();\nindex.set('a', { height: 10, width: 10, x: 0, y: 0 });\nconst hits = index.queryRect(marquee); // string[] of ids\nconst shape = shapes.get(hits[0]);\n```\n\n### SpatialIndex members\n\n| Member | Description |\n| ----------------------------------- | ----------------------------------------------------------------------------------- |\n| `set(id, rect)` | Insert, or move an existing id; a no-op when the rect is unchanged |\n| `delete(id)` | `true` when removed, `false` when unknown |\n| `get(id)` | The current `Rect` for an id, or `undefined` |\n| `has(id)` | Membership test |\n| `queryRect(rect)` | Ids whose bounds overlap **or touch** `rect` (closed intervals) |\n| `queryPoint(point, { tolerance? })` | Ids within `tolerance` of `point` (default 0, inclusive); throws on negative values |\n| `clear()` / `size` / `bounds` | Reset, entry count, aggregate bounds (`null` when empty) |\n\nClosed-interval semantics mean zero-area rects (lines, points) are findable: a horizontal line entry is returned by any query rect that crosses it. The index owns no resources, so it has no disposal contract — drop the reference when done.\n\n---\n\n## Matrix Functions\n\nAll matrices use Canvas2D element order `[a, b, c, d, e, f]`; composition `multiply(a, b)` applies `a` first, then `b` (same order as chained `ctx.transform()` calls).\n\n| Function | Description |\n| ------------------------ | ------------------------------------------------- |\n| `IDENTITY` | Frozen identity matrix |\n| `multiply(a, b)` | Compose two matrices |\n| `apply(matrix, point)` | Transform a point |\n| `translate(tx, ty)` | Translation builder |\n| `scale(sx, sy?)` | Scale builder (`sy` defaults to `sx`) |\n| `rotate(radians)` | Rotation builder; positive is clockwise on screen |\n| `invert(matrix)` | Inverse; `null` for zero determinant |\n| `around(anchor, matrix)` | `translate(anchor) · matrix · translate(-anchor)` |\n| `scaleOf(matrix)` | Average axis scale (0 for degenerate matrices) |\n| `toCssMatrix(matrix)` | `matrix(...)` CSS value |\n\n---\n\n## Rect Functions\n\n| Function | Description |\n| ----------------------------------------------------------- | ------------------------------------------------------------------------------ |\n| `rectFromPoints(points)` | AABB of a point set; `null` for iterable input, non-null for a non-empty tuple |\n| `rectRight(rect)` / `rectBottom(rect)` / `rectCenter(rect)` | Edge and center accessors |\n| `unionRect(a, b)` | Smallest rect containing both |\n| `intersectRect(a, b)` | Overlap rect; `null` only when disjoint; touching yields a zero-area rect |\n| `rectsIntersect(a, b)` | Overlap-or-touch test (closed intervals) |\n| `containsRect(outer, inner)` / `containsPoint(rect, point)` | Inclusive containment tests |\n| `inflateRect(rect, amount)` | Grow every edge by `amount` |\n\n`rectFromPoints` has two overloads: pass a literal non-empty tuple (`rectFromPoints([a, b])`) for a guaranteed `Rect`, or any `Iterable<Point>` for `Rect | null`.\n\n---\n\n## Frame Functions\n\nA frame places a local shape in world space: a position, an optional clockwise rotation (radians), and an optional scale pivoting around a world `origin`.\n\n```ts\nfunction frameMatrix(options: FrameOptions): Matrix;\nfunction boundsOfFrame(rect: Rect, matrix: Matrix): Rect;\nfunction resizeRect(rect: Rect, edges: ResizeEdges, point: Point, options?: ResizeOptions): Rect;\n```\n\n| Function | Description |\n| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `frameMatrix({ x, y, rotation?, scale?, origin? })` | Local→world matrix: `around(origin, rotate · scale) · translate(x, y)`; `origin` defaults to `{ x, y }`, `scale` is a number or `{ x?, y? }` |\n| `boundsOfFrame(rect, matrix)` | Axis-aligned world bounds: the AABB of the four transformed corners |\n| `resizeRect(rect, edges, point, { min?, aspect? })` | Resized rect dragging the edge(s) named by `edges` (`'e'`, `'w'`, `'n'`, `'s'`, or a corner like `'nw'`) to `point`; opposite edge(s) stay fixed |\n\n`frameMatrix` composes the matrix helpers for the common positioned-shape case, so `apply(frameMatrix({ rotation, scale, x, y }), localPoint)` places a shape's local coordinates in the world. `boundsOfFrame` pairs with it for culling and selection: rotation grows the AABB, which is what a spatial index needs.\n\n`resizeRect` is the resize-handle math for editors. `min` (default 0) keeps the result from collapsing on either axis. `aspect` (width/height) locks the ratio: a corner drag derives the free axis from the axis that moved further, an edge drag grows the free dimension about its centre.\n\n```ts\nimport { boundsOfFrame, frameMatrix, resizeRect } from '@vielzeug/atlas';\n\nconst frame = frameMatrix({ rotation: Math.PI / 6, scale: 2, x: 100, y: 50 });\nboundsOfFrame({ height: 40, width: 100, x: 0, y: 0 }, frame); // world AABB\nresizeRect(selection, 'se', worldPointer, { min: 4 }); // drag the bottom-right corner\n```\n\nAll three throw `AtlasConfigError` on non-finite inputs; `resizeRect` also throws for unknown `edges`, a negative `min`, or a non-positive `aspect`.\n\n---\n\n## Geometry Functions\n\n| Function | Description |\n| --------------------------------------------- | --------------------------------------------------------------------------- |\n| `pointInPolygon(polygon, point)` | Even-odd ray-cast containment |\n| `distanceToPolyline(path, point)` | Distance to the nearest segment; `Infinity` for empty paths |\n| `pointNearPolygon(polygon, point, tolerance)` | Inside the polygon OR within `tolerance` of its outline; throws on negative |\n\n---\n\n## Snapping Functions\n\n| Function | Description |\n| ------------------------------ | ---------------------------------------------------------------------------------------------- |\n| `snapRect(rect, options)` | Snapped `{ delta, guides }` against candidate rects, grid lines, and equal gaps |\n| `alignRects(rects, edge)` | Copies aligned to a shared `left`/`horizontal-center`/`right`/`top`/`vertical-center`/`bottom` |\n| `distributeRects(rects, axis)` | Copies with equalized gaps along `'x'` or `'y'` |\n\n`snapRect` options: `candidates` (rects to snap to; the moving rect itself must not be included), `grid` (`{ x?, y? }` line spacing), `spacing` (enable equal-gap centering, default `false`), `threshold` (max snap distance; throws `AtlasConfigError` when negative). Each axis resolves independently to its nearest target within `threshold` (inclusive) among candidate anchors (left/center/right, top/center/bottom) and grid lines; the guide's `kind` reports which one engaged. When no target engaged on an axis, `spacing: true` centers the rect between its nearest neighbors when the two gaps can be made equal within `threshold`. A candidate counts as a neighbor only when it overlaps the moving rect on the perpendicular axis, and both sides need one.\n\nA `SnapGuide` is `{ axis, kind, position, from, to, marks? }`: `axis` is the axis the guide line is perpendicular to, `kind` is `'grid'`, `'object'`, or `'spacing'` (what the snap engaged, for dashed vs solid rendering), `position` is the world coordinate of the line, and `from`/`to` span the line along the other axis. Spacing guides sit at the position the rect actually occupies after both axes snapped, and carry `marks`: the centers of the two equal gaps, to draw as × markers. `alignRects` and `distributeRects` are pure; distribution keeps the outermost rects fixed and returns input copies unchanged for fewer than three rects.\n\n---\n\n## Grid Functions\n\nFrom the `@vielzeug/atlas/grid` subpath:\n\n| Function | Returns |\n| -------------------------------------- | ----------------------------------------------------------------------------------------------- |\n| `worldToTile(point, grid)` | `TileCoord` (`{ col, row }`) containing the point (floor division) |\n| `tileToRect(coord, grid)` | World `Rect` of the tile |\n| `tileCenter(coord, grid)` | World `Point` at the tile's centre |\n| `visibleTileRange(view, grid)` | `TileRange` (`minCol/maxCol/minRow/maxRow`) intersecting a world rect |\n| `iterateTileRange(range)` | Generator over every `TileCoord` in a range |\n| `tileKey(coord)` | Stable `\"col:row\"` string |\n| `computeFov(origin, radius, options?)` | `Set<string>` of visible `tileKey`s (8-octant recursive shadowcasting) |\n| `createFog()` | Three-state fog tracker over tile keys: `update`/`state`/`visible`, `exportState`/`importState` |\n\n`grid` is `{ tileSize }` (positive; `worldToTile`/`tileToRect`/`tileCenter`/`visibleTileRange` throw `AtlasConfigError` otherwise, as does a negative/non-integer FOV `radius`). `computeFov` options: `blocks(coord)` returns true when sight cannot pass through the tile; blocking tiles within range are themselves visible. The origin is always in the result. `TileCoord` is `{ col, row }`. `createFog()` stores `tileKey` strings, so a `computeFov` result feeds `fog.update()` directly: one call demotes the previously visible tiles to `seen` and marks the new keys `visible`. `fog.visible` is a `ReadonlySet<string>`.\n\n---\n\n## Errors\n\n| Class | Thrown when |\n| ------------------ | ------------------------------------------------------------------------------- |\n| `AtlasError` | Base class; catch-all via `instanceof AtlasError` |\n| `AtlasConfigError` | Invalid options/clamps, negative snap or query tolerances, and bad frame inputs |\n",
|
|
6
|
+
"usage": "---\ntitle: 'Atlas: Usage Guide'\ndescription: Drive a camera, index shapes in an R-tree, and hit-test points, marquee rects, and polygons with Atlas.\n---\n\n[[toc]]\n\n## Basic Usage\n\nAtlas is headless: it never touches the DOM or a canvas. You feed it input events and scene rectangles, and it answers where things are.\n\n```ts\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\n// Camera: (x, y) is the world point shown at the viewport centre.\nconst camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });\ncamera.resize({ height: viewport.clientHeight, width: viewport.clientWidth });\n\n// Screen → world for input handling.\nconst world = camera.toWorld({ x: event.offsetX, y: event.offsetY });\n\n// World → screen for positioning DOM overlays.\nconst screen = camera.toScreen(shape.position);\n```\n\n## Coordinate Spaces\n\nAtlas works in three spaces and never guesses between them:\n\n- **Client space**: `PointerEvent.clientX/Y`. Subtract the viewport's `getBoundingClientRect()` offset before handing coordinates to the camera.\n- **Screen space**: CSS pixels from the viewport element's top-left. `toWorld()` and `zoomAt()` take screen points. The camera learns this size through `resize()` — a `ResizeObserver` on the viewport element is the usual source.\n- **World space**: your scene coordinates. `camera.matrix` maps world → screen; `zoom` is screen pixels per world unit.\n\nPositive `rotation` is clockwise on screen (y grows downward) and is kept normalized to `(-π, π]`. `camera.matrix` uses Canvas2D element order `[a, b, c, d, e, f]`, so you can hand it straight to `ctx.setTransform()` (multiply by DPR first) or hand it to `toCssMatrix()` for DOM overlays. The getter is a cached composite recomputed only when the camera changes.\n\n## Zooming to the Cursor\n\n`zoomAt()` keeps the world point under a screen point fixed while the zoom changes — the standard infinite-canvas feel:\n\n```ts\nwheelElement.addEventListener('wheel', (event) => {\n const factor = Math.exp(-event.deltaY * 0.0015);\n camera.zoomAt({ x: event.offsetX, y: event.offsetY }, factor);\n});\n```\n\n`rotateAt()` does the same for rotation. Both clamp against `minZoom`/`maxZoom` and still hold the anchor exactly at the clamp.\n\n## Panning and Fitting\n\n`panBy(dx, dy)` takes a screen-space delta; content follows the drag. `fitBounds()` frames a world rect inside the current viewport with optional padding, preserving the current rotation:\n\n```ts\ncamera.panBy(event.movementX, event.movementY);\ncamera.fitBounds(selectionBounds, { padding: 48 });\n```\n\nBecause `state.x`/`state.y` is the world point at the viewport centre, a saved camera state re-frames the same view on any screen size, and a zoom-only `animateTo({ zoom })` keeps the view centred where the user is looking.\n\n## Animating the Camera\n\n`animateTo()` interpolates position linearly and zoom in log space (multiplicative zoom feels linear to the eye). Rotation takes the shortest angular path. Pass an injectable scheduler to drive animations from your render loop or tests:\n\n```ts\ncamera.animateTo(\n { x: 250, y: 100, zoom: 2 },\n {\n duration: 300,\n signal: controller.signal, // abort mid-flight; the animation stops where it is\n },\n);\n```\n\n## Indexing the Scene\n\n`createSpatialIndex()` is a dynamic R-tree keyed by ids. Index every shape by its world-space bounding box, then answer three questions fast: what is under this point, what does this marquee rect touch, and what is inside the viewport:\n\n```ts\nconst index = createSpatialIndex(); // keys default to string\n\nindex.set(shape.id, shape.bounds); // insert, and again after every move\nindex.delete(shape.id); // on delete\n\n// Viewport culling each frame.\nconst visibleIds = index.queryRect(camera.visibleRect);\n\n// Marquee selection — the index returns ids; your own Map holds the data.\nconst selected = index.queryRect(marquee).map((id) => shapes.get(id));\n\n// Hover: tolerance widens the point into a box for fat-finger targets.\nconst hovered = index.queryPoint(worldPoint, { tolerance: 4 / camera.state.zoom });\n```\n\nThe index stores only ids and rects, so it can never hand back a stale copy of your data — call `set()` with the new rect after each committed move. Queries use closed intervals: touching edges count, and zero-area rects (lines, points) are findable. The R-tree is broad-phase only: it answers \"bounding boxes overlap or touch\". For exact hits on polygonal shapes, follow up with the narrow-phase helpers below.\n\n## Exact Hit-Testing\n\n```ts\nimport { pointNearPolygon, pointInPolygon } from '@vielzeug/atlas';\n\npointInPolygon(polygon, worldPoint); // even-odd ray cast\npointNearPolygon(polygon, worldPoint, 2); // inside OR within 2 units of the outline\n```\n\nBuild the polygon from the shape's actual corners (rotate each point yourself with `apply()` if needed) and index its axis-aligned hull in the R-tree. `pointNearPolygon` is what a vector tool needs to hit-test a stroked (unfilled) shape: the outline band plus the interior both count.\n\n## Snapping and Alignment\n\nWhile a shape moves, one `snapRect()` call snaps it to nearby shapes, grid lines, and equal gaps, and returns the guides to draw on an overlay:\n\n```ts\nimport { snapRect } from '@vielzeug/atlas';\n\nconst snap = snapRect(dragRect, {\n candidates: otherSelectedOutRects,\n grid: { x: 50, y: 50 },\n spacing: true, // opt into equal-gap spacing between neighbors\n threshold: 8,\n});\nconst snapped = { ...dragRect, x: dragRect.x + snap.delta.x, y: dragRect.y + snap.delta.y };\n// snap.guides: [{ axis, kind, position, from, to, marks? }] in world coordinates — draw them through the camera.\n```\n\nEach axis resolves independently to its nearest target within `threshold` among candidate anchors (left/center/right, top/center/bottom) and grid lines; the guide's `kind` says which one engaged. With `spacing: true`, an axis that found no target at all falls back to img.ly-style equal-gap centering: the rect centers itself between its nearest neighbors when the two gaps can be made equal within `threshold`. A candidate only counts as a neighbor when it overlaps the moving rect on the perpendicular axis, and both sides need one, so a lone shape never spacing-snaps.\n\nEvery guide carries `kind: 'grid' | 'object' | 'spacing'` so you can style them apart (dashed for grid, solid for objects, × marks at `marks` for spacing). `axis` is the axis the line is perpendicular to: an `axis: 'x'` guide is a vertical line at `position`, running from `from` to `to`. Spacing guides sit at the position the rect actually occupies after both axes snapped, so the marker lines up with the shape. On drop, commit `snapped` to your model so undo history records the final position, not the raw pointer position.\n\nAfter a multi-select, align or distribute with the pure helpers and record one command:\n\n```ts\nimport { alignRects, distributeRects } from '@vielzeug/atlas';\n\nconst aligned = alignRects(selectedRects, 'horizontal-center'); // copies, same order\nconst spread = distributeRects(selectedRects, 'x'); // equal gaps, outermost fixed\n```\n\n## Matrix Helpers\n\nFor custom transforms, the matrix functions use Canvas2D order and compose left-to-right like `ctx.transform()`:\n\n```ts\nimport {\n apply,\n around,\n IDENTITY,\n invert,\n multiply,\n rotate,\n scale,\n scaleOf,\n toCssMatrix,\n translate,\n} from '@vielzeug/atlas';\n\nconst transform = multiply(multiply(scale(2), rotate(Math.PI / 4)), translate(10, 5));\napply(transform, { x: 1, y: 0 }); // transformed point\ninvert(transform); // null for degenerate matrices\naround({ x: 100, y: 100 }, scale(2)); // scale about a point, not the origin\nscaleOf(transform); // average axis scale\ntoCssMatrix(transform); // 'matrix(...)' for CSS transforms\n```\n\n## Frames and Resizing\n\nShapes on a board are placed with a position, an optional rotation, and an optional scale. `frameMatrix()` composes that into one local→world matrix, and `boundsOfFrame()` turns a local rect into the world AABB your spatial index and selection queries need:\n\n```ts\nimport { apply, boundsOfFrame, frameMatrix } from '@vielzeug/atlas';\n\nconst frame = frameMatrix({ rotation: Math.PI / 6, scale: 2, x: 100, y: 50 });\nconst world = apply(frame, localPoint); // local → world\nconst aabb = boundsOfFrame(localRect, frame); // world AABB, ready for index.set()\n```\n\n`origin` pivots rotation and scale around a world point; it defaults to `{ x, y }`, which makes rotation and scale pure post-transforms of the placement. `toCssMatrix(frame)` feeds the same transform straight to a DOM overlay.\n\nResize handles are the other half of editor math. `resizeRect()` takes the dragged handle's direction (`'e'`, `'nw'`, …), the pointer's world position, and keeps the opposite edge(s) fixed:\n\n```ts\nimport { resizeRect } from '@vielzeug/atlas';\n\n// Dragging the bottom-right handle; shapes never collapse below 4 units.\nconst next = resizeRect(selection, 'se', worldPointer, { min: 4 });\n// Shift-drag convention: lock the selection's current ratio.\nconst square = resizeRect(selection, 'se', worldPointer, {\n aspect: selection.width / selection.height,\n min: 4,\n});\n```\n\nOn a corner drag with `aspect` set, the axis the pointer moved further along drives the other, so the drag feels direct from either side. Commit the returned rect to your model on pointer-up, the same way you commit a snapped move.\n\n## Tile Grids\n\nTile and map editors live on a square grid. The `@vielzeug/atlas/grid` subpath converts between world coordinates and tile coordinates, and enumerates only the tiles a viewport can see:\n\n```ts\nimport { iterateTileRange, tileCenter, tileKey, tileToRect, visibleTileRange, worldToTile } from '@vielzeug/atlas/grid';\n\nconst grid = { tileSize: 32 };\n\nworldToTile({ x: 40, y: -1 }, grid); // { col: 1, row: -1 }\ntileToRect({ col: 1, row: -1 }, grid); // { x: 32, y: -32, width: 32, height: 32 }\ntileCenter({ col: 1, row: -1 }, grid); // { x: 48, y: -16 }\n\n// Render loop: iterate the tiles intersecting the camera's world rect.\nfor (const coord of iterateTileRange(visibleTileRange(camera.visibleRect, grid))) {\n drawTile(coord);\n}\n```\n\n`tileKey(coord)` yields the stable `\"col:row\"` string used by the FOV and fog APIs (and convenient as a `Map` key).\n\n## Field of View and Fog\n\n`computeFov()` runs recursive shadowcasting over the eight octants and returns the set of `tileKey` strings a viewer can see within a radius. Blocking tiles are visible but cast shadows behind themselves:\n\n```ts\nimport { computeFov, createFog } from '@vielzeug/atlas/grid';\n\nconst fov = computeFov({ col: 10, row: 8 }, 6, { blocks: (c) => walls.has(`${c.col}:${c.row}`) });\n\nconst fog = createFog();\nfog.update(fov); // demotes the previous frame's visible tiles to 'seen'\nfog.state(tileKey({ col: 10, row: 8 })); // 'visible' | 'seen' | 'unseen'\nsaveGame(fog.exportState()); // serializable { seen, visible } key lists\n```\n\n`computeFov()` is pure and costs O(radius²) worst case; walls prune the walk. `createFog()` owns the three-state bookkeeping (`unseen` → `visible` → `seen`) over `tileKey` strings and round-trips through `exportState()`/`importState()` for save files. One `update(visibleKeys)` call per frame replaces the whole visible set — demote-then-reveal ordering is handled for you — and `fog.visible` is a `ReadonlySet<string>` of the current keys.\n\n## Best Practices\n\n- Subtract the viewport rect once at the input boundary; never mix client and screen coordinates inside camera calls.\n- Call `camera.resize()` from a `ResizeObserver` on the viewport element; the camera cannot anchor zooms to the centre without knowing its size.\n- Call `index.set(id, rect)` after every committed move — stale bounds silently break marquee and culling queries.\n- Use `camera.visibleRect` (the world AABB of the rotated viewport) for culling; it is conservative by design, so no visible shape is ever dropped.\n- Snap against the pre-move rect each pointer move (not the last snapped rect) so the delta stays relative to the raw pointer and snapping never drifts cumulatively.\n- Dispose the camera when the editor unmounts; disposal aborts in-flight animations and turns every mutating method into a no-op. The spatial index owns no resources, so it needs no disposal.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Atlas: Examples'\ndescription: Practical examples and recipes for @vielzeug/atlas.\n---\n\n## Examples\n\n- [Pan, Zoom and Culling](./examples/pan-zoom-and-culling.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
@@ -12,6 +12,11 @@
|
|
|
12
12
|
"code": "import { createCamera, createSpatialIndex } from '@vielzeug/atlas'\n\n// A small scene of world-space rects, indexed by id for hit-testing.\nconst index = createSpatialIndex()\nconst colors = new Map()\nconst palette = ['#38bdf8', '#a78bfa', '#f472b6', '#34d399', '#fbbf24']\nfor (let i = 0; i < 40; i++) {\n const x = (i % 8) * 90 - 320\n const y = Math.floor(i / 8) * 70 - 140\n index.set('r' + i, { x, y, width: 60, height: 44 })\n colors.set('r' + i, palette[i % palette.length])\n}\n\n// Camera state is the world point at the viewport centre (the SVG is 480x300).\nconst camera = createCamera({ minZoom: 0.2, maxZoom: 8, viewport: { width: 480, height: 300 } })\ncamera.fitBounds({ x: -320, y: -140, width: 700, height: 420 }, { padding: 20 })\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '0 0 480 300')\nsvg.style.cssText = 'width:100%;max-width:560px;background:#0f172a;border-radius:12px;touch-action:none;cursor:grab'\ndocument.body.appendChild(svg)\n\nfunction render() {\n svg.replaceChildren()\n for (const id of index.queryRect(camera.visibleRect)) {\n const r = index.get(id)\n const p = camera.toScreen({ x: r.x, y: r.y })\n const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')\n rect.setAttribute('x', String(p.x))\n rect.setAttribute('y', String(p.y))\n rect.setAttribute('width', String(r.width * camera.state.zoom))\n rect.setAttribute('height', String(r.height * camera.state.zoom))\n rect.setAttribute('rx', '6')\n rect.setAttribute('fill', colors.get(id))\n svg.appendChild(rect)\n }\n}\nrender()\n\n// Wheel zoom anchored at the cursor.\nsvg.addEventListener('wheel', (event) => {\n event.preventDefault()\n const box = svg.getBoundingClientRect()\n const sx = (event.clientX - box.left) * (480 / box.width)\n const sy = (event.clientY - box.top) * (300 / box.height)\n camera.zoomAt({ x: sx, y: sy }, Math.exp(-event.deltaY * 0.0015))\n render()\n}, { passive: false })\n\n// Drag to pan; double-click fits the whole scene again.\nlet dragging = false\nsvg.addEventListener('pointerdown', (event) => {\n dragging = true\n svg.setPointerCapture(event.pointerId)\n svg.style.cursor = 'grabbing'\n})\nsvg.addEventListener('pointermove', (event) => {\n if (dragging) { camera.panBy(event.movementX, event.movementY); render() }\n})\nsvg.addEventListener('pointerup', () => { dragging = false; svg.style.cursor = 'grab' })\nsvg.addEventListener('dblclick', () => {\n camera.animateTo({ x: 0, y: 0, zoom: 1, rotation: 0 }, { duration: 400 })\n})\n\nconsole.log('visible rects:', index.queryRect(camera.visibleRect).length)",
|
|
13
13
|
"name": "createCamera - Pan, zoom and culling"
|
|
14
14
|
},
|
|
15
|
+
{
|
|
16
|
+
"id": "atlas-frames",
|
|
17
|
+
"code": "import { apply, boundsOfFrame, frameMatrix, resizeRect, toCssMatrix } from '@vielzeug/atlas'\n\n// One shape: a local rect placed by a frame matrix, resized by its handles.\nlet rect = { x: -90, y: -50, width: 180, height: 100 }\nconst rotation = Math.PI / 10\nconst frame = frameMatrix({ rotation, x: 0, y: 0 })\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '-240 -160 480 320')\nsvg.style.cssText = 'width:100%;max-width:560px;background:#0f172a;border-radius:12px;touch-action:none'\ndocument.body.appendChild(svg)\n\nconst ns = 'http://www.w3.org/2000/svg'\nfunction render() {\n svg.replaceChildren()\n const aabb = boundsOfFrame(rect, frame)\n const box = document.createElementNS(ns, 'rect')\n box.setAttribute('x', String(aabb.x)); box.setAttribute('y', String(aabb.y))\n box.setAttribute('width', String(aabb.width)); box.setAttribute('height', String(aabb.height))\n box.setAttribute('fill', 'none'); box.setAttribute('stroke', '#64748b'); box.setAttribute('stroke-dasharray', '4 4')\n svg.appendChild(box)\n const shape = document.createElementNS(ns, 'rect')\n shape.setAttribute('x', String(rect.x)); shape.setAttribute('y', String(rect.y))\n shape.setAttribute('width', String(rect.width)); shape.setAttribute('height', String(rect.height))\n shape.setAttribute('rx', '8'); shape.setAttribute('fill', '#38bdf8')\n shape.setAttribute('transform', toCssMatrix(frame))\n svg.appendChild(shape)\n // Handles sit on the rotated corners, and drag in world space.\n const corners = [\n { dir: 'nw', x: rect.x, y: rect.y },\n { dir: 'ne', x: rect.x + rect.width, y: rect.y },\n { dir: 'sw', x: rect.x, y: rect.y + rect.height },\n { dir: 'se', x: rect.x + rect.width, y: rect.y + rect.height },\n ]\n for (const c of corners) {\n const p = apply(frame, { x: c.x, y: c.y })\n const h = document.createElementNS(ns, 'rect')\n h.setAttribute('x', String(p.x - 5)); h.setAttribute('y', String(p.y - 5))\n h.setAttribute('width', '10'); h.setAttribute('height', '10'); h.setAttribute('rx', '2')\n h.setAttribute('fill', '#fbbf24'); h.style.cursor = 'grab'\n h.dataset.dir = c.dir\n svg.appendChild(h)\n }\n}\nrender()\n\n// Drag a handle: resizeRect keeps the opposite corner fixed; Shift locks the ratio.\nlet drag = null\nsvg.addEventListener('pointerdown', (event) => {\n const dir = event.target instanceof Element ? event.target.dataset.dir : undefined\n if (!dir) return\n drag = dir\n svg.setPointerCapture(event.pointerId)\n})\nsvg.addEventListener('pointermove', (event) => {\n if (!drag) return\n const box = svg.getBoundingClientRect()\n const point = {\n x: (event.clientX - box.left) * (480 / box.width) - 240,\n y: (event.clientY - box.top) * (320 / box.height) - 160,\n }\n const aspect = event.shiftKey && rect.height > 0 ? rect.width / rect.height : undefined\n rect = resizeRect(rect, drag, point, { aspect, min: 20 })\n render()\n})\nsvg.addEventListener('pointerup', () => { drag = null })\n\nconsole.log('aabb:', JSON.stringify(boundsOfFrame(rect, frame)))",
|
|
18
|
+
"name": "frameMatrix + resizeRect - Rotated frame with resize handles"
|
|
19
|
+
},
|
|
15
20
|
{
|
|
16
21
|
"id": "atlas-snap",
|
|
17
22
|
"code": "import { alignRects, distributeRects, snapRect, type Rect } from '@vielzeug/atlas'\n\n// Drag a rect with the pointer; it snaps to nearby rects and a 50px grid.\nconst candidates: Rect[] = [\n { x: -120, y: -80, width: 80, height: 60 },\n { x: 40, y: 20, width: 100, height: 40 },\n { x: -30, y: 110, width: 60, height: 60 },\n]\nlet moving: Rect = { x: 150, y: -40, width: 90, height: 50 }\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '-200 -150 480 340')\nsvg.style.cssText = 'width:100%;max-width:560px;background:#0f172a;border-radius:12px;touch-action:none'\ndocument.body.appendChild(svg)\n\nfunction render(guides) {\n svg.replaceChildren()\n const ns = 'http://www.w3.org/2000/svg'\n for (const g of guides) {\n const line = document.createElementNS(ns, 'line')\n if (g.axis === 'x') {\n line.setAttribute('x1', String(g.position)); line.setAttribute('x2', String(g.position))\n line.setAttribute('y1', String(g.from)); line.setAttribute('y2', String(g.to))\n } else {\n line.setAttribute('y1', String(g.position)); line.setAttribute('y2', String(g.position))\n line.setAttribute('x1', String(g.from)); line.setAttribute('x2', String(g.to))\n }\n line.setAttribute('stroke', '#f472b6'); line.setAttribute('stroke-width', '1.5')\n svg.appendChild(line)\n }\n for (const r of [...candidates, moving]) {\n const rect = document.createElementNS(ns, 'rect')\n rect.setAttribute('x', String(r.x)); rect.setAttribute('y', String(r.y))\n rect.setAttribute('width', String(r.width)); rect.setAttribute('height', String(r.height))\n rect.setAttribute('rx', '6')\n rect.setAttribute('fill', r === moving ? '#38bdf8' : '#334155')\n svg.appendChild(rect)\n }\n}\nrender([])\n\nsvg.addEventListener('pointermove', (event) => {\n if (event.buttons !== 1) return\n const box = svg.getBoundingClientRect()\n const px = (event.clientX - box.left) * (480 / box.width) - 200\n const py = (event.clientY - box.top) * (340 / box.height) - 150\n const target = { ...moving, x: px - moving.width / 2, y: py - moving.height / 2 }\n const snap = snapRect(target, { candidates, grid: { x: 50, y: 50 }, threshold: 8 })\n moving = { ...target, x: target.x + snap.delta.x, y: target.y + snap.delta.y }\n render(snap.guides)\n})\n\n// Press A to align all rects to the top edge, D to distribute horizontally.\nwindow.addEventListener('keydown', (event) => {\n if (event.key === 'a') candidates.splice(0, candidates.length, ...alignRects(candidates, 'top'))\n if (event.key === 'd') candidates.splice(0, candidates.length, ...distributeRects(candidates, 'x'))\n render([])\n})",
|
|
@@ -27,6 +32,12 @@
|
|
|
27
32
|
"FrameScheduler": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
28
33
|
"AtlasConfigError": "export { AtlasConfigError, AtlasError } from './errors.js';",
|
|
29
34
|
"AtlasError": "export { AtlasConfigError, AtlasError } from './errors.js';",
|
|
35
|
+
"boundsOfFrame": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
36
|
+
"FrameOptions": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
37
|
+
"frameMatrix": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
38
|
+
"ResizeEdges": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
39
|
+
"ResizeOptions": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
40
|
+
"resizeRect": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
30
41
|
"distanceToPolyline": "export { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';",
|
|
31
42
|
"pointInPolygon": "export { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';",
|
|
32
43
|
"pointNearPolygon": "export { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';",
|
package/data/packages/ink.json
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
{
|
|
2
|
-
"apiSource": "/**\n * @vielzeug/ink: freehand stroke smoothing, width profiling, and SVG path output.\n *\n * Pure, deterministic geometry functions. No DOM, no timers, no long-lived handles.\n */\nexport { InkConfigError, InkError } from './errors.js';\nexport { strokeOutline } from './outline.js';\nexport { simplifyStroke } from './simplify.js';\nexport { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';\nexport { type StabilizeStrokeOptions, stabilizeStroke } from './stabilize.js';\nexport { type PolylineToSvgPathOptions, polylineToSvgPath } from './svg.js';\nexport type { Point, StrokePoint } from './types.js';\nexport { type StrokeWidthOptions, strokeWidths } from './widths.js';\n",
|
|
2
|
+
"apiSource": "/**\n * @vielzeug/ink: freehand stroke smoothing, width profiling, and SVG path output.\n *\n * Pure, deterministic geometry functions. No DOM, no timers, no long-lived handles.\n */\nexport { InkConfigError, InkError } from './errors.js';\nexport { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';\nexport { simplifyStroke } from './simplify.js';\nexport { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';\nexport { type StabilizeStrokeOptions, stabilizeStroke } from './stabilize.js';\nexport { type PolylineToSvgPathOptions, polylineToSvgPath } from './svg.js';\nexport type { Point, StrokePoint } from './types.js';\nexport { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';\n",
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: 'Ink: Freehand Stroke Geometry'\ndescription: Deterministic causal stroke stabilization, Catmull-Rom smoothing, speed and pressure width profiling, outline polygons, RDP simplification, and SVG path output.\npackage: ink\ncategory: data\nkeywords:\n [\n freehand,\n stroke,\n smoothing,\n catmull-rom,\n streamline,\n simplify,\n ramer-douglas-peucker,\n svg,\n path,\n variable-width,\n pressure,\n drawing,\n canvas,\n ]\nexports: [stabilizeStroke, smoothStroke, strokeWidths, strokeOutline, simplifyStroke, polylineToSvgPath]\nrelated: [gesture, prism]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"ink\" />\n\n## Why Ink?\n\nRaw pointer samples are jagged, and a good ink line needs stabilization, speed- and pressure-derived widths, a closed outline polygon, and a compact SVG path on top of them. Ink computes all four as pure, deterministic functions: identical samples always produce identical geometry, so strokes are replayable, testable, and server-renderable.\n\n```ts\n// Before\n// Hand-rolled filter math, per-point width heuristics, and manual path assembly\n// in every drawing surface, each with its own jitter and nondeterminism.\n\n// After\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';\n\nconst stabilized = stabilizeStroke(samples);\nconst d = polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 4 })), {\n close: true,\n});\n```\n\n| Feature | Ink | Ad-hoc smoothing | Sketch libraries |\n| ------------------------------ | -------------------------------------------- | ---------------- | -------------------- |\n| Bundle size | <PackageInfo package=\"ink\" type=\"size\" /> | n/a | Typically 10–50 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a | Varies |\n| Deterministic pure functions | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Rarely | Often randomized |\n| Variable-width outline polygon | Built in | Manual | Rare |\n| Runs without a DOM | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies | Usually browser-only |\n\n<div class=\"decision-callout\">\n\n**Use Ink when** a drawing or annotation surface needs reusable stroke geometry: stabilization, smoothing, width profiling, outlines, decimation, or SVG serialization without owning the math.\n\n**Consider direct polyline rendering when** the input is already clean (vector tools with their own smoothing) and a plain segment path is visually sufficient.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/ink\n```\n\n```sh [npm]\nnpm install @vielzeug/ink\n```\n\n```sh [yarn]\nyarn add @vielzeug/ink\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';\n\n// Raw samples from a pointer stream (see @vielzeug/gesture for capture),\n// timestamped with PointerEvent.timeStamp.\nconst samples = [\n { time: 0, x: 0, y: 0 },\n { time: 16, x: 12, y: 3 },\n { time: 32, x: 25, y: -2 },\n { time: 48, x: 40, y: 1 },\n];\n\nconst stabilized = stabilizeStroke(samples); // causal jitter removal\nconst widths = strokeWidths(stabilized, { width: 6 }); // speed-derived widths\nconst ring = strokeOutline(stabilized, widths); // closed variable-width polygon\nconst d = polylineToSvgPath(ring, { close: true }); // SVG `d` string\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `stabilizeStroke()`: causal Streamline-style averaging for live drawing; the stroke ends exactly where the pen lifted\n- `smoothStroke()`: deterministic Catmull-Rom resampling after capture\n- `strokeWidths()`: real-speed-derived widths (`distance / Δtime`) with pressure modulation and clamped scaling\n- `strokeOutline()`: closed variable-width polygon offset along local normals with capped ends; constant width with a single number\n- `simplifyStroke()`: iterative Ramer-Douglas-Peucker decimation preserving endpoints\n- `polylineToSvgPath()`: SVG `d` strings for open strokes and closed outline rings, with configurable precision\n- `InkError` / `InkConfigError`: typed configuration errors thrown at call time\n- Determinism: identical input always yields identical output; no randomness, no clocks\n- Zero runtime dependencies and no DOM requirement: works in Node, Workers, and SSR\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Gesture](/gesture/): captures the pointer samples Ink consumes; pan handles produce the raw point streams.\n- [Prism](/prism/): SVG rendering primitives; Ink's `d` strings drop straight into its path elements.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Ink: API Reference'\ndescription: 'API reference for @vielzeug/ink: causal stabilization, Catmull-Rom smoothing, speed-based widths, outline polygons, simplification, and SVG path output.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------- | -------------------------------------------------------- | --------- | ----------------------------------------------------------------- |\n| `stabilizeStroke()` | Causal jitter removal while drawing | Sync | One output point per input; last point snaps to the pen-up spot |\n| `smoothStroke()` | Catmull-Rom resampling after capture | Sync | Adds points: `steps` samples per input segment |\n| `strokeWidths()` | Per-point widths from real speed (`time`) and pressure | Sync | Velocity is off for the whole stroke if any point lacks `time` |\n| `strokeOutline()` | Closed variable-width polygon around a stroke | Sync | Array `widths` must match point count; a number is constant |\n| `simplifyStroke()` | Ramer-Douglas-Peucker decimation | Sync | Returns input references, not copies |\n| `polylineToSvgPath()` | SVG `d` string for polylines and closed outline rings | Sync | Requires at least one point; pass `close: true` for rings |\n| `InkError` | Base class for all ink errors | Sync | Narrow with `instanceof InkError` |\n| `InkConfigError` | Invalid options or point counts | Sync | Thrown at call time, not construction |\n| `Point` / `StrokePoint` | Structural point shapes shared across the canvas toolkit | Sync | `pressure` and `time` are optional; `time` unlocks width velocity |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------- | ---------------------------------------------------------------------------------------------------- |\n| `@vielzeug/ink` | Stabilization, smoothing, width profiling, outline, simplification, SVG serialization, types, errors |\n\n---\n\n## Core Functions\n\n### `stabilizeStroke()`\n\n```ts\nfunction stabilizeStroke(points: readonly StrokePoint[], options?: StabilizeStrokeOptions): StrokePoint[];\n```\n\nRemoves hand jitter _while the stroke is being drawn_: a causal exponential average toward each incoming sample with a jitter dead zone, so straight lines stay crisp. It never looks ahead.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | ----------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Input samples |\n| `options` | `StabilizeStrokeOptions` | `strength` in `[0, 1]`; `0` is the raw input, default `0.5` |\n\n**Returns:** New `StrokePoint[]` with exactly the input's length. The last point is the last input point exactly — the stroke ends where the pen lifted. Inside the dead zone the position repeats but the incoming sample's `pressure` and `time` carry through.\n\n**Example**\n\n```ts\nimport { stabilizeStroke } from '@vielzeug/ink';\n\nconst live = stabilizeStroke(samples, { strength: 0.6 });\n```\n\nThrows `InkConfigError` for a `strength` outside `[0, 1]`.\n\n---\n\n### `smoothStroke()`\n\n```ts\nfunction smoothStroke(points: readonly StrokePoint[], options?: SmoothStrokeOptions): StrokePoint[];\n```\n\nResamples a stroke through a uniform Catmull-Rom spline: `steps` samples per input segment, with the first and last input points preserved exactly. `pressure` and `time` are interpolated linearly, so widths computed from the output match widths computed from the input. For jitter removal while drawing, use `stabilizeStroke()` instead — this function adds points and looks ahead.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | ------------------------------------------------------------------------------ |\n| `points` | `readonly StrokePoint[]` | Input samples; fewer than three are returned as copies |\n| `options` | `SmoothStrokeOptions` | `tension` in `[0, 1]` (default `1`), `steps` integer `[2, 1000]` (default `8`) |\n\n**Returns:** New `StrokePoint[]` with `steps` samples per input segment plus the exact final point.\n\n**Example**\n\n```ts\nimport { smoothStroke } from '@vielzeug/ink';\n\nconst resampled = smoothStroke(samples, { tension: 1, steps: 8 });\n```\n\nThrows `InkConfigError` for a `tension` outside `[0, 1]` or a `steps` value outside `[2, 1000]` or non-integer.\n\n---\n\n### `strokeWidths()`\n\n```ts\nfunction strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[];\n```\n\nReturns one width per point from real pen speed and optional pressure. Speed is `distance / Δtime` between consecutive points, which stays correct after any stabilization, smoothing, or simplification. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale. When any point lacks `time` — or a Δtime is zero — velocity modulation is disabled for the whole stroke (width becomes `width × pressure`) instead of guessing speed from sample spacing.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | ---------------------------------------------------------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |\n| `options` | `StrokeWidthOptions` | `width` (required, > 0), `thinning` in `[0, 1]` (default `0.5`), `referenceSpeed` in px/ms (default `0.5`) |\n\n**Returns:** `number[]` with the same length as `points`. The first point uses the forward segment; degenerate (zero-length) segments keep the previous scale so stationary samples do not spike.\n\nPressure multiplies the result through a curve where `0.5` (the neutral value a mouse reports) maps to exactly `1`: the range is `[0.5, 1.25]`, so a neutral-pressure stroke is as wide as one without pressure data.\n\n**Example**\n\n```ts\nimport { strokeWidths } from '@vielzeug/ink';\n\nconst widths = strokeWidths(samples, { width: 6, thinning: 0.5 });\n```\n\nThrows `InkConfigError` for a non-positive `width` or `referenceSpeed`, a `thinning` outside `[0, 1]`, or an empty `points` array.\n\n---\n\n### `strokeOutline()`\n\n```ts\nfunction strokeOutline(points: readonly StrokePoint[], widths: number | readonly number[]): Point[];\n```\n\nReturns a closed polygon approximating the variable-width stroke: start cap, left offsets forward, end cap, right offsets backward, with no repeated final vertex. Pass a constant `widths` number for a uniform stroke.\n\n| Parameter | Type | Description |\n| --------- | ----------------------------- | --------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |\n| `widths` | `number \\| readonly number[]` | Constant width, or per-point widths from `strokeWidths()` |\n\n**Returns:** `Point[]` ring, deterministic for deterministic input.\n\n**Example**\n\n```ts\nimport { strokeOutline } from '@vielzeug/ink';\n\nconst ring = strokeOutline(samples, widths);\nconst uniform = strokeOutline(samples, 4);\n```\n\nThrows `InkConfigError` when an array `widths` length differs from `points` length or any width is not a positive finite number.\n\n---\n\n### `simplifyStroke()`\n\n```ts\nfunction simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[];\n```\n\nReturns a Ramer-Douglas-Peucker decimated subsequence of the input; first and last points are always kept.\n\n| Parameter | Type | Description |\n| ----------- | ------------------------ | -------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples |\n| `tolerance` | `number` | Maximum perpendicular deviation to discard, `>= 0` |\n\n**Returns:** `StrokePoint[]` containing the same object references as the input (metadata such as `pressure` and `time` survives).\n\n**Example**\n\n```ts\nimport { simplifyStroke } from '@vielzeug/ink';\n\nconst decimated = simplifyStroke(samples, 0.5);\n```\n\nThrows `InkConfigError` for a negative or non-finite `tolerance`.\n\n---\n\n### `polylineToSvgPath()`\n\n```ts\nfunction polylineToSvgPath(points: readonly Point[], options?: PolylineToSvgPathOptions): string;\n```\n\nReturns an SVG path `d` string: `M x y` plus one `L x y` per remaining point. Works for open strokes and for the closed ring from `strokeOutline()` — pass `close: true` for rings.\n\n| Parameter | Type | Description |\n| --------- | -------------------------- | --------------------------------------------------------------------------- |\n| `points` | `readonly Point[]` | Stroke samples or ring vertices (at least one) |\n| `options` | `PolylineToSvgPathOptions` | `close` appends `Z`; `precision` rounds coordinates (`0`–`12`, default `2`) |\n\n**Returns:** `string` suitable for a `<path d=\"...\">` attribute.\n\n**Example**\n\n```ts\nimport { polylineToSvgPath } from '@vielzeug/ink';\n\nconst d = polylineToSvgPath(samples, { precision: 1 }); // \"M 0 0 L 12 3 L 25 -2\"\nconst outline = polylineToSvgPath(ring, { close: true }); // \"M ... L ... Z\"\n```\n\nThrows `InkConfigError` when `points` is empty or `precision` is out of range.\n\n## Types\n\n```ts\ntype Point = Readonly<{ x: number; y: number }>;\n```\n\nA two-dimensional point. Structural so canvas-toolkit packages can share it without importing each other.\n\n```ts\ntype StrokePoint = Readonly<{\n x: number;\n y: number;\n pressure?: number; // normalized [0, 1]; 0.5 is neutral\n time?: number; // milliseconds, e.g. PointerEvent.timeStamp; enables width velocity\n}>;\n```\n\nA sampled stroke point. `time` values only need to share a clock; any monotonic source works.\n\n```ts\ninterface StabilizeStrokeOptions {\n strength?: number; // [0, 1], default 0.5\n}\n```\n\n```ts\ninterface SmoothStrokeOptions {\n tension?: number; // [0, 1], default 1\n steps?: number; // [2, 1000] integer, default 8\n}\n```\n\n```ts\ninterface StrokeWidthOptions {\n width: number; // required, > 0\n thinning?: number; // [0, 1], default 0.5\n referenceSpeed?: number; // > 0, default 0.5 (px per ms)\n}\n```\n\n```ts\ninterface PolylineToSvgPathOptions {\n close?: boolean; // default false\n precision?: number; // [0, 12] integer, default 2\n}\n```\n\n## Errors\n\n| Error | Trigger |\n| ---------------- | -------------------------------------------------------------------------------------------------------------- |\n| `InkError` | Base class; catch all ink errors with `instanceof InkError` |\n| `InkConfigError` | Invalid options (strength, tension, steps, width, thinning, precision, tolerance, …) or point-count mismatches |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Ink: Usage Guide'\ndescription: 'How to smooth freehand strokes with @vielzeug/ink: stabilization, smoothing, speed-based widths, outline polygons, and SVG paths.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nCapture samples from any pointer source — with a timestamp — then run them through the pipeline: stabilize while drawing, simplify, width, outline, serialize. Every function is pure, so you can call them in any order and re-run them freely.\n\n```ts\nimport {\n polylineToSvgPath,\n simplifyStroke,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n} from '@vielzeug/ink';\n\n// Capture: PointerEvent.timeStamp is the timestamp ink wants.\nconst samples: StrokePoint[] = [];\nelement.addEventListener('pointermove', (event) => {\n samples.push({ pressure: event.pressure, time: event.timeStamp, x: event.offsetX, y: event.offsetY });\n});\n\nconst stabilized = stabilizeStroke(samples);\nconst widths = strokeWidths(stabilized, { width: 6 });\nconst d = polylineToSvgPath(strokeOutline(stabilized, widths), { close: true });\n\n// Render with any SVG-capable surface.\nconst path = document.createElementNS('http://www.w3.org/2000/svg', 'path');\npath.setAttribute('d', d);\n```\n\n## Stabilize While Drawing\n\n`stabilizeStroke()` removes hand jitter causally — it never looks ahead — so you can run it on every pointer move while the stroke is being drawn. It emits exactly one point per input sample, keeping per-sample metadata aligned, and its last point is always the last input point: the stroke ends exactly where the pen lifted.\n\n```ts\nimport { stabilizeStroke } from '@vielzeug/ink';\n\nconst live = stabilizeStroke(samples, { strength: 0.5 }); // 0 = raw, 1 = maximum smoothing\n```\n\n## Smooth After Capture\n\n`smoothStroke()` resamples the stroke through a uniform Catmull-Rom spline: each input segment becomes `steps` samples, and the first and last input points are preserved exactly. Use it after capture when you want extra curvature between sparse samples. `pressure` and `time` are interpolated linearly, so widths computed from the output match widths computed from the input.\n\n```ts\nimport { smoothStroke } from '@vielzeug/ink';\n\nconst resampled = smoothStroke(samples, { tension: 1, steps: 8 });\n```\n\n## Profile Widths From Speed and Pressure\n\n`strokeWidths()` derives real pen speed from the `time` field: `distance / Δtime` between consecutive points. That stays correct after any stabilization, smoothing, or simplification — pipeline order no longer matters. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n\n```ts\nimport { strokeWidths } from '@vielzeug/ink';\n\nconst widths = strokeWidths(stabilized, {\n width: 6,\n thinning: 0.5, // 0 disables velocity, 1 is fully inverse-proportional\n referenceSpeed: 0.5, // neutral pen speed in pixels per millisecond\n});\n```\n\nWhen points carry `pressure` (normalized `[0, 1]`), it multiplies the result: `0.5` is neutral and maps to exactly `1`, so a mouse (which reports `0.5`) draws as wide as a device without pressure data. When any point lacks `time`, velocity modulation is disabled for the whole stroke — width becomes `width × pressure` — instead of guessing speed from sample spacing.\n\n## Build the Outline\n\n`strokeOutline()` offsets each sample by half its width along the local normal and closes the ring with half-circle caps at both ends. The result is a plain `Point[]` you can fill with any renderer.\n\n```ts\nimport { strokeOutline } from '@vielzeug/ink';\n\nconst ring = strokeOutline(stabilized, widths); // variable width, closed polygon\nconst uniform = strokeOutline(stabilized, 6); // constant width, no array needed\n```\n\n## Simplify Before Serializing\n\nLong strokes accumulate samples. `simplifyStroke()` runs Ramer-Douglas-Peucker and returns a subsequence of the input, so object identity, `pressure`, and `time` survive. Apply it to the outline before emitting SVG to shrink path data.\n\n```ts\nimport { simplifyStroke, polylineToSvgPath } from '@vielzeug/ink';\n\nconst compact = polylineToSvgPath(simplifyStroke(ring, 0.25), { close: true });\n```\n\n## Serialize to SVG Paths\n\n`polylineToSvgPath()` writes `M` plus one `L` per point, rounding coordinates to `precision` decimal places. Pass `close: true` to append `Z` for the closed outline ring; leave it off for a centerline path.\n\n```ts\nimport { polylineToSvgPath } from '@vielzeug/ink';\n\nconst centerline = polylineToSvgPath(simplifyStroke(stabilized, 0.5), { precision: 1 });\nconst outline = polylineToSvgPath(ring, { close: true });\n```\n\n## Framework Integration\n\nInk functions are pure, so they memoize cleanly. Recompute geometry only when the sample array changes.\n\n::: code-group\n\n```tsx [React]\nimport { useMemo } from 'react';\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths, type StrokePoint } from '@vielzeug/ink';\n\nfunction InkPath({ samples }: { samples: StrokePoint[] }) {\n const d = useMemo(() => {\n const stabilized = stabilizeStroke(samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n }, [samples]);\n\n return <path d={d} />;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { computed } from 'vue';\nimport {\n polylineToSvgPath,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n} from '@vielzeug/ink';\n\nconst props = defineProps<{ samples: StrokePoint[] }>();\nconst d = computed(() => {\n const stabilized = stabilizeStroke(props.samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n});\n</script>\n\n<template>\n <svg><path :d=\"d\" /></svg>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import {\n polylineToSvgPath,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n } from '@vielzeug/ink';\n\n export let samples: StrokePoint[];\n $: d = (() => {\n const stabilized = stabilizeStroke(samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n })();\n</script>\n\n<svg><path {d} /></svg>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nGesture produces the raw samples: bind a pan or drag handle, append each `current` point (with `event.timeStamp`) to an array, and pass the array to Ink when the stroke ends. Prism (or any SVG renderer) consumes the `d` strings Ink returns.\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\nimport { polylineToSvgPath, stabilizeStroke, type StrokePoint } from '@vielzeug/ink';\n\nconst samples: StrokePoint[] = [];\nconst drag = createDragGesture(surface, {\n onMove: ({ currentX, currentY, event }) => samples.push({ time: event.timeStamp, x: currentX, y: currentY }),\n onEnd: () => {\n path.setAttribute('d', polylineToSvgPath(stabilizeStroke(samples), { precision: 1 }));\n },\n});\n```\n\n## Best Practices\n\n- Pass `time` on every sample (`PointerEvent.timeStamp` or `performance.now()`): without it, widths are pressure-only and speed information is thrown away.\n- Stabilize live, smooth once: run `stabilizeStroke()` per pointer move for a calm preview, and add `smoothStroke()` or `simplifyStroke()` at commit time.\n- Simplify outlines with a tolerance around `0.2`–`0.5` device pixels; larger tolerances visibly flatten caps.\n- Keep `precision` at `1`–`2` for display paths; raise it only when another tool re-processes the output.\n- Treat invalid options errors (`InkConfigError`) as programming bugs: they throw at call time with the offending option named.\n- Memoize per stroke in UI frameworks; the functions are pure and cheap to cache.\n",
|
|
5
|
+
"api": "---\ntitle: 'Ink: API Reference'\ndescription: 'API reference for @vielzeug/ink: causal stabilization, Catmull-Rom smoothing, speed-based widths, outline polygons, simplification, and SVG path output.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------- | -------------------------------------------------------- | --------- | ----------------------------------------------------------------- |\n| `stabilizeStroke()` | Causal jitter removal while drawing | Sync | One output point per input; last point snaps to the pen-up spot |\n| `smoothStroke()` | Catmull-Rom resampling after capture | Sync | Adds points: `steps` samples per input segment |\n| `strokeWidths()` | Per-point widths from real speed (`time`) and pressure | Sync | Velocity is off for the whole stroke if any point lacks `time` |\n| `strokeOutline()` | Closed variable-width polygon around a stroke | Sync | Array `widths` must match point count; a number is constant |\n| `simplifyStroke()` | Ramer-Douglas-Peucker decimation | Sync | Returns input references, not copies |\n| `polylineToSvgPath()` | SVG `d` string for polylines and closed outline rings | Sync | Requires at least one point; pass `close: true` for rings |\n| `InkError` | Base class for all ink errors | Sync | Narrow with `instanceof InkError` |\n| `InkConfigError` | Invalid options or point counts | Sync | Thrown at call time, not construction |\n| `Point` / `StrokePoint` | Structural point shapes shared across the canvas toolkit | Sync | `pressure` and `time` are optional; `time` unlocks width velocity |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------- | ---------------------------------------------------------------------------------------------------- |\n| `@vielzeug/ink` | Stabilization, smoothing, width profiling, outline, simplification, SVG serialization, types, errors |\n\n---\n\n## Core Functions\n\n### `stabilizeStroke()`\n\n```ts\nfunction stabilizeStroke(points: readonly StrokePoint[], options?: StabilizeStrokeOptions): StrokePoint[];\n```\n\nRemoves hand jitter _while the stroke is being drawn_: a causal exponential average toward each incoming sample with a jitter dead zone, so straight lines stay crisp. It never looks ahead.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | ----------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Input samples |\n| `options` | `StabilizeStrokeOptions` | `strength` in `[0, 1]`; `0` is the raw input, default `0.5` |\n\n**Returns:** New `StrokePoint[]` with exactly the input's length. The last point is the last input point exactly — the stroke ends where the pen lifted. Inside the dead zone the position repeats but the incoming sample's `pressure` and `time` carry through.\n\n**Example**\n\n```ts\nimport { stabilizeStroke } from '@vielzeug/ink';\n\nconst live = stabilizeStroke(samples, { strength: 0.6 });\n```\n\nThrows `InkConfigError` for a `strength` outside `[0, 1]`.\n\n---\n\n### `smoothStroke()`\n\n```ts\nfunction smoothStroke(points: readonly StrokePoint[], options?: SmoothStrokeOptions): StrokePoint[];\n```\n\nResamples a stroke through a uniform Catmull-Rom spline: `steps` samples per input segment, with the first and last input points preserved exactly. `pressure` and `time` are interpolated linearly, so widths computed from the output match widths computed from the input. For jitter removal while drawing, use `stabilizeStroke()` instead — this function adds points and looks ahead.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | ------------------------------------------------------------------------------ |\n| `points` | `readonly StrokePoint[]` | Input samples; fewer than three are returned as copies |\n| `options` | `SmoothStrokeOptions` | `tension` in `[0, 1]` (default `1`), `steps` integer `[2, 1000]` (default `8`) |\n\n**Returns:** New `StrokePoint[]` with `steps` samples per input segment plus the exact final point.\n\n**Example**\n\n```ts\nimport { smoothStroke } from '@vielzeug/ink';\n\nconst resampled = smoothStroke(samples, { tension: 1, steps: 8 });\n```\n\nThrows `InkConfigError` for a `tension` outside `[0, 1]` or a `steps` value outside `[2, 1000]` or non-integer.\n\n---\n\n### `strokeWidths()`\n\n```ts\nfunction strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[];\n```\n\nReturns one width per point from real pen speed and optional pressure. Speed is `distance / Δtime` between consecutive points, which stays correct after any stabilization, smoothing, or simplification. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale. When any point lacks `time` — or a Δtime is zero — velocity modulation is disabled for the whole stroke (width becomes `width × pressure`) instead of guessing speed from sample spacing.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |\n| `options` | `StrokeWidthOptions` | `width` (required, > 0), `thinning` in `[0, 1]` (default `0.5`), `referenceSpeed` in px/ms (default `0.5`), `taper`, `simulatePressure` |\n\n**Returns:** `number[]` with the same length as `points`. The first point uses the forward segment; degenerate (zero-length) segments keep the previous scale so stationary samples do not spike.\n\nPressure multiplies the result through a curve where `0.5` (the neutral value a mouse reports) maps to exactly `1`: the range is `[0.5, 1.25]`, so a neutral-pressure stroke is as wide as one without pressure data.\n\n`taper` fades the width in over `taper.start` and out over `taper.end` units of arc length (same units as `width`): a smoothstep ramp from a `0.15` floor at the tip to full width at the taper length, multiplied on top of the speed/pressure profile. `simulatePressure` (default `false`) synthesizes pressure for points that have none on a timed stroke: the width multiplier ramps from `0.5` at each tip to neutral across the first and last 15% of arc length, so mouse strokes thin at the ends. Points that carry real `pressure` always use it, and untimed strokes ignore the option.\n\n**Example**\n\n```ts\nimport { strokeWidths } from '@vielzeug/ink';\n\nconst widths = strokeWidths(samples, { width: 6, thinning: 0.5 });\nconst tapered = strokeWidths(samples, { width: 6, taper: { start: 30, end: 30 }, simulatePressure: true });\n```\n\nThrows `InkConfigError` for a non-positive `width` or `referenceSpeed`, a `thinning` outside `[0, 1]`, a negative or non-finite `taper` length, or an empty `points` array.\n\n---\n\n### `strokeOutline()`\n\n```ts\nfunction strokeOutline(\n points: readonly StrokePoint[],\n widths: number | readonly number[],\n options?: StrokeOutlineOptions,\n): Point[];\n```\n\nReturns a closed polygon approximating the variable-width stroke: start cap, left offsets forward, end cap, right offsets backward, with no repeated final vertex. Pass a constant `widths` number for a uniform stroke.\n\n| Parameter | Type | Description |\n| --------- | ----------------------------- | --------------------------------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |\n| `widths` | `number \\| readonly number[]` | Constant width, or per-point widths from `strokeWidths()` |\n| `options` | `StrokeOutlineOptions` | `cap` (default `'round'`), `join` (default `'round'`), `miterLimit` (default `4`) |\n\n`cap` selects the end treatment: `'round'` half-circle caps, `'butt'` no cap points, `'square'` a half-width tangent extension at each end. `join` handles turns sharper than 90°, where naive offsetting makes the inner side cross itself: `'round'` keeps the plain offset samples (current default output), `'bevel'` replaces each sharp joint with the two adjacent segment-offset points, dropping the crossing spike, and `'miter'` extends to the offset-line intersection while the miter length stays within `miterLimit` × half width, falling back to bevel beyond it.\n\n**Returns:** `Point[]` ring, deterministic for deterministic input.\n\n**Example**\n\n```ts\nimport { strokeOutline } from '@vielzeug/ink';\n\nconst ring = strokeOutline(samples, widths);\nconst uniform = strokeOutline(samples, 4);\nconst marker = strokeOutline(samples, 4, { cap: 'square', join: 'miter', miterLimit: 6 });\n```\n\nThrows `InkConfigError` when an array `widths` length differs from `points` length or any width is not a positive finite number, when `cap` or `join` is not a known variant, or when `miterLimit` is not a positive finite number.\n\n---\n\n### `simplifyStroke()`\n\n```ts\nfunction simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[];\n```\n\nReturns a Ramer-Douglas-Peucker decimated subsequence of the input; first and last points are always kept.\n\n| Parameter | Type | Description |\n| ----------- | ------------------------ | -------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples |\n| `tolerance` | `number` | Maximum perpendicular deviation to discard, `>= 0` |\n\n**Returns:** `StrokePoint[]` containing the same object references as the input (metadata such as `pressure` and `time` survives).\n\n**Example**\n\n```ts\nimport { simplifyStroke } from '@vielzeug/ink';\n\nconst decimated = simplifyStroke(samples, 0.5);\n```\n\nThrows `InkConfigError` for a negative or non-finite `tolerance`.\n\n---\n\n### `polylineToSvgPath()`\n\n```ts\nfunction polylineToSvgPath(points: readonly Point[], options?: PolylineToSvgPathOptions): string;\n```\n\nReturns an SVG path `d` string: `M x y` plus one `L x y` per remaining point. Works for open strokes and for the closed ring from `strokeOutline()` — pass `close: true` for rings.\n\n| Parameter | Type | Description |\n| --------- | -------------------------- | --------------------------------------------------------------------------- |\n| `points` | `readonly Point[]` | Stroke samples or ring vertices (at least one) |\n| `options` | `PolylineToSvgPathOptions` | `close` appends `Z`; `precision` rounds coordinates (`0`–`12`, default `2`) |\n\n**Returns:** `string` suitable for a `<path d=\"...\">` attribute.\n\n**Example**\n\n```ts\nimport { polylineToSvgPath } from '@vielzeug/ink';\n\nconst d = polylineToSvgPath(samples, { precision: 1 }); // \"M 0 0 L 12 3 L 25 -2\"\nconst outline = polylineToSvgPath(ring, { close: true }); // \"M ... L ... Z\"\n```\n\nThrows `InkConfigError` when `points` is empty or `precision` is out of range.\n\n## Types\n\n```ts\ntype Point = Readonly<{ x: number; y: number }>;\n```\n\nA two-dimensional point. Structural so canvas-toolkit packages can share it without importing each other.\n\n```ts\ntype StrokePoint = Readonly<{\n x: number;\n y: number;\n pressure?: number; // normalized [0, 1]; 0.5 is neutral\n time?: number; // milliseconds, e.g. PointerEvent.timeStamp; enables width velocity\n}>;\n```\n\nA sampled stroke point. `time` values only need to share a clock; any monotonic source works.\n\n```ts\ninterface StabilizeStrokeOptions {\n strength?: number; // [0, 1], default 0.5\n}\n```\n\n```ts\ninterface SmoothStrokeOptions {\n tension?: number; // [0, 1], default 1\n steps?: number; // [2, 1000] integer, default 8\n}\n```\n\n```ts\ninterface StrokeWidthOptions {\n width: number; // required, > 0\n thinning?: number; // [0, 1], default 0.5\n referenceSpeed?: number; // > 0, default 0.5 (px per ms)\n taper?: StrokeTaperOptions; // arc-length end fade, default none\n simulatePressure?: boolean; // default false; timed strokes only\n}\n```\n\n```ts\ninterface StrokeTaperOptions {\n start?: number; // fade-in length along arc length, >= 0, default 0\n end?: number; // fade-out length along arc length, >= 0, default 0\n}\n```\n\n```ts\ntype StrokeCap = 'round' | 'butt' | 'square';\n```\n\n```ts\ntype StrokeJoin = 'round' | 'bevel' | 'miter';\n```\n\n```ts\ninterface StrokeOutlineOptions {\n cap?: StrokeCap; // default 'round'\n join?: StrokeJoin; // default 'round'\n miterLimit?: number; // > 0, default 4 (miter length / half width)\n}\n```\n\n```ts\ninterface PolylineToSvgPathOptions {\n close?: boolean; // default false\n precision?: number; // [0, 12] integer, default 2\n}\n```\n\n## Errors\n\n| Error | Trigger |\n| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |\n| `InkError` | Base class; catch all ink errors with `instanceof InkError` |\n| `InkConfigError` | Invalid options (strength, tension, steps, width, thinning, precision, tolerance, cap, join, miterLimit, taper, …) or point-count mismatches |\n",
|
|
6
|
+
"usage": "---\ntitle: 'Ink: Usage Guide'\ndescription: 'How to smooth freehand strokes with @vielzeug/ink: stabilization, smoothing, speed-based widths, outline polygons, and SVG paths.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nCapture samples from any pointer source — with a timestamp — then run them through the pipeline: stabilize while drawing, simplify, width, outline, serialize. Every function is pure, so you can call them in any order and re-run them freely.\n\n```ts\nimport {\n polylineToSvgPath,\n simplifyStroke,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n} from '@vielzeug/ink';\n\n// Capture: PointerEvent.timeStamp is the timestamp ink wants.\nconst samples: StrokePoint[] = [];\nelement.addEventListener('pointermove', (event) => {\n samples.push({ pressure: event.pressure, time: event.timeStamp, x: event.offsetX, y: event.offsetY });\n});\n\nconst stabilized = stabilizeStroke(samples);\nconst widths = strokeWidths(stabilized, { width: 6 });\nconst d = polylineToSvgPath(strokeOutline(stabilized, widths), { close: true });\n\n// Render with any SVG-capable surface.\nconst path = document.createElementNS('http://www.w3.org/2000/svg', 'path');\npath.setAttribute('d', d);\n```\n\n## Stabilize While Drawing\n\n`stabilizeStroke()` removes hand jitter causally — it never looks ahead — so you can run it on every pointer move while the stroke is being drawn. It emits exactly one point per input sample, keeping per-sample metadata aligned, and its last point is always the last input point: the stroke ends exactly where the pen lifted.\n\n```ts\nimport { stabilizeStroke } from '@vielzeug/ink';\n\nconst live = stabilizeStroke(samples, { strength: 0.5 }); // 0 = raw, 1 = maximum smoothing\n```\n\n## Smooth After Capture\n\n`smoothStroke()` resamples the stroke through a uniform Catmull-Rom spline: each input segment becomes `steps` samples, and the first and last input points are preserved exactly. Use it after capture when you want extra curvature between sparse samples. `pressure` and `time` are interpolated linearly, so widths computed from the output match widths computed from the input.\n\n```ts\nimport { smoothStroke } from '@vielzeug/ink';\n\nconst resampled = smoothStroke(samples, { tension: 1, steps: 8 });\n```\n\n## Profile Widths From Speed and Pressure\n\n`strokeWidths()` derives real pen speed from the `time` field: `distance / Δtime` between consecutive points. That stays correct after any stabilization, smoothing, or simplification — pipeline order no longer matters. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n\n```ts\nimport { strokeWidths } from '@vielzeug/ink';\n\nconst widths = strokeWidths(stabilized, {\n width: 6,\n thinning: 0.5, // 0 disables velocity, 1 is fully inverse-proportional\n referenceSpeed: 0.5, // neutral pen speed in pixels per millisecond\n});\n```\n\nWhen points carry `pressure` (normalized `[0, 1]`), it multiplies the result: `0.5` is neutral and maps to exactly `1`, so a mouse (which reports `0.5`) draws as wide as a device without pressure data. When any point lacks `time`, velocity modulation is disabled for the whole stroke — width becomes `width × pressure` — instead of guessing speed from sample spacing.\n\n`taper` fades the ends: within the first `taper.start` and last `taper.end` units of arc length, the width is multiplied by a smoothstep ramp that bottoms out at `0.15` of full width at the tips. `simulatePressure` gives mouse strokes the same in/out feel by synthesizing pressure for points that have none (ramping to `0.5×` width at each tip over the last 15% of arc length); points with real `pressure` always keep it.\n\n```ts\nconst tapered = strokeWidths(stabilized, {\n width: 6,\n taper: { start: 40, end: 40 }, // 40 px of arc length faded at each end\n simulatePressure: true, // thin the ends of pressure-less mouse strokes\n});\n```\n\n## Build the Outline\n\n`strokeOutline()` offsets each sample by half its width along the local normal and closes the ring with half-circle caps at both ends. The result is a plain `Point[]` you can fill with any renderer.\n\n```ts\nimport { strokeOutline } from '@vielzeug/ink';\n\nconst ring = strokeOutline(stabilized, widths); // variable width, closed polygon\nconst uniform = strokeOutline(stabilized, 6); // constant width, no array needed\n```\n\n`cap` changes the ends: `'butt'` stops at the last offsets, `'square'` extends each end by half the width along the tangent. `join` fixes the crossing spike naive offsetting produces at turns sharper than 90°: `'bevel'` cuts the corner with the two adjacent offset points, and `'miter'` extends to the exact intersection while its length stays within `miterLimit` × half width, falling back to bevel beyond that.\n\n```ts\nconst marker = strokeOutline(stabilized, 6, { cap: 'square', join: 'miter', miterLimit: 6 });\n```\n\n## Simplify Before Serializing\n\nLong strokes accumulate samples. `simplifyStroke()` runs Ramer-Douglas-Peucker and returns a subsequence of the input, so object identity, `pressure`, and `time` survive. Apply it to the outline before emitting SVG to shrink path data.\n\n```ts\nimport { simplifyStroke, polylineToSvgPath } from '@vielzeug/ink';\n\nconst compact = polylineToSvgPath(simplifyStroke(ring, 0.25), { close: true });\n```\n\n## Serialize to SVG Paths\n\n`polylineToSvgPath()` writes `M` plus one `L` per point, rounding coordinates to `precision` decimal places. Pass `close: true` to append `Z` for the closed outline ring; leave it off for a centerline path.\n\n```ts\nimport { polylineToSvgPath } from '@vielzeug/ink';\n\nconst centerline = polylineToSvgPath(simplifyStroke(stabilized, 0.5), { precision: 1 });\nconst outline = polylineToSvgPath(ring, { close: true });\n```\n\n## Framework Integration\n\nInk functions are pure, so they memoize cleanly. Recompute geometry only when the sample array changes.\n\n::: code-group\n\n```tsx [React]\nimport { useMemo } from 'react';\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths, type StrokePoint } from '@vielzeug/ink';\n\nfunction InkPath({ samples }: { samples: StrokePoint[] }) {\n const d = useMemo(() => {\n const stabilized = stabilizeStroke(samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n }, [samples]);\n\n return <path d={d} />;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { computed } from 'vue';\nimport {\n polylineToSvgPath,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n} from '@vielzeug/ink';\n\nconst props = defineProps<{ samples: StrokePoint[] }>();\nconst d = computed(() => {\n const stabilized = stabilizeStroke(props.samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n});\n</script>\n\n<template>\n <svg><path :d=\"d\" /></svg>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import {\n polylineToSvgPath,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n } from '@vielzeug/ink';\n\n export let samples: StrokePoint[];\n $: d = (() => {\n const stabilized = stabilizeStroke(samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n })();\n</script>\n\n<svg><path {d} /></svg>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nGesture produces the raw samples: bind a pan or drag handle, append each `current` point (with `event.timeStamp`) to an array, and pass the array to Ink when the stroke ends. Prism (or any SVG renderer) consumes the `d` strings Ink returns.\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\nimport { polylineToSvgPath, stabilizeStroke, type StrokePoint } from '@vielzeug/ink';\n\nconst samples: StrokePoint[] = [];\nconst drag = createDragGesture(surface, {\n onMove: ({ currentX, currentY, event }) => samples.push({ time: event.timeStamp, x: currentX, y: currentY }),\n onEnd: () => {\n path.setAttribute('d', polylineToSvgPath(stabilizeStroke(samples), { precision: 1 }));\n },\n});\n```\n\n## Best Practices\n\n- Pass `time` on every sample (`PointerEvent.timeStamp` or `performance.now()`): without it, widths are pressure-only and speed information is thrown away.\n- Stabilize live, smooth once: run `stabilizeStroke()` per pointer move for a calm preview, and add `smoothStroke()` or `simplifyStroke()` at commit time.\n- Simplify outlines with a tolerance around `0.2`–`0.5` device pixels; larger tolerances visibly flatten caps.\n- Keep `precision` at `1`–`2` for display paths; raise it only when another tool re-processes the output.\n- Treat invalid options errors (`InkConfigError`) as programming bugs: they throw at call time with the offending option named.\n- Memoize per stroke in UI frameworks; the functions are pure and cheap to cache.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Ink: Examples'\ndescription: Practical examples and recipes for @vielzeug/ink.\n---\n\n## Examples\n\n- [Jitter-Free Ink](./examples/jitter-free-ink.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
10
|
+
{
|
|
11
|
+
"id": "ink-outline-options",
|
|
12
|
+
"code": "import { polylineToSvgPath, strokeOutline, strokeWidths } from '@vielzeug/ink'\n\n// A hairpin turn plus a straight run: sharp enough that naive offsets spike.\nconst samples = [\n { time: 0, x: 20, y: 40 },\n { time: 16, x: 150, y: 40 },\n { time: 32, x: 70, y: 110 },\n { time: 48, x: 60, y: 30 },\n]\n\nconst widths = strokeWidths(samples, {\n width: 14,\n taper: { start: 30, end: 30 }, // fade the ends over 30px of arc length\n simulatePressure: true, // mouse strokes have no pressure: synthesize it\n})\n\nconst variants = [\n { label: 'round join + round cap', options: {} },\n { label: 'bevel join + butt cap', options: { cap: 'butt', join: 'bevel' } },\n { label: 'miter join + square cap', options: { cap: 'square', join: 'miter', miterLimit: 6 } },\n]\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '0 0 320 260')\nsvg.style.cssText = 'width:100%;max-width:480px;background:#f8fafc;border-radius:12px;'\n\nvariants.forEach((variant, row) => {\n const outline = strokeOutline(samples, widths, variant.options)\n const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')\n path.setAttribute('d', polylineToSvgPath(outline, { close: true }))\n path.setAttribute('fill', '#0f172a')\n path.setAttribute('transform', `translate(0 ${row * 84})`)\n const label = document.createElementNS('http://www.w3.org/2000/svg', 'text')\n label.setAttribute('x', '8')\n label.setAttribute('y', 12 + row * 84)\n label.setAttribute('font-size', '10')\n label.setAttribute('fill', '#64748b')\n label.textContent = variant.label\n svg.append(label, path)\n console.log(variant.label, 'outline points:', outline.length)\n})\n\ndocument.body.appendChild(svg)",
|
|
13
|
+
"name": "strokeOutline options - caps, joins, and taper"
|
|
14
|
+
},
|
|
10
15
|
{
|
|
11
16
|
"id": "ink-smoothing",
|
|
12
17
|
"code": "import { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink'\n\n// Deterministic zig-zag samples with timestamps: the jitter stabilization must remove.\nconst samples = Array.from({ length: 24 }, (_, i) => ({\n time: i * 16,\n x: 20 + i * 12,\n y: 80 + (i % 2 === 0 ? 14 : -14),\n}))\n\nconst stabilized = stabilizeStroke(samples)\nconst widths = strokeWidths(stabilized, { width: 8 })\nconst outline = strokeOutline(stabilized, widths)\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '0 0 320 160')\nsvg.style.cssText = 'width:100%;max-width:480px;background:#f8fafc;border-radius:12px;'\n\nconst raw = document.createElementNS('http://www.w3.org/2000/svg', 'polyline')\nraw.setAttribute('points', samples.map((p) => `${p.x},${p.y}`).join(' '))\nraw.setAttribute('fill', 'none')\nraw.setAttribute('stroke', '#cbd5e1')\nraw.setAttribute('stroke-dasharray', '4 4')\n\nconst ink = document.createElementNS('http://www.w3.org/2000/svg', 'path')\nink.setAttribute('d', polylineToSvgPath(outline, { close: true }))\nink.setAttribute('fill', '#0f172a')\n\nsvg.append(raw, ink)\ndocument.body.appendChild(svg)\n\nconsole.log('samples:', samples.length, 'stabilized:', stabilized.length, 'outline points:', outline.length)",
|
|
@@ -16,7 +21,10 @@
|
|
|
16
21
|
"typeSignatures": {
|
|
17
22
|
"InkConfigError": "export { InkConfigError, InkError } from './errors.js';",
|
|
18
23
|
"InkError": "export { InkConfigError, InkError } from './errors.js';",
|
|
19
|
-
"
|
|
24
|
+
"StrokeCap": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
|
|
25
|
+
"StrokeJoin": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
|
|
26
|
+
"StrokeOutlineOptions": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
|
|
27
|
+
"strokeOutline": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
|
|
20
28
|
"simplifyStroke": "export { simplifyStroke } from './simplify.js';",
|
|
21
29
|
"SmoothStrokeOptions": "export { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';",
|
|
22
30
|
"smoothStroke": "export { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';",
|
|
@@ -26,7 +34,8 @@
|
|
|
26
34
|
"polylineToSvgPath": "export { type PolylineToSvgPathOptions, polylineToSvgPath } from './svg.js';",
|
|
27
35
|
"Point": "export type { Point, StrokePoint } from './types.js';",
|
|
28
36
|
"StrokePoint": "export type { Point, StrokePoint } from './types.js';",
|
|
29
|
-
"
|
|
30
|
-
"
|
|
37
|
+
"StrokeTaperOptions": "export { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';",
|
|
38
|
+
"StrokeWidthOptions": "export { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';",
|
|
39
|
+
"strokeWidths": "export { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';"
|
|
31
40
|
}
|
|
32
41
|
}
|
package/data/packages/stage.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
|
-
"apiSource": "// Public root surface of @vielzeug/stage. Every public export goes through this file.\n\nexport { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';\nexport {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';\n",
|
|
2
|
+
"apiSource": "// Public root surface of @vielzeug/stage. Every public export goes through this file.\n\nexport { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';\nexport {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Stage: Retained-Mode 2D Canvas Engine'\ndescription: 'Retained-mode 2D canvas stage engine with DPR-aware layers, dirty repaints, and PNG export'\npackage: stage\ncategory: utilities\nkeywords: [canvas, rendering, layers, dpr, offscreencanvas, png-export, 2d]\nexports: [createStage, StageError, StageConfigError, StageDisposedError, StageUnsupportedError]\nrelated: [atlas, gesture, ink]\nenvironments: [browser, worker]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"stage\" />\n\n## Why Stage?\n\nA `requestAnimationFrame` loop that redraws everything every frame falls over once a canvas has more than a handful of layers: backgrounds, tiles, tokens, and overlays all repaint even when one token moved. Stage gives you a retained-mode alternative as a headless engine: every layer owns a cached backing surface, only dirty layers repaint, and the composite is one `drawImage` per layer. It handles DPR scaling, world-space transforms (pair it with `@vielzeug/atlas` cameras), and PNG export — with injectable surfaces and schedulers so the whole thing is unit-testable without a GPU.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/stage\n```\n\n```sh [npm]\nnpm install @vielzeug/stage\n```\n\n```sh [yarn]\nyarn add @vielzeug/stage\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createStage } from '@vielzeug/stage';\n\nconst stage = createStage(canvas, {\n dpr: window.devicePixelRatio,\n height: 600,\n layers: [\n { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },\n { id: 'tokens', paint: (ctx) => drawTokens(ctx) },\n ],\n width: 800,\n});\n\nstage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen; DPR applied on top\ntoken.x += 10;\nstage.invalidate('tokens'); // only the tokens layer repaints\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createStage()`**: layered retained-mode renderer with cached per-layer surfaces\n- **Dirty repaints**: invalidate one layer or all; frames coalesce via an injectable scheduler\n- **DPR-aware transforms**: paint in world units, the stage scales by `dpr × matrix`\n- **`StageController`**: one control type shared by main-thread and worker stages\n- **`toBlob()`**: PNG export of the composited canvas, flushing pending frames, with typed unsupported-capability errors\n- **Injectable surfaces**: `createSurface` factory for tests and `OffscreenCanvas` workers\n- **`@vielzeug/stage/worker`**: worker-rendered stages via a transferred `OffscreenCanvas` and a typed scene channel\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Atlas](/atlas/): cameras, spatial index, and tile grids that feed Stage transforms.\n- [Gesture](/gesture/): pointer drag, pinch, and wheel recognition.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Stage: API Reference'\ndescription: API reference for the Stage retained-mode 2D canvas engine.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------- | ------------------------------------------------------- | --------- | ----------------------------------------------------------------- |\n| `createStage()` | Retained-mode layered canvas renderer | Sync | Paint callbacks draw in world units; the stage applies the matrix |\n| `StageController` | Control surface shared by main-thread and worker stages | Type | Both modes are assignable to it; mode extras are not |\n| `StageError` | Base class for all stage errors | Sync | Narrow with `instanceof StageError` |\n| `StageConfigError` | Invalid sizes, duplicate/unknown layer ids | Sync | Thrown at call time, in both modes |\n| `StageDisposedError` | Blob export or worker request after disposal | Sync | Worker blob failures carry a `kind` mapped to this class |\n| `StageUnsupportedError` | Missing browser capability (2D context, blob export) | Sync | No silent degradation to a lesser path |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | ------------------------------------------------- |\n| `@vielzeug/stage` | Stage factory, controller type, and error classes |\n| `@vielzeug/stage/worker` | Worker-rendered stages over `OffscreenCanvas` |\n\nGeometry is not re-declared here: `Point`, `Rect`, `Matrix`, and `FrameScheduler` come from\n[`@vielzeug/atlas`](/atlas/api/), which `@vielzeug/stage` depends on.\n\n---\n\n## Core Types\n\n```ts\nimport type { FrameScheduler, Matrix, Rect, Size } from '@vielzeug/atlas';\n\ntype PaintContext = Readonly<{\n /** World→screen matrix (DPR already applied to the context transform). */\n matrix: Matrix;\n /** Visible world-space rect for culling. */\n visibleRect: Rect;\n /** Device pixel ratio in effect. */\n dpr: number;\n /** Frame timestamp from the scheduler. */\n time: number;\n}>;\n\n/** A backing surface a layer paints into. `OffscreenCanvas` on workers. */\ntype StageSurface = {\n width: number;\n height: number;\n getContext: (type: '2d', attributes?: CanvasRenderingContext2DSettings) => unknown;\n};\ntype CreateSurface = (width: number, height: number) => StageSurface;\n\n/**\n * The control surface both stage modes share. A main-thread `Stage` and a\n * `WorkerStage` are interchangeable wherever only control is needed.\n */\ntype StageController = Readonly<{\n resize: (size: Size, dpr?: number) => void;\n setTransform: (matrix: Matrix) => void;\n invalidate: (layerId?: string) => void;\n toBlob: (options?: { type?: string; quality?: number }) => Promise<Blob>;\n dispose: () => void;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n [Symbol.dispose]: () => void;\n}>;\n```\n\n`Size` comes from [`@vielzeug/atlas`](/atlas/api/) as well.\n\n---\n\n## `createStage()`\n\n```ts\nfunction createStage(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n options: StageOptions & Readonly<{ width: number; height: number }>,\n): Stage;\n```\n\nCreates a retained-mode stage: every layer owns a cached backing surface, is repainted only when dirty, and all layers are composited onto `canvas` in order each scheduled frame. The canvas backing store is sized `width × dpr` by `height × dpr`.\n\n| Parameter | Type | Description |\n| ----------------------- | -------------------------------------- | ---------------------------------------------------------------------- |\n| `canvas` | `HTMLCanvasElement \\| OffscreenCanvas` | Canvas the stage composites into (visible or transferred) |\n| `options.width` | `number` | CSS width in pixels; must be positive and finite |\n| `options.height` | `number` | CSS height in pixels; must be positive and finite |\n| `options.dpr` | `number?` | Device pixel ratio; defaults to `1` |\n| `options.layers` | `readonly StageLayerOptions[]` | Layers in paint order, fixed at creation; duplicate ids throw |\n| `options.scheduler` | `FrameScheduler?` | Injectable rAF scheduler for deterministic tests |\n| `options.createSurface` | `CreateSurface?` | Backing-surface factory; defaults to `OffscreenCanvas`/document canvas |\n| `options.background` | `string \\| null?` | Color cleared under the layers; defaults to transparent |\n\n**Returns:** `Stage` handle.\n\n**Example**\n\n```ts\nconst stage = createStage(canvas, {\n width: 800,\n height: 600,\n dpr: window.devicePixelRatio,\n layers: [{ id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) }],\n});\nstage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen, CSS pixels\nstage.invalidate('scene');\n```\n\n### `Stage` members\n\n`Stage` extends `StageController` (`resize`, `setTransform`, `invalidate`, `toBlob`, `dispose`, `disposed`, `disposalSignal`, `[Symbol.dispose]`) and adds:\n\n| Member | Description |\n| -------------------------------------------- | -------------------------------------------------------------------------------------- |\n| `render(time?)` | Runs the pending repaint/composite synchronously; `time` defaults to `scheduler.now()` |\n| `visibleRect` | Visible world-space rect derived from the inverse transform |\n| `matrix`, `width`, `height`, `dpr`, `canvas` | Current configuration |\n\n`toBlob()` flushes a pending frame before rasterizing, so it always exports the current frame. Paint callbacks receive a context whose transform is `dpr × matrix`, so they draw in world units. Clear and reset with `ctx.setTransform(1, 0, 0, 1, 0, 0)` only if you must paint in device pixels.\n\n---\n\n## Worker Subpath (`@vielzeug/stage/worker`)\n\n| Export | Description |\n| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `createWorkerStage<Scene>(canvas, worker, options)` | Main-thread client: transfers `canvas` to `worker` once, then drives it; a `StageController` plus `ready` and `sendScene(scene: Scene)` |\n| `serveStage<Scene>(scope, setup)` | Worker half: waits for `init`, creates a `createStage` on the transferred `OffscreenCanvas`, and services commands; `setup` returns `{ layers, onScene?, onDispose? }` |\n| `WorkerScope`, `WorkerSelfScope`, `WorkerStage`, `WorkerStageOptions`, `ServeStageSetup`, `StageServer` | Supporting types for both halves |\n\nThe worker owns its layer painters: `serveStage`'s `setup` supplies them, and the main thread never names layers. `onScene(scene, stage)` runs for each forwarded `scene` command and owns repaints — call `stage.invalidate(layerId)` for the layers the payload changed. `server.stage` exposes the created stage whenever you need it.\n\n`Scene` is the application payload type shared by `sendScene` and `onScene`, so neither side casts. Invalid size, DPR, or matrix input throws `StageConfigError` on the main thread, exactly like `createStage`. Worker-side exceptions are surfaced through `reportError`. The message protocol is internal: its version is checked once at the init/ready handshake, and a mismatch rejects `ready` with a `StageError` and disposes the stage.\n\n`createWorkerStage` throws `StageUnsupportedError` when the canvas cannot transfer control (`transferControlToOffscreen` missing). `dispose()` posts a final `dispose` command, rejects in-flight `toBlob()` promises with `StageDisposedError`, aborts `disposalSignal` (terminate the worker from there — the creator owns it), and makes later calls inert.\n\n## Errors\n\n| Class | Thrown when |\n| ----------------------- | ----------------------------------------------------------------- |\n| `StageError` | Base class; catch all stage failures with `instanceof` |\n| `StageConfigError` | Non-positive sizes, non-finite matrices, duplicate/unknown ids |\n| `StageDisposedError` | `toBlob()` after `dispose()`, or worker blob rejected on disposal |\n| `StageUnsupportedError` | No 2D context on a surface, or `canvas.toBlob` missing/failing |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Stage: Usage Guide'\ndescription: 'How to drive a @vielzeug/stage layered canvas: layers, transforms, dirty repaints, and export.'\n---\n\n[[toc]]\n\n## Basic Usage\n\n```ts\nimport { createStage } from '@vielzeug/stage';\n\nconst stage = createStage(canvas, {\n width: canvas.clientWidth,\n height: canvas.clientHeight,\n dpr: window.devicePixelRatio,\n layers: [\n { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },\n { id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) },\n { id: 'overlay', paint: (ctx) => drawSelection(ctx) },\n ],\n});\n```\n\nEach layer paints into its own cached backing surface. The stage composites all surfaces onto the visible canvas in registration order whenever a frame is scheduled. Paint callbacks receive a context already transformed by `dpr × matrix`, so they draw in **world units** and can cull against `frame.visibleRect`.\n\nLayers are fixed when the stage is created — the same in both render modes. Hide a layer by returning early from its paint and invalidating it. The stage sizes the canvas backing store; you own the canvas CSS size (set it via CSS or a `ResizeObserver`).\n\n## Driving the Transform\n\nThe stage takes a world→screen matrix in CSS pixels (it applies DPR itself). Pair it with an `@vielzeug/atlas` camera:\n\n```ts\nimport { createCamera } from '@vielzeug/atlas';\n\nconst camera = createCamera({ maxZoom: 16, minZoom: 0.05 });\ncamera.subscribe(() => stage.setTransform(camera.matrix));\n\ncanvas.addEventListener('wheel', (event) => {\n event.preventDefault();\n camera.zoomAt({ x: event.offsetX, y: event.offsetY }, Math.exp(-event.deltaY * 0.0015));\n});\n```\n\n`setTransform()` invalidates every layer — the cached world-space surfaces are no longer valid at the new transform. Compositing stays cheap (one `drawImage` per layer); only the paint callbacks re-run.\n\n## Dirty Repaints\n\nInvalidate the smallest unit that changed:\n\n```ts\ntoken.x += 10;\nstage.invalidate('tokens'); // only the tokens layer repaints next frame\n```\n\nInvalidations within one frame coalesce into a single scheduled frame. Call `stage.render()` to force a synchronous repaint (useful in tests).\n\n## Resize and DPR Changes\n\n```ts\nnew ResizeObserver(([entry]) => {\n stage.resize({ width: entry.contentRect.width, height: entry.contentRect.height }, window.devicePixelRatio);\n}).observe(canvas.parentElement!);\n```\n\n`resize()` resizes the canvas backing store and invalidates all layers; surfaces are reallocated at the new pixel size.\n\n## Exporting a PNG\n\n```ts\nconst blob = await stage.toBlob();\nawait navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);\n```\n\n`toBlob()` flushes any pending repaint before rasterizing, so it always captures the current frame — no manual `render()` first. It throws `StageUnsupportedError` when the canvas cannot produce a blob — the stage never silently degrades.\n\n## Testing with Injected Surfaces\n\nInject a fake surface factory and scheduler to unit-test paint behaviour without a GPU:\n\n```ts\nconst frames = { queued: new Set<(t: number) => void>() };\nconst stage = createStage(fakeCanvas, {\n createSurface: (w, h) => fakeSurface(w, h),\n height: 200,\n scheduler: {\n cancelFrame: (id) => frames.queued.delete(id),\n now: () => 0,\n requestFrame: (cb) => {\n frames.queued.add(cb);\n return frames.queued.size;\n },\n },\n width: 400,\n});\n```\n\nThe default factory uses `OffscreenCanvas` when present, else a canvas from the document; in environments with neither, it throws `StageUnsupportedError`.\n\n## Worker Rendering\n\nThe `@vielzeug/stage/worker` subpath renders the composited canvas inside a Web Worker. The main thread transfers an `OffscreenCanvas` once and then drives the stage over an internal message protocol; painters live worker-side. A `WorkerStage` and a main-thread `Stage` share the `StageController` type, so code that only controls a stage works with either.\n\n```ts\n// main.ts\nimport { createWorkerStage } from '@vielzeug/stage/worker';\n\ntype Scene = Readonly<{ col: number; id: string; row: number; type: 'move' }>;\n\nconst worker = new Worker(new URL('./stage.worker.ts', import.meta.url), { type: 'module' });\nconst stage = createWorkerStage<Scene>(canvas, worker, {\n height: 600,\n width: 800,\n});\n// The creator owns the worker: terminate it when the stage is disposed.\nstage.disposalSignal.addEventListener('abort', () => worker.terminate());\n\nawait stage.ready; // the worker created its stage\nstage.setTransform([1, 0, 0, 1, 0, 0]);\nstage.sendScene({ col: 3, id: 'hero', row: 2, type: 'move' });\nconst blob = await stage.toBlob({ type: 'image/png' }); // correlated round-trip\nstage.dispose(); // also rejects any in-flight blob requests\n```\n\n```ts\n// stage.worker.ts\nimport { serveStage } from '@vielzeug/stage/worker';\n\nserveStage<Scene>(self, () => ({\n layers: [{ id: 'scene', paint: (ctx) => ctx.fillRect(0, 0, 800, 600) }],\n onScene: (scene, stage) => {\n applyMove(scene);\n stage.invalidate('scene'); // the handler owns repaints\n },\n}));\n```\n\nNotes:\n\n- The worker owns its painters. `serveStage`'s `setup` returns the `layers` (and optional `onScene`/`onDispose` hooks); the main thread never names layers.\n- The canvas transfer is **one-shot**: `createWorkerStage` calls `transferControlToOffscreen()` on construction. To go back to main-thread rendering, mount a fresh `<canvas>` element.\n- `toBlob()` sends a `blob` command and resolves with the worker's response; requests are correlated by id and reject with `StageDisposedError` if the client is disposed while one is in flight.\n- `sendScene(scene)` forwards your typed payload to the worker's `onScene(scene, stage)` hook — useful for mirroring model state (e.g. token moves) without shipping painters to the main thread. The handler decides which layers to invalidate; nothing repaints automatically.\n- Invalid size, DPR, or matrix input throws `StageConfigError` on the main thread, exactly like `createStage`.\n- Worker-side exceptions are reported through `reportError`, the same path an uncaught main-thread paint error takes. The protocol version is checked once at the init/ready handshake; a stale cached worker rejects `ready` with a `StageError` and disposes the stage.\n\n## Best Practices\n\n- Keep per-layer paint callbacks cheap and cull with `frame.visibleRect`; the stage caches the result, so cost is paid once per invalidation, not per frame.\n- Put rarely-changing content (tile grids, backgrounds) on lower layers so pointer-driven changes only repaint upper layers.\n- Dispose the stage when the view unmounts: `using stage = createStage(...)` or `stage.dispose()`. Disposal cancels scheduled frames and releases every backing surface.\n- Treat `StageUnsupportedError` as a hard capability gap (feature-detect or surface it to the user); there is deliberately no fallback path.\n- In worker mode, invalidate only the layers a scene message changed — `onScene` runs on every forwarded payload.\n",
|
|
4
|
+
"index": "---\ntitle: 'Stage: Retained-Mode 2D Canvas Engine'\ndescription: 'Retained-mode 2D canvas stage engine with DPR-aware layers, dirty repaints, and PNG export'\npackage: stage\ncategory: utilities\nkeywords: [canvas, rendering, layers, dpr, offscreencanvas, png-export, 2d]\nexports: [createStage, StageError, StageConfigError, StageDisposedError, StageUnsupportedError]\nrelated: [atlas, gesture, ink]\nenvironments: [browser, worker]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"stage\" />\n\n## Why Stage?\n\nA `requestAnimationFrame` loop that redraws everything every frame falls over once a canvas has more than a handful of layers: backgrounds, tiles, tokens, and overlays all repaint even when one token moved. Stage gives you a retained-mode alternative as a headless engine: every layer owns a cached backing surface, only dirty layers repaint, and the composite is one `drawImage` per layer. It handles DPR scaling, world-space transforms (pair it with `@vielzeug/atlas` cameras), and PNG export — with injectable surfaces and schedulers so the whole thing is unit-testable without a GPU.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/stage\n```\n\n```sh [npm]\nnpm install @vielzeug/stage\n```\n\n```sh [yarn]\nyarn add @vielzeug/stage\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createStage } from '@vielzeug/stage';\n\nconst stage = createStage(canvas, {\n dpr: window.devicePixelRatio,\n height: 600,\n layers: [\n { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },\n { id: 'tokens', paint: (ctx) => drawTokens(ctx) },\n ],\n width: 800,\n});\n\nstage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen; DPR applied on top\ntoken.x += 10;\nstage.invalidate('tokens'); // only the tokens layer repaints\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createStage()`**: layered retained-mode renderer with cached per-layer surfaces\n- **Dirty repaints**: invalidate one layer or all; frames coalesce via an injectable scheduler\n- **DPR-aware transforms**: paint in world units, the stage scales by `dpr × matrix`\n- **`StageController`**: one control type shared by main-thread and worker stages\n- **`toBlob()`**: PNG export of the composited canvas, flushing pending frames, with optional world-space `region`/`scale` re-render and typed unsupported-capability errors\n- **Injectable surfaces**: `createSurface` factory for tests and `OffscreenCanvas` workers\n- **`@vielzeug/stage/worker`**: worker-rendered stages via a transferred `OffscreenCanvas` and a typed scene channel\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Atlas](/atlas/): cameras, spatial index, and tile grids that feed Stage transforms.\n- [Gesture](/gesture/): pointer drag, pinch, and wheel recognition.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Stage: API Reference'\ndescription: API reference for the Stage retained-mode 2D canvas engine.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------- | ------------------------------------------------------- | --------- | ----------------------------------------------------------------- |\n| `createStage()` | Retained-mode layered canvas renderer | Sync | Paint callbacks draw in world units; the stage applies the matrix |\n| `StageController` | Control surface shared by main-thread and worker stages | Type | Both modes are assignable to it; mode extras are not |\n| `StageError` | Base class for all stage errors | Sync | Narrow with `instanceof StageError` |\n| `StageConfigError` | Invalid sizes, duplicate/unknown layer ids | Sync | Thrown at call time, in both modes |\n| `StageDisposedError` | Blob export or worker request after disposal | Sync | Worker blob failures carry a `kind` mapped to this class |\n| `StageUnsupportedError` | Missing browser capability (2D context, blob export) | Sync | No silent degradation to a lesser path |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | ------------------------------------------------- |\n| `@vielzeug/stage` | Stage factory, controller type, and error classes |\n| `@vielzeug/stage/worker` | Worker-rendered stages over `OffscreenCanvas` |\n\nGeometry is not re-declared here: `Point`, `Rect`, `Matrix`, and `FrameScheduler` come from\n[`@vielzeug/atlas`](/atlas/api/), which `@vielzeug/stage` depends on.\n\n---\n\n## Core Types\n\n```ts\nimport type { FrameScheduler, Matrix, Rect, Size } from '@vielzeug/atlas';\n\ntype PaintContext = Readonly<{\n /** World→screen matrix (DPR already applied to the context transform). */\n matrix: Matrix;\n /** Visible world-space rect for culling. */\n visibleRect: Rect;\n /** Device pixel ratio in effect. */\n dpr: number;\n /** Frame timestamp from the scheduler. */\n time: number;\n}>;\n\n/** A backing surface a layer paints into. `OffscreenCanvas` on workers. */\ntype StageSurface = {\n width: number;\n height: number;\n getContext: (type: '2d', attributes?: CanvasRenderingContext2DSettings) => unknown;\n};\ntype CreateSurface = (width: number, height: number) => StageSurface;\n\n/** Options for `toBlob()`: blob encoding plus an optional world-space crop and density. */\ntype StageBlobOptions = Readonly<{\n type?: string;\n quality?: number;\n region?: Rect;\n scale?: number;\n}>;\n\n/**\n * The control surface both stage modes share. A main-thread `Stage` and a\n * `WorkerStage` are interchangeable wherever only control is needed.\n */\ntype StageController = Readonly<{\n resize: (size: Size, dpr?: number) => void;\n setTransform: (matrix: Matrix) => void;\n invalidate: (layerId?: string) => void;\n toBlob: (options?: StageBlobOptions) => Promise<Blob>;\n dispose: () => void;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n [Symbol.dispose]: () => void;\n}>;\n```\n\n`Size` comes from [`@vielzeug/atlas`](/atlas/api/) as well.\n\n---\n\n## `createStage()`\n\n```ts\nfunction createStage(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n options: StageOptions & Readonly<{ width: number; height: number }>,\n): Stage;\n```\n\nCreates a retained-mode stage: every layer owns a cached backing surface, is repainted only when dirty, and all layers are composited onto `canvas` in order each scheduled frame. The canvas backing store is sized `width × dpr` by `height × dpr`.\n\n| Parameter | Type | Description |\n| ----------------------- | -------------------------------------- | ---------------------------------------------------------------------- |\n| `canvas` | `HTMLCanvasElement \\| OffscreenCanvas` | Canvas the stage composites into (visible or transferred) |\n| `options.width` | `number` | CSS width in pixels; must be positive and finite |\n| `options.height` | `number` | CSS height in pixels; must be positive and finite |\n| `options.dpr` | `number?` | Device pixel ratio; defaults to `1` |\n| `options.layers` | `readonly StageLayerOptions[]` | Layers in paint order, fixed at creation; duplicate ids throw |\n| `options.scheduler` | `FrameScheduler?` | Injectable rAF scheduler for deterministic tests |\n| `options.createSurface` | `CreateSurface?` | Backing-surface factory; defaults to `OffscreenCanvas`/document canvas |\n| `options.background` | `string \\| null?` | Color cleared under the layers; defaults to transparent |\n\n**Returns:** `Stage` handle.\n\n**Example**\n\n```ts\nconst stage = createStage(canvas, {\n width: 800,\n height: 600,\n dpr: window.devicePixelRatio,\n layers: [{ id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) }],\n});\nstage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen, CSS pixels\nstage.invalidate('scene');\n```\n\n### `Stage` members\n\n`Stage` extends `StageController` (`resize`, `setTransform`, `invalidate`, `toBlob`, `dispose`, `disposed`, `disposalSignal`, `[Symbol.dispose]`) and adds:\n\n| Member | Description |\n| -------------------------------------------- | -------------------------------------------------------------------------------------- |\n| `render(time?)` | Runs the pending repaint/composite synchronously; `time` defaults to `scheduler.now()` |\n| `visibleRect` | Visible world-space rect derived from the inverse transform |\n| `matrix`, `width`, `height`, `dpr`, `canvas` | Current configuration |\n\n`toBlob()` flushes a pending frame before rasterizing, so it always exports the current frame. Paint callbacks receive a context whose transform is `dpr × matrix`, so they draw in world units. Clear and reset with `ctx.setTransform(1, 0, 0, 1, 0, 0)` only if you must paint in device pixels.\n\n### `toBlob(options?)`\n\n```ts\ntype StageBlobOptions = Readonly<{\n type?: string; // blob MIME type; defaults to 'image/png'\n quality?: number; // encoder quality for lossy types\n region?: Rect; // world-space crop; defaults to the visible rect\n scale?: number; // export pixels per world unit\n}>;\n```\n\nWithout `region`/`scale`, the stage exports its current canvas at the current device scale. With them, the stage re-paints every layer into scratch surfaces against `translate(-region) × scale` and composites the result into an offscreen surface sized `region.width × scale` by `region.height × scale` (rounded, at least 1 pixel per side) — layer caches are keyed to the live viewport transform, so a crop cannot reuse the cached composite. The cost is a full repaint; the live viewport, caches, and dirty flags are untouched. `scale` defaults to the current device pixels per world unit (`dpr × matrix scale`), which matches the on-screen density; paint callbacks see `frame.dpr = 1` and `frame.visibleRect = region` during an export.\n\nInvalid `region` (non-finite coordinates or non-positive size) or `scale` (non-positive or non-finite) throws `StageConfigError`; on a worker stage the failure arrives as `StageError`.\n\n---\n\n## Worker Subpath (`@vielzeug/stage/worker`)\n\n| Export | Description |\n| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `createWorkerStage<Scene>(canvas, worker, options)` | Main-thread client: transfers `canvas` to `worker` once, then drives it; a `StageController` plus `ready` and `sendScene(scene: Scene)` |\n| `serveStage<Scene>(scope, setup)` | Worker half: waits for `init`, creates a `createStage` on the transferred `OffscreenCanvas`, and services commands; `setup` returns `{ layers, onScene?, onDispose? }` |\n| `WorkerScope`, `WorkerSelfScope`, `WorkerStage`, `WorkerStageOptions`, `ServeStageSetup`, `StageServer` | Supporting types for both halves |\n\nThe worker owns its layer painters: `serveStage`'s `setup` supplies them, and the main thread never names layers. `onScene(scene, stage)` runs for each forwarded `scene` command and owns repaints — call `stage.invalidate(layerId)` for the layers the payload changed. `server.stage` exposes the created stage whenever you need it.\n\n`Scene` is the application payload type shared by `sendScene` and `onScene`, so neither side casts. Invalid size, DPR, or matrix input throws `StageConfigError` on the main thread, exactly like `createStage`. Worker-side exceptions are surfaced through `reportError`. The message protocol is internal: its version is checked once at the init/ready handshake, and a mismatch rejects `ready` with a `StageError` and disposes the stage.\n\n`createWorkerStage` throws `StageUnsupportedError` when the canvas cannot transfer control (`transferControlToOffscreen` missing). `dispose()` posts a final `dispose` command, rejects in-flight `toBlob()` promises with `StageDisposedError`, aborts `disposalSignal` (terminate the worker from there — the creator owns it), and makes later calls inert. `toBlob(options?)` forwards `StageBlobOptions` — including `region` and `scale` — verbatim; the worker performs the same region re-paint export on its `OffscreenCanvas` pipeline.\n\n## Errors\n\n| Class | Thrown when |\n| ----------------------- | ----------------------------------------------------------------------------------------- |\n| `StageError` | Base class; catch all stage failures with `instanceof` |\n| `StageConfigError` | Non-positive sizes, non-finite matrices, duplicate/unknown ids, bad `toBlob` region/scale |\n| `StageDisposedError` | `toBlob()` after `dispose()`, or worker blob rejected on disposal |\n| `StageUnsupportedError` | No 2D context on a surface, or `canvas.toBlob` missing/failing |\n",
|
|
6
|
+
"usage": "---\ntitle: 'Stage: Usage Guide'\ndescription: 'How to drive a @vielzeug/stage layered canvas: layers, transforms, dirty repaints, and export.'\n---\n\n[[toc]]\n\n## Basic Usage\n\n```ts\nimport { createStage } from '@vielzeug/stage';\n\nconst stage = createStage(canvas, {\n width: canvas.clientWidth,\n height: canvas.clientHeight,\n dpr: window.devicePixelRatio,\n layers: [\n { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },\n { id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) },\n { id: 'overlay', paint: (ctx) => drawSelection(ctx) },\n ],\n});\n```\n\nEach layer paints into its own cached backing surface. The stage composites all surfaces onto the visible canvas in registration order whenever a frame is scheduled. Paint callbacks receive a context already transformed by `dpr × matrix`, so they draw in **world units** and can cull against `frame.visibleRect`.\n\nLayers are fixed when the stage is created — the same in both render modes. Hide a layer by returning early from its paint and invalidating it. The stage sizes the canvas backing store; you own the canvas CSS size (set it via CSS or a `ResizeObserver`).\n\n## Driving the Transform\n\nThe stage takes a world→screen matrix in CSS pixels (it applies DPR itself). Pair it with an `@vielzeug/atlas` camera:\n\n```ts\nimport { createCamera } from '@vielzeug/atlas';\n\nconst camera = createCamera({ maxZoom: 16, minZoom: 0.05 });\ncamera.subscribe(() => stage.setTransform(camera.matrix));\n\ncanvas.addEventListener('wheel', (event) => {\n event.preventDefault();\n camera.zoomAt({ x: event.offsetX, y: event.offsetY }, Math.exp(-event.deltaY * 0.0015));\n});\n```\n\n`setTransform()` invalidates every layer — the cached world-space surfaces are no longer valid at the new transform. Compositing stays cheap (one `drawImage` per layer); only the paint callbacks re-run.\n\n## Dirty Repaints\n\nInvalidate the smallest unit that changed:\n\n```ts\ntoken.x += 10;\nstage.invalidate('tokens'); // only the tokens layer repaints next frame\n```\n\nInvalidations within one frame coalesce into a single scheduled frame. Call `stage.render()` to force a synchronous repaint (useful in tests).\n\n## Resize and DPR Changes\n\n```ts\nnew ResizeObserver(([entry]) => {\n stage.resize({ width: entry.contentRect.width, height: entry.contentRect.height }, window.devicePixelRatio);\n}).observe(canvas.parentElement!);\n```\n\n`resize()` resizes the canvas backing store and invalidates all layers; surfaces are reallocated at the new pixel size.\n\n## Exporting a PNG\n\n```ts\nconst blob = await stage.toBlob();\nawait navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);\n```\n\n`toBlob()` flushes any pending repaint before rasterizing, so it always captures the current frame — no manual `render()` first. It throws `StageUnsupportedError` when the canvas cannot produce a blob — the stage never silently degrades.\n\nFor a crop or a higher resolution, pass `region` (world units) and `scale` (export pixels per world unit):\n\n```ts\n// Export the visible area at 2× the on-screen density.\nconst blob = await stage.toBlob({\n region: stage.visibleRect,\n scale: stage.dpr * cameraZoom * 2,\n});\n```\n\nThe stage re-paints every layer into scratch surfaces against the region transform, so the cost is a full repaint rather than a blit of the cached composite; the live viewport and its caches are untouched. `scale` defaults to the current device pixels per world unit, and omitting `region` exports the visible rect. A non-positive or non-finite `region`/`scale` throws `StageConfigError`.\n\n## Testing with Injected Surfaces\n\nInject a fake surface factory and scheduler to unit-test paint behaviour without a GPU:\n\n```ts\nconst frames = { queued: new Set<(t: number) => void>() };\nconst stage = createStage(fakeCanvas, {\n createSurface: (w, h) => fakeSurface(w, h),\n height: 200,\n scheduler: {\n cancelFrame: (id) => frames.queued.delete(id),\n now: () => 0,\n requestFrame: (cb) => {\n frames.queued.add(cb);\n return frames.queued.size;\n },\n },\n width: 400,\n});\n```\n\nThe default factory uses `OffscreenCanvas` when present, else a canvas from the document; in environments with neither, it throws `StageUnsupportedError`.\n\n## Worker Rendering\n\nThe `@vielzeug/stage/worker` subpath renders the composited canvas inside a Web Worker. The main thread transfers an `OffscreenCanvas` once and then drives the stage over an internal message protocol; painters live worker-side. A `WorkerStage` and a main-thread `Stage` share the `StageController` type, so code that only controls a stage works with either.\n\n```ts\n// main.ts\nimport { createWorkerStage } from '@vielzeug/stage/worker';\n\ntype Scene = Readonly<{ col: number; id: string; row: number; type: 'move' }>;\n\nconst worker = new Worker(new URL('./stage.worker.ts', import.meta.url), { type: 'module' });\nconst stage = createWorkerStage<Scene>(canvas, worker, {\n height: 600,\n width: 800,\n});\n// The creator owns the worker: terminate it when the stage is disposed.\nstage.disposalSignal.addEventListener('abort', () => worker.terminate());\n\nawait stage.ready; // the worker created its stage\nstage.setTransform([1, 0, 0, 1, 0, 0]);\nstage.sendScene({ col: 3, id: 'hero', row: 2, type: 'move' });\nconst blob = await stage.toBlob({ type: 'image/png' }); // correlated round-trip\nstage.dispose(); // also rejects any in-flight blob requests\n```\n\n```ts\n// stage.worker.ts\nimport { serveStage } from '@vielzeug/stage/worker';\n\nserveStage<Scene>(self, () => ({\n layers: [{ id: 'scene', paint: (ctx) => ctx.fillRect(0, 0, 800, 600) }],\n onScene: (scene, stage) => {\n applyMove(scene);\n stage.invalidate('scene'); // the handler owns repaints\n },\n}));\n```\n\nNotes:\n\n- The worker owns its painters. `serveStage`'s `setup` returns the `layers` (and optional `onScene`/`onDispose` hooks); the main thread never names layers.\n- The canvas transfer is **one-shot**: `createWorkerStage` calls `transferControlToOffscreen()` on construction. To go back to main-thread rendering, mount a fresh `<canvas>` element.\n- `toBlob()` sends a `blob` command and resolves with the worker's response; requests are correlated by id and reject with `StageDisposedError` if the client is disposed while one is in flight. `region` and `scale` are forwarded verbatim and applied worker-side.\n- `sendScene(scene)` forwards your typed payload to the worker's `onScene(scene, stage)` hook — useful for mirroring model state (e.g. token moves) without shipping painters to the main thread. The handler decides which layers to invalidate; nothing repaints automatically.\n- Invalid size, DPR, or matrix input throws `StageConfigError` on the main thread, exactly like `createStage`.\n- Worker-side exceptions are reported through `reportError`, the same path an uncaught main-thread paint error takes. The protocol version is checked once at the init/ready handshake; a stale cached worker rejects `ready` with a `StageError` and disposes the stage.\n\n## Best Practices\n\n- Keep per-layer paint callbacks cheap and cull with `frame.visibleRect`; the stage caches the result, so cost is paid once per invalidation, not per frame.\n- Put rarely-changing content (tile grids, backgrounds) on lower layers so pointer-driven changes only repaint upper layers.\n- Dispose the stage when the view unmounts: `using stage = createStage(...)` or `stage.dispose()`. Disposal cancels scheduled frames and releases every backing surface.\n- Treat `StageUnsupportedError` as a hard capability gap (feature-detect or surface it to the user); there is deliberately no fallback path.\n- In worker mode, invalidate only the layers a scene message changed — `onScene` runs on every forwarded payload.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Stage: Examples'\ndescription: Practical examples and recipes for @vielzeug/stage.\n---\n\n## Examples\n\n- [Layered Repaints](./examples/layered-repaints.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [],
|
|
@@ -12,14 +12,15 @@
|
|
|
12
12
|
"StageDisposedError": "export { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';",
|
|
13
13
|
"StageError": "export { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';",
|
|
14
14
|
"StageUnsupportedError": "export { StageConfigError, StageDisposedError, StageError, StageUnsupportedError } from './errors.js';",
|
|
15
|
-
"CreateSurface": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
16
|
-
"createStage": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
17
|
-
"PaintContext": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
18
|
-
"Stage": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
15
|
+
"CreateSurface": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
16
|
+
"createStage": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
17
|
+
"PaintContext": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
18
|
+
"Stage": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
19
|
+
"StageBlobOptions": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
20
|
+
"StageController": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
21
|
+
"StageFrameInfo": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
22
|
+
"StageLayerOptions": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
23
|
+
"StageOptions": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';",
|
|
24
|
+
"StageSurface": "export {\n type CreateSurface,\n createStage,\n type PaintContext,\n type Stage,\n type StageBlobOptions,\n type StageController,\n type StageFrameInfo,\n type StageLayerOptions,\n type StageOptions,\n type StageSurface,\n} from './stage.js';"
|
|
24
25
|
}
|
|
25
26
|
}
|