@vielzeug/codex 26.11.21 → 26.11.23

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.
@@ -1,6 +1,6 @@
1
1
  # Vielzeug: Full Documentation
2
2
 
3
- > Complete documentation for 47 packages. Version: 26.11.20
3
+ > Complete documentation for 52 packages. Version: 26.11.22
4
4
 
5
5
  ---
6
6
 
@@ -2784,6 +2784,509 @@ use the flat tree for DOM algorithms; this helper is for test code that needs eq
2784
2784
 
2785
2785
  ---
2786
2786
 
2787
+ ## @vielzeug/atlas
2788
+
2789
+ **Category:** utilities
2790
+
2791
+ ### Overview
2792
+
2793
+ ## Why Atlas?
2794
+
2795
+ Every 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.
2796
+
2797
+ ```ts
2798
+ // Before
2799
+ // Hand-rolled transform stacks, linear scans on every pointermove, and
2800
+ // selection boxes that drift while zooming.
2801
+
2802
+ // After
2803
+ import { createCamera, createSpatialIndex } from '@vielzeug/atlas';
2804
+
2805
+ const camera = createCamera();
2806
+ camera.zoomAt({ x: 400, y: 300 }, 1.2); // world point under (400,300) stays put
2807
+
2808
+ const index = createSpatialIndex();
2809
+ index.set('shape-1', { height: 40, width: 60, x: 12, y: 8 });
2810
+ const hits = index.queryRect(camera.visibleRect); // viewport culling, returns ids
2811
+ ```
2812
+
2813
+ | Feature | Atlas | Ad-hoc math | Full scene libraries |
2814
+ | ------------------------------------- | -------------------------------------------- | ----------- | -------------------- |
2815
+ | Bundle size | | n/a | Typically 20–100 kB |
2816
+ | External dependencies | | n/a | Varies |
2817
+ | Anchor-preserving zoom/rotate | Built in | Drifts | Yes |
2818
+ | Dynamic R-tree hit-testing | Built in | O(n) scans | Yes |
2819
+ | Headless: no DOM, canvas, or renderer | | Varies | Usually coupled |
2820
+
2821
+ **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.
2822
+
2823
+ **Consider a full canvas engine when** you want a retained scene graph, built-in rendering, and event routing wholesale instead of headless primitives.
2824
+
2825
+ ## Installation
2826
+
2827
+ ```sh [pnpm]
2828
+ pnpm add @vielzeug/atlas
2829
+ ```
2830
+
2831
+ ```sh [npm]
2832
+ npm install @vielzeug/atlas
2833
+ ```
2834
+
2835
+ ```sh [yarn]
2836
+ yarn add @vielzeug/atlas
2837
+ ```
2838
+
2839
+ ## Quick Start
2840
+
2841
+ ```ts
2842
+ import { createCamera, createSpatialIndex } from '@vielzeug/atlas';
2843
+
2844
+ // state.x/y is the world point at the viewport centre
2845
+ const camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });
2846
+ camera.resize({ height: 600, width: 800 });
2847
+ camera.panBy(20, 0); // content follows the drag
2848
+ camera.fitBounds({ height: 400, width: 600, x: -50, y: -50 }, { padding: 40 });
2849
+
2850
+ const index = createSpatialIndex();
2851
+ index.set('a', { height: 10, width: 10, x: 0, y: 0 });
2852
+ index.queryPoint({ x: 5, y: 5 }); // ['a']
2853
+ ```
2854
+
2855
+ ## Features
2856
+
2857
+ - `createCamera()`: viewport-centred state, pan, anchor-preserving zoom/rotate, `fitBounds()`, rotated `visibleRect`, and `animateTo()` with an injectable frame scheduler
2858
+ - `createSpatialIndex()`: dynamic R-tree (Guttman quadratic split) with `set`/`delete`/`get`/`queryRect`/`queryPoint` over ids
2859
+ - Matrix helpers: `multiply`, `invert`, `apply`, `translate`, `scale`, `rotate`, `around`, `scaleOf`, `toCssMatrix` in Canvas2D element order
2860
+ - Rect math: union, closed-interval intersection, containment, inflation, and bounds-from-points
2861
+ - Snapping: `snapRect()` alignment/grid/equal-gap guides with `kind`-tagged targets, plus pure `alignRects()`/`distributeRects()`
2862
+ - Narrow-phase geometry: `pointInPolygon`, `distanceToPolyline`, `pointNearPolygon` for exact stroke and polygon hit-testing
2863
+ - `AtlasError` / `AtlasConfigError`: typed errors; the camera follows the Vielzeug disposal contract
2864
+ - Zero runtime dependencies, no DOM requirement: works in Node, Workers, and SSR
2865
+
2866
+ ## Documentation
2867
+
2868
+ - [Usage Guide](./usage.md)
2869
+ - [API Reference](./api.md)
2870
+ - [Examples](./examples.md)
2871
+ - [Migration Guide](./migration.md)
2872
+
2873
+ ## See Also
2874
+
2875
+ - [Gesture](/gesture/): pinch and wheel handles feed `zoomAt()` and `panBy()` directly.
2876
+ - [Ink](/ink/): stroke geometry whose bounds and outlines Atlas hit-tests.
2877
+ - [Wire](/wire/): edge routing for node editors sharing the same world coordinates.
2878
+
2879
+ ### API Reference
2880
+
2881
+ ## API Overview
2882
+
2883
+ | Symbol | Purpose | Execution | Common gotcha |
2884
+ | ------------------------------------ | -------------------------------------------------------- | --------- | --------------------------------------------------------- |
2885
+ | `createCamera()` | Pan/zoom/rotate camera with anchor-preserving transforms | Sync | `x`/`y` is the world point at the viewport centre |
2886
+ | `createSpatialIndex()` | Dynamic R-tree over world-space rects | Sync | Broad-phase only: bounds overlap, not exact shape hits |
2887
+ | `multiply()` etc. | Canvas2D-order matrix composition | Sync | Element order is `[a,b,c,d,e,f]`, not row-major 3×3 |
2888
+ | `rectFromPoints()` | AABB of a point set | Sync | Returns `null` only for iterable input that may be empty |
2889
+ | `pointInPolygon()` | Even-odd ray-cast containment | Sync | Boundary points are implementation-defined; add tolerance |
2890
+ | `distanceToPolyline()` | Distance to the nearest segment | Sync | Returns `Infinity` for empty paths |
2891
+ | `snapRect()` | Alignment, grid, and equal-gap snapping with guides | Sync | Each axis resolves independently; alignment wins |
2892
+ | `alignRects()` | Align rects to a shared edge or center | Sync | Pure: returns new rects, input untouched |
2893
+ | `distributeRects()` | Equalize gaps along one axis | Sync | Needs 3+ rects; outermost rects stay fixed |
2894
+ | `AtlasError` | Base class for all atlas errors | Sync | Narrow with `instanceof AtlasError` |
2895
+ | `AtlasConfigError` | Invalid options and negative tolerances | Sync | Thrown at call time |
2896
+ | `Point` / `Rect` / `Size` / `Matrix` | Structural shapes shared across the canvas toolkit | Sync | All readonly; treat as values |
2897
+
2898
+ ## Package Entry Point
2899
+
2900
+ | Import | Purpose |
2901
+ | ---------------------- | ---------------------------------------------------------------------- |
2902
+ | `@vielzeug/atlas` | Camera, spatial index, matrix/rect/geometry helpers, types, and errors |
2903
+ | `@vielzeug/atlas/grid` | Square-tile math, recursive shadowcasting FOV, and fog-of-war state |
2904
+
2905
+ ---
2906
+
2907
+ ## Core Types
2908
+
2909
+ ```ts
2910
+ type Point = Readonly;
2911
+ type Size = Readonly;
2912
+ type Rect = Readonly;
2913
+ /** Canvas2D/DOMMatrix element order: [a, b, c, d, e, f]. */
2914
+ type Matrix = readonly [number, number, number, number, number, number];
2915
+ ```
2916
+
2917
+ ---
2918
+
2919
+ ## `createCamera()`
2920
+
2921
+ ```ts
2922
+ function createCamera(options?: CameraOptions): Camera;
2923
+ ```
2924
+
2925
+ Creates 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.
2926
+
2927
+ | Parameter | Type | Description |
2928
+ | --------- | --------------- | ----------------------------------------------------------------------------------- |
2929
+ | `options` | `CameraOptions` | `initial` state, `viewport` size in CSS px, `minZoom`/`maxZoom` clamps, `scheduler` |
2930
+
2931
+ **Returns:** `Camera` handle.
2932
+
2933
+ **Example**
2934
+
2935
+ ```ts
2936
+ import { createCamera } from '@vielzeug/atlas';
2937
+
2938
+ const camera = createCamera({
2939
+ initial: { zoom: 1.5 },
2940
+ maxZoom: 8,
2941
+ minZoom: 0.1,
2942
+ viewport: { height: 600, width: 800 },
2943
+ });
2944
+ camera.zoomAt({ x: 400, y: 300 }, 1.2);
2945
+ ```
2946
+
2947
+ Without `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).
2948
+
2949
+ Throws `AtlasConfigError` when clamps violate `0 (options?: SpatialIndexOptions): SpatialIndex;
2950
+ ```
2951
+
2952
+ Creates 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.
2953
+
2954
+ | Parameter | Type | Description |
2955
+ | --------- | --------------------- | -------------------------------------------- |
2956
+ | `options` | `SpatialIndexOptions` | `maxEntriesPerNode` (integer ≥ 4, default 8) |
2957
+
2958
+ **Returns:** `SpatialIndex` handle.
2959
+
2960
+ **Example**
2961
+
2962
+ ```ts
2963
+ import { createSpatialIndex } from '@vielzeug/atlas';
2964
+
2965
+ const shapes = new Map();
2966
+ const index = createSpatialIndex();
2967
+ index.set('a', { height: 10, width: 10, x: 0, y: 0 });
2968
+ const hits = index.queryRect(marquee); // string[] of ids
2969
+ const shape = shapes.get(hits[0]);
2970
+ ```
2971
+
2972
+ ### SpatialIndex members
2973
+
2974
+ | Member | Description |
2975
+ | ----------------------------------- | ----------------------------------------------------------------------------------- |
2976
+ | `set(id, rect)` | Insert, or move an existing id; a no-op when the rect is unchanged |
2977
+ | `delete(id)` | `true` when removed, `false` when unknown |
2978
+ | `get(id)` | The current `Rect` for an id, or `undefined` |
2979
+ | `has(id)` | Membership test |
2980
+ | `queryRect(rect)` | Ids whose bounds overlap **or touch** `rect` (closed intervals) |
2981
+ | `queryPoint(point, { tolerance? })` | Ids within `tolerance` of `point` (default 0, inclusive); throws on negative values |
2982
+ | `clear()` / `size` / `bounds` | Reset, entry count, aggregate bounds (`null` when empty) |
2983
+
2984
+ Closed-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.
2985
+
2986
+ ---
2987
+
2988
+ ## Matrix Functions
2989
+
2990
+ All 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).
2991
+
2992
+ | Function | Description |
2993
+ | ------------------------ | ------------------------------------------------- |
2994
+ | `IDENTITY` | Frozen identity matrix |
2995
+ | `multiply(a, b)` | Compose two matrices |
2996
+ | `apply(matrix, point)` | Transform a point |
2997
+ | `translate(tx, ty)` | Translation builder |
2998
+ | `scale(sx, sy?)` | Scale builder (`sy` defaults to `sx`) |
2999
+ | `rotate(radians)` | Rotation builder; positive is clockwise on screen |
3000
+ | `invert(matrix)` | Inverse; `null` for zero determinant |
3001
+ | `around(anchor, matrix)` | `translate(anchor) · matrix · translate(-anchor)` |
3002
+ | `scaleOf(matrix)` | Average axis scale (0 for degenerate matrices) |
3003
+ | `toCssMatrix(matrix)` | `matrix(...)` CSS value |
3004
+
3005
+ ---
3006
+
3007
+ ## Rect Functions
3008
+
3009
+ | Function | Description |
3010
+ | ----------------------------------------------------------- | ------------------------------------------------------------------------------ |
3011
+ | `rectFromPoints(points)` | AABB of a point set; `null` for iterable input, non-null for a non-empty tuple |
3012
+ | `rectRight(rect)` / `rectBottom(rect)` / `rectCenter(rect)` | Edge and center accessors |
3013
+ | `unionRect(a, b)` | Smallest rect containing both |
3014
+ | `intersectRect(a, b)` | Overlap rect; `null` only when disjoint; touching yields a zero-area rect |
3015
+ | `rectsIntersect(a, b)` | Overlap-or-touch test (closed intervals) |
3016
+ | `containsRect(outer, inner)` / `containsPoint(rect, point)` | Inclusive containment tests |
3017
+ | `inflateRect(rect, amount)` | Grow every edge by `amount` |
3018
+
3019
+ `rectFromPoints` has two overloads: pass a literal non-empty tuple (`rectFromPoints([a, b])`) for a guaranteed `Rect`, or any `Iterable` for `Rect | null`.
3020
+
3021
+ ---
3022
+
3023
+ ## Geometry Functions
3024
+
3025
+ | Function | Description |
3026
+ | --------------------------------------------- | --------------------------------------------------------------------------- |
3027
+ | `pointInPolygon(polygon, point)` | Even-odd ray-cast containment |
3028
+ | `distanceToPolyline(path, point)` | Distance to the nearest segment; `Infinity` for empty paths |
3029
+ | `pointNearPolygon(polygon, point, tolerance)` | Inside the polygon OR within `tolerance` of its outline; throws on negative |
3030
+
3031
+ ---
3032
+
3033
+ ## Snapping Functions
3034
+
3035
+ | Function | Description |
3036
+ | ------------------------------ | ---------------------------------------------------------------------------------------------- |
3037
+ | `snapRect(rect, options)` | Snapped `{ delta, guides }` against candidate rects, grid lines, and equal gaps |
3038
+ | `alignRects(rects, edge)` | Copies aligned to a shared `left`/`horizontal-center`/`right`/`top`/`vertical-center`/`bottom` |
3039
+ | `distributeRects(rects, axis)` | Copies with equalized gaps along `'x'` or `'y'` |
3040
+
3041
+ `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.
3042
+
3043
+ A `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.
3044
+
3045
+ ---
3046
+
3047
+ ## Grid Functions
3048
+
3049
+ From the `@vielzeug/atlas/grid` subpath:
3050
+
3051
+ | Function | Returns |
3052
+ | -------------------------------------- | ----------------------------------------------------------------------------------------------- |
3053
+ | `worldToTile(point, grid)` | `TileCoord` (`{ col, row }`) containing the point (floor division) |
3054
+ | `tileToRect(coord, grid)` | World `Rect` of the tile |
3055
+ | `tileCenter(coord, grid)` | World `Point` at the tile's centre |
3056
+ | `visibleTileRange(view, grid)` | `TileRange` (`minCol/maxCol/minRow/maxRow`) intersecting a world rect |
3057
+ | `iterateTileRange(range)` | Generator over every `TileCoord` in a range |
3058
+ | `tileKey(coord)` | Stable `"col:row"` string |
3059
+ | `computeFov(origin, radius, options?)` | `Set` of visible `tileKey`s (8-octant recursive shadowcasting) |
3060
+ | `createFog()` | Three-state fog tracker over tile keys: `update`/`state`/`visible`, `exportState`/`importState` |
3061
+
3062
+ `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`.
3063
+
3064
+ ---
3065
+
3066
+ ## Errors
3067
+
3068
+ | Class | Thrown when |
3069
+ | ------------------ | ------------------------------------------------------------ |
3070
+ | `AtlasError` | Base class; catch-all via `instanceof AtlasError` |
3071
+ | `AtlasConfigError` | Invalid options/clamps and negative snap or query tolerances |
3072
+
3073
+ ### Usage Guide
3074
+
3075
+ ## Basic Usage
3076
+
3077
+ Atlas is headless: it never touches the DOM or a canvas. You feed it input events and scene rectangles, and it answers where things are.
3078
+
3079
+ ```ts
3080
+ import { createCamera, createSpatialIndex } from '@vielzeug/atlas';
3081
+
3082
+ // Camera: (x, y) is the world point shown at the viewport centre.
3083
+ const camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });
3084
+ camera.resize({ height: viewport.clientHeight, width: viewport.clientWidth });
3085
+
3086
+ // Screen → world for input handling.
3087
+ const world = camera.toWorld({ x: event.offsetX, y: event.offsetY });
3088
+
3089
+ // World → screen for positioning DOM overlays.
3090
+ const screen = camera.toScreen(shape.position);
3091
+ ```
3092
+
3093
+ ## Coordinate Spaces
3094
+
3095
+ Atlas works in three spaces and never guesses between them:
3096
+
3097
+ - **Client space**: `PointerEvent.clientX/Y`. Subtract the viewport's `getBoundingClientRect()` offset before handing coordinates to the camera.
3098
+ - **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.
3099
+ - **World space**: your scene coordinates. `camera.matrix` maps world → screen; `zoom` is screen pixels per world unit.
3100
+
3101
+ Positive `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.
3102
+
3103
+ ## Zooming to the Cursor
3104
+
3105
+ `zoomAt()` keeps the world point under a screen point fixed while the zoom changes — the standard infinite-canvas feel:
3106
+
3107
+ ```ts
3108
+ wheelElement.addEventListener('wheel', (event) => {
3109
+ const factor = Math.exp(-event.deltaY * 0.0015);
3110
+ camera.zoomAt({ x: event.offsetX, y: event.offsetY }, factor);
3111
+ });
3112
+ ```
3113
+
3114
+ `rotateAt()` does the same for rotation. Both clamp against `minZoom`/`maxZoom` and still hold the anchor exactly at the clamp.
3115
+
3116
+ ## Panning and Fitting
3117
+
3118
+ `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:
3119
+
3120
+ ```ts
3121
+ camera.panBy(event.movementX, event.movementY);
3122
+ camera.fitBounds(selectionBounds, { padding: 48 });
3123
+ ```
3124
+
3125
+ Because `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.
3126
+
3127
+ ## Animating the Camera
3128
+
3129
+ `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:
3130
+
3131
+ ```ts
3132
+ camera.animateTo(
3133
+ { x: 250, y: 100, zoom: 2 },
3134
+ {
3135
+ duration: 300,
3136
+ signal: controller.signal, // abort mid-flight; the animation stops where it is
3137
+ },
3138
+ );
3139
+ ```
3140
+
3141
+ ## Indexing the Scene
3142
+
3143
+ `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:
3144
+
3145
+ ```ts
3146
+ const index = createSpatialIndex(); // keys default to string
3147
+
3148
+ index.set(shape.id, shape.bounds); // insert, and again after every move
3149
+ index.delete(shape.id); // on delete
3150
+
3151
+ // Viewport culling each frame.
3152
+ const visibleIds = index.queryRect(camera.visibleRect);
3153
+
3154
+ // Marquee selection — the index returns ids; your own Map holds the data.
3155
+ const selected = index.queryRect(marquee).map((id) => shapes.get(id));
3156
+
3157
+ // Hover: tolerance widens the point into a box for fat-finger targets.
3158
+ const hovered = index.queryPoint(worldPoint, { tolerance: 4 / camera.state.zoom });
3159
+ ```
3160
+
3161
+ The 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.
3162
+
3163
+ ## Exact Hit-Testing
3164
+
3165
+ ```ts
3166
+ import { pointNearPolygon, pointInPolygon } from '@vielzeug/atlas';
3167
+
3168
+ pointInPolygon(polygon, worldPoint); // even-odd ray cast
3169
+ pointNearPolygon(polygon, worldPoint, 2); // inside OR within 2 units of the outline
3170
+ ```
3171
+
3172
+ Build 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.
3173
+
3174
+ ## Snapping and Alignment
3175
+
3176
+ While 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:
3177
+
3178
+ ```ts
3179
+ import { snapRect } from '@vielzeug/atlas';
3180
+
3181
+ const snap = snapRect(dragRect, {
3182
+ candidates: otherSelectedOutRects,
3183
+ grid: { x: 50, y: 50 },
3184
+ spacing: true, // opt into equal-gap spacing between neighbors
3185
+ threshold: 8,
3186
+ });
3187
+ const snapped = { ...dragRect, x: dragRect.x + snap.delta.x, y: dragRect.y + snap.delta.y };
3188
+ // snap.guides: [{ axis, kind, position, from, to, marks? }] in world coordinates — draw them through the camera.
3189
+ ```
3190
+
3191
+ Each 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.
3192
+
3193
+ Every 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.
3194
+
3195
+ After a multi-select, align or distribute with the pure helpers and record one command:
3196
+
3197
+ ```ts
3198
+ import { alignRects, distributeRects } from '@vielzeug/atlas';
3199
+
3200
+ const aligned = alignRects(selectedRects, 'horizontal-center'); // copies, same order
3201
+ const spread = distributeRects(selectedRects, 'x'); // equal gaps, outermost fixed
3202
+ ```
3203
+
3204
+ ## Matrix Helpers
3205
+
3206
+ For custom transforms, the matrix functions use Canvas2D order and compose left-to-right like `ctx.transform()`:
3207
+
3208
+ ```ts
3209
+ import {
3210
+ apply,
3211
+ around,
3212
+ IDENTITY,
3213
+ invert,
3214
+ multiply,
3215
+ rotate,
3216
+ scale,
3217
+ scaleOf,
3218
+ toCssMatrix,
3219
+ translate,
3220
+ } from '@vielzeug/atlas';
3221
+
3222
+ const transform = multiply(multiply(scale(2), rotate(Math.PI / 4)), translate(10, 5));
3223
+ apply(transform, { x: 1, y: 0 }); // transformed point
3224
+ invert(transform); // null for degenerate matrices
3225
+ around({ x: 100, y: 100 }, scale(2)); // scale about a point, not the origin
3226
+ scaleOf(transform); // average axis scale
3227
+ toCssMatrix(transform); // 'matrix(...)' for CSS transforms
3228
+ ```
3229
+
3230
+ ## Tile Grids
3231
+
3232
+ Tile 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:
3233
+
3234
+ ```ts
3235
+ import { iterateTileRange, tileCenter, tileKey, tileToRect, visibleTileRange, worldToTile } from '@vielzeug/atlas/grid';
3236
+
3237
+ const grid = { tileSize: 32 };
3238
+
3239
+ worldToTile({ x: 40, y: -1 }, grid); // { col: 1, row: -1 }
3240
+ tileToRect({ col: 1, row: -1 }, grid); // { x: 32, y: -32, width: 32, height: 32 }
3241
+ tileCenter({ col: 1, row: -1 }, grid); // { x: 48, y: -16 }
3242
+
3243
+ // Render loop: iterate the tiles intersecting the camera's world rect.
3244
+ for (const coord of iterateTileRange(visibleTileRange(camera.visibleRect, grid))) {
3245
+ drawTile(coord);
3246
+ }
3247
+ ```
3248
+
3249
+ `tileKey(coord)` yields the stable `"col:row"` string used by the FOV and fog APIs (and convenient as a `Map` key).
3250
+
3251
+ ## Field of View and Fog
3252
+
3253
+ `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:
3254
+
3255
+ ```ts
3256
+ import { computeFov, createFog } from '@vielzeug/atlas/grid';
3257
+
3258
+ const fov = computeFov({ col: 10, row: 8 }, 6, { blocks: (c) => walls.has(`${c.col}:${c.row}`) });
3259
+
3260
+ const fog = createFog();
3261
+ fog.update(fov); // demotes the previous frame's visible tiles to 'seen'
3262
+ fog.state(tileKey({ col: 10, row: 8 })); // 'visible' | 'seen' | 'unseen'
3263
+ saveGame(fog.exportState()); // serializable { seen, visible } key lists
3264
+ ```
3265
+
3266
+ `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` of the current keys.
3267
+
3268
+ ## Best Practices
3269
+
3270
+ - Subtract the viewport rect once at the input boundary; never mix client and screen coordinates inside camera calls.
3271
+ - Call `camera.resize()` from a `ResizeObserver` on the viewport element; the camera cannot anchor zooms to the centre without knowing its size.
3272
+ - Call `index.set(id, rect)` after every committed move — stale bounds silently break marquee and culling queries.
3273
+ - Use `camera.visibleRect` (the world AABB of the rotated viewport) for culling; it is conservative by design, so no visible shape is ever dropped.
3274
+ - 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.
3275
+ - 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.
3276
+
3277
+ ### Examples
3278
+
3279
+ ## Examples
3280
+
3281
+ - [Pan, Zoom and Culling](./examples/pan-zoom-and-culling.md)
3282
+
3283
+ ### REPL Examples
3284
+
3285
+ - createCamera - Pan, zoom and culling (id: `atlas-camera`)
3286
+ - snapRect - Magnetic snapping and guides (id: `atlas-snap`)
3287
+
3288
+ ---
3289
+
2787
3290
  ## @vielzeug/bard
2788
3291
 
2789
3292
  **Category:** utilities
@@ -4010,7 +4513,7 @@ onScopeDispose(unsubscribe);
4010
4513
 
4011
4514
  ## Examples
4012
4515
 
4013
- - [Getting Started](./examples/getting-started.md)
4516
+ - [Guided Tour](./examples/guided-tour.md)
4014
4517
 
4015
4518
  ### REPL Examples
4016
4519
 
@@ -5123,6 +5626,8 @@ npx -y @vielzeug/codex skills install --force # overwrite an existing copy
5123
5626
 
5124
5627
  Without `--target`, the first existing directory among `.agents/skills`, `.github/skills`, and `.claude/skills` is used; when none exists, `.agents/skills` is created. The command refuses to overwrite an installed skill unless `--force` is passed. Rerun after upgrading codex to pick up the current package list, which is generated from the published manifests. The skill pairs with the MCP server: its lookups (`get-docs`, `refine-get-component`, `refine-validate-usage`, …) assume codex is connected, and it documents `node_modules` fallbacks for when it is not.
5125
5628
 
5629
+ This installs only the **vielzeug consumer** skill (package discovery, Refine lookups). It does **not** install klugzeug workflow skills (`plan`, `build`, `test`, `review`, `docs`, `deliver`, `pipeline`, `onboard`). In the Vielzeug monorepo, workflow procedure lives under `~/.agents/skills/`; repo policy and validation gates live in root `AGENTS.md`.
5630
+
5126
5631
  ## Local Development
5127
5632
 
5128
5633
  Requires Node 22+ and root setup:
@@ -7220,7 +7725,7 @@ type SortableTouchOptions = Readonly HTMLElement | null);
7220
7725
 
7221
7726
  `preview` returns a template that Dnd clones before mounting it as a transient touch preview, so returning an element from the sortable item does not reparent or remove caller-owned DOM. Return `false` to disable the preview.
7222
7727
 
7223
- Touch sorting delegates one-pointer activation, movement, identity, and cancellation to Gesture's `createDragGesture()` with pointer capture disabled for document hit-testing. Dnd retains preview rendering, hit-testing, synthetic drag events, and sortable transactions. Non-primary pointers are ignored, and cancellation restores the pre-drag order without firing `onReorder`.
7728
+ Touch sorting delegates activation, movement, identity, and cancellation to Gesture's `createDragGesture()` with pointer capture disabled for document hit-testing. Dnd retains preview rendering, hit-testing, synthetic drag events, and sortable transactions. A second touch cancels sorting and restores the pre-drag order without firing `onReorder` or `onMove`. Without a configured handle, touch starts on editing controls, buttons, links, ARIA controls, and `[data-no-drag]` subtrees are excluded. Explicit handles remain eligible, including button handles.
7224
7729
 
7225
7730
  ## `createDropZone()`
7226
7731
 
@@ -7702,6 +8207,8 @@ createSortable({
7702
8207
  });
7703
8208
  ```
7704
8209
 
8210
+ Touch sorting ignores controls inside an item unless they belong to the configured handle. Put `data-no-drag` on a custom interaction subtree to exclude it when sorting whole items. A second finger cancels the drag and restores the original order; it never commits a reorder.
8211
+
7705
8212
  ### Keyboard reordering
7706
8213
 
7707
8214
  Focus an item and use arrow keys to move it. `Home` and `End` move to the boundary positions.
@@ -10818,6 +11325,8 @@ window.addEventListener('pagehide', () => pan.dispose(), { once: true });
10818
11325
  - `createDragGesture()`: unrestricted two-dimensional pointer movement tracking
10819
11326
  - `createPanGesture()`: one-axis pointer movement with direction intent recognition
10820
11327
  - `createLongPress()`: hold recognition with slop cancellation and click swallowing
11328
+ - `createPinchGesture()`: two-pointer scale and rotation with per-frame deltas
11329
+ - `createWheelGesture()`: wheel and trackpad input with pixel-normalized deltas
10821
11330
  - Direction locking: activates only when movement favors the configured axis
10822
11331
  - Configurable pointer capture: own the pointer by default or preserve native targeting
10823
11332
  - Configurable `activationDistance`: tune slop for touch density and component needs
@@ -10842,21 +11351,26 @@ window.addEventListener('pagehide', () => pan.dispose(), { once: true });
10842
11351
 
10843
11352
  ## API Overview
10844
11353
 
10845
- | Symbol | Purpose | Execution mode | Common gotcha |
10846
- | ------------------------------------------ | --------------------------------------------------- | -------------- | ------------------------------------------------------- |
10847
- | `createDragGesture()` | Track unrestricted two-dimensional pointer movement | Sync | Does not provide DOM movement or drop semantics |
10848
- | `createPanGesture()` | Track pointer movement projected onto one axis | Sync | Cross-axis intent ends a pending interaction |
10849
- | `createLongPress()` | Recognize a primary pointer held in place | Sync | The click that follows a fired hold is swallowed |
10850
- | `DragGesture` / `PanGesture` / `LongPress` | Control recognition lifecycle | Sync | `dispose()` does not invoke `onEnd` |
10851
- | `DragGestureOptions` | Configure free-drag recognition | Sync | `activationDistance` uses Euclidean distance |
10852
- | `PanGestureOptions` | Configure axis-locked recognition | Sync | Completion thresholds belong in `onEnd` |
10853
- | `LongPressOptions` | Configure hold recognition | Sync | `durationMs` and `slopPx` are validated at construction |
11354
+ | Symbol | Purpose | Execution mode | Common gotcha |
11355
+ | ------------------------------------------ | --------------------------------------------------- | -------------- | -------------------------------------------------------- |
11356
+ | `createDragGesture()` | Track unrestricted two-dimensional pointer movement | Sync | Does not provide DOM movement or drop semantics |
11357
+ | `createPanGesture()` | Track pointer movement projected onto one axis | Sync | Cross-axis intent ends a pending interaction |
11358
+ | `createLongPress()` | Recognize a primary pointer held in place | Sync | The click that follows a fired hold is swallowed |
11359
+ | `createPinchGesture()` | Track two-pointer scale and rotation | Sync | Ends when either pointer lifts |
11360
+ | `createWheelGesture()` | Track wheel input with pixel-normalized deltas | Sync | Never prevents scrolling unless `preventDefault` opts in |
11361
+ | `normalizeWheel()` | Convert wheel deltas to CSS pixels for any mode | Sync | Page-mode scaling uses the target's client box |
11362
+ | `DragGesture` / `PanGesture` / `LongPress` | Control recognition lifecycle | Sync | `dispose()` does not invoke `onEnd` |
11363
+ | `DragGestureOptions` | Configure free-drag recognition | Sync | `activationDistance` uses Euclidean distance |
11364
+ | `PanGestureOptions` | Configure axis-locked recognition | Sync | Completion thresholds belong in `onEnd` |
11365
+ | `LongPressOptions` | Configure hold recognition | Sync | `durationMs` and `slopPx` are validated at construction |
11366
+ | `PinchGestureOptions` | Configure pinch/rotate recognition | Sync | `activationDistance` is a span change, not pointer move |
11367
+ | `WheelOptions` | Configure wheel recognition | Sync | `preventDefault` accepts a per-event predicate |
10854
11368
 
10855
11369
  ## Package Entry Point
10856
11370
 
10857
- | Import | Purpose |
10858
- | ------------------- | ----------------------------------------------------------------------------------------- |
10859
- | `@vielzeug/gesture` | Drag and pan factories, handles, callback details, options, axes, points, and end reasons |
11371
+ | Import | Purpose |
11372
+ | ------------------- | -------------------------------------------------------------------------------------------------------------- |
11373
+ | `@vielzeug/gesture` | Drag, pan, long-press, pinch, and wheel factories, handles, callback details, options, points, and end reasons |
10860
11374
 
10861
11375
  ## Core Functions
10862
11376
 
@@ -10962,7 +11476,83 @@ const hold = createLongPress(list, {
10962
11476
  });
10963
11477
  ```
10964
11478
 
10965
- Movement beyond `slopPx` cancels back to a normal press, and window blur or a hidden document cancels a pending hold. The click that follows a fired hold is swallowed through a capture-phase listener on `target`, so releasing never commits what the hold opened; bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers.
11479
+ Movement beyond `slopPx`, a second touch, window blur, or a hidden document cancels a pending hold. The dynamic `disabled` predicate is checked again before the timer fires. The pointer-generated click following a fired hold is swallowed through a capture-phase listener on `target`; keyboard clicks (`detail: 0`) remain available. Bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers.
11480
+
11481
+ ---
11482
+
11483
+ ### `createPinchGesture()`
11484
+
11485
+ ```ts
11486
+ function createPinchGesture(target: Element, options?: PinchGestureOptions): PinchGesture;
11487
+ ```
11488
+
11489
+ Tracks two pointers and reports scale and rotation relative to the positions where they went down.
11490
+
11491
+ | Parameter | Type | Description |
11492
+ | --------- | --------------------- | --------------------------------------------------------------------- |
11493
+ | `target` | `Element` | Element that owns pointer admission and optional capture |
11494
+ | `options` | `PinchGestureOptions` | Activation, admission, capture, callback, and lifecycle configuration |
11495
+
11496
+ **Returns:** A lifecycle-owned `PinchGesture` handle with the same members as the other gestures.
11497
+
11498
+ **Example**
11499
+
11500
+ ```ts
11501
+ import { createPinchGesture } from '@vielzeug/gesture';
11502
+
11503
+ const pinch = createPinchGesture(stage, {
11504
+ onMove: ({ deltaScale, deltaRotation, deltaCentroid }) => {
11505
+ camera.zoomBy(1 + deltaScale);
11506
+ camera.rotateBy(deltaRotation);
11507
+ camera.panBy(deltaCentroid.x, deltaCentroid.y);
11508
+ },
11509
+ });
11510
+ ```
11511
+
11512
+ The gesture activates once the span between the pointers changes by `activationDistance` pixels. It ends when either pointer lifts (`reason: 'release'`) or the session is cancelled; the remaining pointer never continues the gesture. A third pointer down is ignored.
11513
+
11514
+ ---
11515
+
11516
+ ### `createWheelGesture()`
11517
+
11518
+ ```ts
11519
+ function createWheelGesture(target: Element, options?: WheelOptions): WheelGesture;
11520
+ ```
11521
+
11522
+ Reports wheel events with deltas normalized to CSS pixels. The handle is disposal-only: it has `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]()`, but no `active` or `cancel()` because wheel events are stateless.
11523
+
11524
+ | Parameter | Type | Description |
11525
+ | --------- | -------------- | ------------------------------------------------------------ |
11526
+ | `target` | `Element` | Element the `wheel` listener is attached to |
11527
+ | `options` | `WheelOptions` | Prevention, admission, callback, and lifecycle configuration |
11528
+
11529
+ **Returns:** A disposal-only `WheelGesture` handle.
11530
+
11531
+ **Example**
11532
+
11533
+ ```ts
11534
+ import { createWheelGesture } from '@vielzeug/gesture';
11535
+
11536
+ const wheel = createWheelGesture(stage, {
11537
+ preventDefault: true,
11538
+ onWheel: ({ deltaX, deltaY, pinch }) => {
11539
+ if (pinch) camera.zoomBy(Math.exp(-deltaY * 0.01));
11540
+ else camera.panBy(-deltaX, -deltaY);
11541
+ },
11542
+ });
11543
+ ```
11544
+
11545
+ `pinch` is `true` when `ctrlKey` is set, which is how browsers report trackpad pinch-zoom. Prevention defaults to `false`; the listener is non-passive so `preventDefault` works when opted in.
11546
+
11547
+ ---
11548
+
11549
+ ### `normalizeWheel()`
11550
+
11551
+ ```ts
11552
+ function normalizeWheel(event: WheelEvent, target: Element): { deltaX: number; deltaY: number };
11553
+ ```
11554
+
11555
+ Converts a wheel event's deltas to CSS pixels for any `deltaMode`: pixel mode passes through, line mode multiplies by 16, and page mode multiplies by the larger of the target's client width and height (falling back to the window box). Exported for consumers that already own their wheel listener.
10966
11556
 
10967
11557
  ## Types
10968
11558
 
@@ -10983,6 +11573,7 @@ type DragGestureOptions = Readonly boolean | undefined);
10983
11573
  onMove?: (detail: DragGestureDetail) => void;
10984
11574
  onStart?: (detail: DragGestureDetail) => void;
10985
11575
  pointerCapture?: boolean;
11576
+ shouldActivate?: (detail: DragGestureDetail) => boolean;
10986
11577
  shouldStart?: (event: PointerEvent) => boolean;
10987
11578
  signal?: AbortSignal;
10988
11579
  }>;
@@ -11007,6 +11598,7 @@ type PanGestureOptions = Readonly PanAxis);
11007
11598
  onMove?: (detail: PanGestureDetail) => void;
11008
11599
  onStart?: (detail: PanGestureDetail) => void;
11009
11600
  pointerCapture?: boolean;
11601
+ shouldActivate?: (detail: PanGestureDetail) => boolean;
11010
11602
  shouldStart?: (event: PointerEvent) => boolean;
11011
11603
  signal?: AbortSignal;
11012
11604
  }>;
@@ -11014,6 +11606,8 @@ type PanGestureOptions = Readonly PanAxis);
11014
11606
 
11015
11607
  Pan details project `start`, `current`, and `distance` onto `axis`. The default axis is `'x'`.
11016
11608
 
11609
+ Velocity is signed CSS pixels per second over the trailing 90 ms. Samples include pointerdown, movement (including activation), and release. A window with fewer than two distinct sample times reports zero velocity; a pause longer than the window removes earlier movement.
11610
+
11017
11611
  ### Long-press types
11018
11612
 
11019
11613
  ```ts
@@ -11029,6 +11623,49 @@ type LongPressOptions = Readonly boolean | undefined);
11029
11623
 
11030
11624
  `durationMs` defaults to `500` and `slopPx` to `8`. `event` is the pointerdown that started the hold, so `event.target` is the pressed element.
11031
11625
 
11626
+ ### Pinch types
11627
+
11628
+ ```ts
11629
+ type PinchEndReason = 'cancel' | 'release';
11630
+
11631
+ type PinchPoint = Readonly;
11632
+
11633
+ type PinchGestureDetail = Readonly;
11634
+
11635
+ type PinchGestureEndDetail = PinchGestureDetail &
11636
+ Readonly;
11637
+
11638
+ type PinchGestureOptions = Readonly boolean | undefined);
11639
+ onEnd?: (detail: PinchGestureEndDetail) => void;
11640
+ onMove?: (detail: PinchGestureDetail) => void;
11641
+ onStart?: (detail: PinchGestureDetail) => void;
11642
+ pointerCapture?: boolean;
11643
+ signal?: AbortSignal;
11644
+ }>;
11645
+ ```
11646
+
11647
+ `scale` is the current pointer span divided by the span when the pointers went down; `rotation` is the pointer-line angle since pointerdown in radians, positive clockwise, wrapped to `(-π, π]`. `deltaScale`, `deltaRotation`, and `deltaCentroid` are the change since the previous event (the start event's baseline for the first callback), which is what incremental transforms consume. Centroid coordinates are viewport `clientX`/`clientY` space. `activationDistance` is a span change in pixels and defaults to `6`. Pinch has no `shouldStart`; the first two pointers down after creation are tracked and later pointers are ignored.
11648
+
11649
+ ### Wheel types
11650
+
11651
+ ```ts
11652
+ type WheelDetail = Readonly;
11653
+
11654
+ type WheelOptions = Readonly boolean | undefined);
11655
+ onWheel?: (detail: WheelDetail) => void;
11656
+ preventDefault?: boolean | ((event: WheelEvent) => boolean);
11657
+ signal?: AbortSignal;
11658
+ }>;
11659
+
11660
+ type WheelGesture = Readonly void;
11661
+ readonly disposalSignal: AbortSignal;
11662
+ dispose(): void;
11663
+ readonly disposed: boolean;
11664
+ }>;
11665
+ ```
11666
+
11667
+ `deltaX`/`deltaY` are normalized to CSS pixels (see `normalizeWheel()`); positive moves content right/down. `pinch` mirrors `ctrlKey`.
11668
+
11032
11669
  ### Handle types
11033
11670
 
11034
11671
  ```ts
@@ -11042,25 +11679,28 @@ type DragGesture = {
11042
11679
  };
11043
11680
 
11044
11681
  type PanGesture = DragGesture;
11682
+
11683
+ type PinchGesture = DragGesture;
11045
11684
  ```
11046
11685
 
11047
11686
  ### Shared option behavior
11048
11687
 
11049
- | Option | Default | Contract |
11050
- | -------------------- | ------- | ------------------------------------------------------------------------------------------------------ |
11051
- | `activationDistance` | `6` | Non-negative finite CSS pixels; drag uses Euclidean distance, pan waits for dominant-axis intent |
11052
- | `axis` | `'x'` | Pan only; fixed value or getter sampled when each interaction starts |
11053
- | `disabled` | `false` | Fixed value or getter; blocks starts and cancels active recognition on the next matching pointer event |
11054
- | `pointerCapture` | `true` | Best-effort capture after activation; document tracking continues when capture is disabled or fails |
11055
- | `shouldStart` | N/A | Admission predicate evaluated for the primary pointer before tracking starts |
11056
- | `signal` | N/A | Disposes the handle when the external owner aborts |
11057
- | `onStart` | N/A | Runs once on the activating movement |
11058
- | `onMove` | N/A | Runs on the activating movement and each later matching movement |
11059
- | `onEnd` | N/A | Runs once for active release or cancellation; pending interactions end without callbacks |
11688
+ | Option | Default | Contract |
11689
+ | -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
11690
+ | `activationDistance` | `6` | Non-negative finite CSS pixels; drag uses Euclidean distance, pan waits for dominant-axis intent |
11691
+ | `axis` | `'x'` | Pan only; fixed value or getter sampled when each interaction starts |
11692
+ | `disabled` | `false` | Fixed value or getter; blocks starts and cancels active recognition on the next matching pointer event |
11693
+ | `pointerCapture` | `true` | Best-effort capture after activation; document tracking continues when capture is disabled or fails |
11694
+ | `shouldStart` | N/A | Admission predicate evaluated for the primary pointer before tracking starts |
11695
+ | `shouldActivate` | N/A | Drag/pan predicate evaluated once after distance/axis recognition and before capture or callbacks; false rejects the session |
11696
+ | `signal` | N/A | Disposes the handle when the external owner aborts |
11697
+ | `onStart` | N/A | Runs once on the activating movement |
11698
+ | `onMove` | N/A | Runs on the activating movement and each later matching movement |
11699
+ | `onEnd` | N/A | Runs once for active release or cancellation; pending interactions end without callbacks |
11060
11700
 
11061
11701
  Options and callback details are readonly. Fixed callbacks and capture policy are snapshotted at construction. Function-valued `axis` and `disabled` options remain dynamic.
11062
11702
 
11063
- Gesture tracks accepted movement with capture-phase listeners on the target's current owner document. Window blur, hidden-document transition, `pointercancel`, and pointer capture loss on the gesture target cancel active recognition. A `lostpointercapture` event bubbling from a descendant does not cancel the target's gesture.
11703
+ Gesture tracks accepted movement with capture-phase listeners on the target's current owner document. Window blur, hidden-document transition, `pointercancel`, pointer capture loss on the gesture target, and a second touch anywhere in that document cancel recognition. A `lostpointercapture` event bubbling from a descendant does not cancel the target's gesture. Exact diagonal ties remain pending until one axis dominates; cross-axis dominance rejects the pending pan. Gesture does not arbitrate ownership between recognizers on the same axis.
11064
11704
 
11065
11705
  ## Errors
11066
11706
 
@@ -11147,6 +11787,57 @@ const hold = createLongPress(grid, {
11147
11787
 
11148
11788
  Movement beyond `slopPx` cancels back to a normal press, so scrolling never triggers the hold. The click that follows a fired hold is swallowed through a capture-phase listener on `target`: bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers, and gate `shouldStart` to the elements the hold belongs to.
11149
11789
 
11790
+ ## Recognize Pinch and Rotate
11791
+
11792
+ Use `createPinchGesture()` for two-pointer scale and rotation. `scale` and `rotation` are relative to the positions where the two pointers went down, so a transform applied from `onStart` onward composes against the gesture's own baseline:
11793
+
11794
+ ```ts
11795
+ import { createPinchGesture } from '@vielzeug/gesture';
11796
+
11797
+ const stage = document.querySelector('[data-stage]');
11798
+ if (!stage) throw new Error('Missing [data-stage] element');
11799
+
11800
+ const card = stage.querySelector('[data-card]');
11801
+ if (!card) throw new Error('Missing [data-card] element');
11802
+
11803
+ let x = 0;
11804
+ let y = 0;
11805
+ createPinchGesture(stage, {
11806
+ onMove: ({ scale, rotation, deltaCentroid }) => {
11807
+ x += deltaCentroid.x;
11808
+ y += deltaCentroid.y;
11809
+ card.style.transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotation}rad)`;
11810
+ },
11811
+ });
11812
+ ```
11813
+
11814
+ The gesture activates once the pointer span changes by `activationDistance` pixels (default 6), which keeps two-finger taps from jittering the canvas. `deltaScale`, `deltaRotation`, and `deltaCentroid` carry the movement since the previous event, which is what incremental camera transforms consume. The session ends when either pointer lifts; the remaining pointer never continues the gesture. Set `touch-action: none` on the target.
11815
+
11816
+ Centroid coordinates are client-space, like every other pointer coordinate in this package. When the target is offset from the viewport origin, convert to target-local coordinates with `getBoundingClientRect()` before applying them to content.
11817
+
11818
+ Pair pinch with a single-pointer drag or pan by cancelling the single-pointer gesture from pinch's `onStart`; the drag handle's `cancel()` ends its active session without firing `onEnd`, so dragging and pinching never fight over the same surface.
11819
+
11820
+ ## Recognize Wheel and Trackpad Zoom
11821
+
11822
+ Use `createWheelGesture()` for scroll-wheel and trackpad input. Deltas are normalized to CSS pixels regardless of the browser's `deltaMode` (pixels, lines, or pages), and `pinch` marks the ctrl-key wheel events macOS sends for trackpad pinch-zoom:
11823
+
11824
+ ```ts
11825
+ import { createWheelGesture } from '@vielzeug/gesture';
11826
+
11827
+ const wheel = createWheelGesture(stage, {
11828
+ preventDefault: (event) => event.ctrlKey || stage.contains(event.target as Node),
11829
+ onWheel: ({ deltaX, deltaY, pinch }) => {
11830
+ if (pinch) {
11831
+ camera.zoomBy(Math.exp(-deltaY * 0.01));
11832
+ } else {
11833
+ camera.panBy(-deltaX, -deltaY);
11834
+ }
11835
+ },
11836
+ });
11837
+ ```
11838
+
11839
+ The recognizer never prevents silently: `preventDefault` defaults to `false`, and the listener is registered non-passive so prevention works when you opt in. `normalizeWheel()` is exported for code that already listens for wheel events and only needs the normalization.
11840
+
11150
11841
  ## Completion Rules
11151
11842
 
11152
11843
  Gesture reports movement and terminal state but does not decide what constitutes a swipe. Apply thresholds and allowed directions in `onEnd`.
@@ -11155,7 +11846,7 @@ Gesture reports movement and terminal state but does not decide what constitutes
11155
11846
  const pan = createPanGesture(panel, {
11156
11847
  axis: 'x',
11157
11848
  onEnd: ({ distance, reason }) => {
11158
- if (reason === 'release' && distance
11849
+ if (reason === 'release' && distance distance > 0 && scroller.scrollTop
11159
11850
  !event.composedPath().some((node) => node instanceof Element && node.matches('button, a, input, select, textarea')),
11160
11851
  onMove,
11161
11852
  onEnd,
@@ -11332,6 +12023,8 @@ Gesture owns pointer recognition: unrestricted two-dimensional drag and one-axis
11332
12023
 
11333
12024
  - createDragGesture - Basic (id: `drag-basic`)
11334
12025
  - createPanGesture - Basic (id: `pan-basic`)
12026
+ - createPinchGesture - Basic (id: `pinch-basic`)
12027
+ - createWheelGesture - Basic (id: `wheel-basic`)
11335
12028
 
11336
12029
  ---
11337
12030
 
@@ -12979,6 +13672,533 @@ const customers = Array.from({ length: 100 }, () => ({
12979
13672
 
12980
13673
  ---
12981
13674
 
13675
+ ## @vielzeug/ink
13676
+
13677
+ **Category:** data
13678
+
13679
+ ### Overview
13680
+
13681
+ ## Why Ink?
13682
+
13683
+ Raw 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.
13684
+
13685
+ ```ts
13686
+ // Before
13687
+ // Hand-rolled filter math, per-point width heuristics, and manual path assembly
13688
+ // in every drawing surface, each with its own jitter and nondeterminism.
13689
+
13690
+ // After
13691
+ import { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';
13692
+
13693
+ const stabilized = stabilizeStroke(samples);
13694
+ const d = polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 4 })), {
13695
+ close: true,
13696
+ });
13697
+ ```
13698
+
13699
+ | Feature | Ink | Ad-hoc smoothing | Sketch libraries |
13700
+ | ------------------------------ | -------------------------------------------- | ---------------- | -------------------- |
13701
+ | Bundle size | | n/a | Typically 10–50 kB |
13702
+ | External dependencies | | n/a | Varies |
13703
+ | Deterministic pure functions | | Rarely | Often randomized |
13704
+ | Variable-width outline polygon | Built in | Manual | Rare |
13705
+ | Runs without a DOM | | Varies | Usually browser-only |
13706
+
13707
+ **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.
13708
+
13709
+ **Consider direct polyline rendering when** the input is already clean (vector tools with their own smoothing) and a plain segment path is visually sufficient.
13710
+
13711
+ ## Installation
13712
+
13713
+ ```sh [pnpm]
13714
+ pnpm add @vielzeug/ink
13715
+ ```
13716
+
13717
+ ```sh [npm]
13718
+ npm install @vielzeug/ink
13719
+ ```
13720
+
13721
+ ```sh [yarn]
13722
+ yarn add @vielzeug/ink
13723
+ ```
13724
+
13725
+ ## Quick Start
13726
+
13727
+ ```ts
13728
+ import { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';
13729
+
13730
+ // Raw samples from a pointer stream (see @vielzeug/gesture for capture),
13731
+ // timestamped with PointerEvent.timeStamp.
13732
+ const samples = [
13733
+ { time: 0, x: 0, y: 0 },
13734
+ { time: 16, x: 12, y: 3 },
13735
+ { time: 32, x: 25, y: -2 },
13736
+ { time: 48, x: 40, y: 1 },
13737
+ ];
13738
+
13739
+ const stabilized = stabilizeStroke(samples); // causal jitter removal
13740
+ const widths = strokeWidths(stabilized, { width: 6 }); // speed-derived widths
13741
+ const ring = strokeOutline(stabilized, widths); // closed variable-width polygon
13742
+ const d = polylineToSvgPath(ring, { close: true }); // SVG `d` string
13743
+ ```
13744
+
13745
+ ## Features
13746
+
13747
+ - `stabilizeStroke()`: causal Streamline-style averaging for live drawing; the stroke ends exactly where the pen lifted
13748
+ - `smoothStroke()`: deterministic Catmull-Rom resampling after capture
13749
+ - `strokeWidths()`: real-speed-derived widths (`distance / Δtime`) with pressure modulation and clamped scaling
13750
+ - `strokeOutline()`: closed variable-width polygon offset along local normals with capped ends; constant width with a single number
13751
+ - `simplifyStroke()`: iterative Ramer-Douglas-Peucker decimation preserving endpoints
13752
+ - `polylineToSvgPath()`: SVG `d` strings for open strokes and closed outline rings, with configurable precision
13753
+ - `InkError` / `InkConfigError`: typed configuration errors thrown at call time
13754
+ - Determinism: identical input always yields identical output; no randomness, no clocks
13755
+ - Zero runtime dependencies and no DOM requirement: works in Node, Workers, and SSR
13756
+
13757
+ ## Documentation
13758
+
13759
+ - [Usage Guide](./usage.md)
13760
+ - [API Reference](./api.md)
13761
+ - [Examples](./examples.md)
13762
+ - [Migration Guide](./migration.md)
13763
+
13764
+ ## See Also
13765
+
13766
+ - [Gesture](/gesture/): captures the pointer samples Ink consumes; pan handles produce the raw point streams.
13767
+ - [Prism](/prism/): SVG rendering primitives; Ink's `d` strings drop straight into its path elements.
13768
+
13769
+ ### API Reference
13770
+
13771
+ ## API Overview
13772
+
13773
+ | Symbol | Purpose | Execution | Common gotcha |
13774
+ | ----------------------- | -------------------------------------------------------- | --------- | ----------------------------------------------------------------- |
13775
+ | `stabilizeStroke()` | Causal jitter removal while drawing | Sync | One output point per input; last point snaps to the pen-up spot |
13776
+ | `smoothStroke()` | Catmull-Rom resampling after capture | Sync | Adds points: `steps` samples per input segment |
13777
+ | `strokeWidths()` | Per-point widths from real speed (`time`) and pressure | Sync | Velocity is off for the whole stroke if any point lacks `time` |
13778
+ | `strokeOutline()` | Closed variable-width polygon around a stroke | Sync | Array `widths` must match point count; a number is constant |
13779
+ | `simplifyStroke()` | Ramer-Douglas-Peucker decimation | Sync | Returns input references, not copies |
13780
+ | `polylineToSvgPath()` | SVG `d` string for polylines and closed outline rings | Sync | Requires at least one point; pass `close: true` for rings |
13781
+ | `InkError` | Base class for all ink errors | Sync | Narrow with `instanceof InkError` |
13782
+ | `InkConfigError` | Invalid options or point counts | Sync | Thrown at call time, not construction |
13783
+ | `Point` / `StrokePoint` | Structural point shapes shared across the canvas toolkit | Sync | `pressure` and `time` are optional; `time` unlocks width velocity |
13784
+
13785
+ ## Package Entry Point
13786
+
13787
+ | Import | Purpose |
13788
+ | --------------- | ---------------------------------------------------------------------------------------------------- |
13789
+ | `@vielzeug/ink` | Stabilization, smoothing, width profiling, outline, simplification, SVG serialization, types, errors |
13790
+
13791
+ ---
13792
+
13793
+ ## Core Functions
13794
+
13795
+ ### `stabilizeStroke()`
13796
+
13797
+ ```ts
13798
+ function stabilizeStroke(points: readonly StrokePoint[], options?: StabilizeStrokeOptions): StrokePoint[];
13799
+ ```
13800
+
13801
+ Removes 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.
13802
+
13803
+ | Parameter | Type | Description |
13804
+ | --------- | ------------------------ | ----------------------------------------------------------- |
13805
+ | `points` | `readonly StrokePoint[]` | Input samples |
13806
+ | `options` | `StabilizeStrokeOptions` | `strength` in `[0, 1]`; `0` is the raw input, default `0.5` |
13807
+
13808
+ **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.
13809
+
13810
+ **Example**
13811
+
13812
+ ```ts
13813
+ import { stabilizeStroke } from '@vielzeug/ink';
13814
+
13815
+ const live = stabilizeStroke(samples, { strength: 0.6 });
13816
+ ```
13817
+
13818
+ Throws `InkConfigError` for a `strength` outside `[0, 1]`.
13819
+
13820
+ ---
13821
+
13822
+ ### `smoothStroke()`
13823
+
13824
+ ```ts
13825
+ function smoothStroke(points: readonly StrokePoint[], options?: SmoothStrokeOptions): StrokePoint[];
13826
+ ```
13827
+
13828
+ Resamples 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.
13829
+
13830
+ | Parameter | Type | Description |
13831
+ | --------- | ------------------------ | ------------------------------------------------------------------------------ |
13832
+ | `points` | `readonly StrokePoint[]` | Input samples; fewer than three are returned as copies |
13833
+ | `options` | `SmoothStrokeOptions` | `tension` in `[0, 1]` (default `1`), `steps` integer `[2, 1000]` (default `8`) |
13834
+
13835
+ **Returns:** New `StrokePoint[]` with `steps` samples per input segment plus the exact final point.
13836
+
13837
+ **Example**
13838
+
13839
+ ```ts
13840
+ import { smoothStroke } from '@vielzeug/ink';
13841
+
13842
+ const resampled = smoothStroke(samples, { tension: 1, steps: 8 });
13843
+ ```
13844
+
13845
+ Throws `InkConfigError` for a `tension` outside `[0, 1]` or a `steps` value outside `[2, 1000]` or non-integer.
13846
+
13847
+ ---
13848
+
13849
+ ### `strokeWidths()`
13850
+
13851
+ ```ts
13852
+ function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[];
13853
+ ```
13854
+
13855
+ Returns 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.
13856
+
13857
+ | Parameter | Type | Description |
13858
+ | --------- | ------------------------ | ---------------------------------------------------------------------------------------------------------- |
13859
+ | `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |
13860
+ | `options` | `StrokeWidthOptions` | `width` (required, > 0), `thinning` in `[0, 1]` (default `0.5`), `referenceSpeed` in px/ms (default `0.5`) |
13861
+
13862
+ **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.
13863
+
13864
+ Pressure 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.
13865
+
13866
+ **Example**
13867
+
13868
+ ```ts
13869
+ import { strokeWidths } from '@vielzeug/ink';
13870
+
13871
+ const widths = strokeWidths(samples, { width: 6, thinning: 0.5 });
13872
+ ```
13873
+
13874
+ Throws `InkConfigError` for a non-positive `width` or `referenceSpeed`, a `thinning` outside `[0, 1]`, or an empty `points` array.
13875
+
13876
+ ---
13877
+
13878
+ ### `strokeOutline()`
13879
+
13880
+ ```ts
13881
+ function strokeOutline(points: readonly StrokePoint[], widths: number | readonly number[]): Point[];
13882
+ ```
13883
+
13884
+ Returns 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.
13885
+
13886
+ | Parameter | Type | Description |
13887
+ | --------- | ----------------------------- | --------------------------------------------------------- |
13888
+ | `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |
13889
+ | `widths` | `number \| readonly number[]` | Constant width, or per-point widths from `strokeWidths()` |
13890
+
13891
+ **Returns:** `Point[]` ring, deterministic for deterministic input.
13892
+
13893
+ **Example**
13894
+
13895
+ ```ts
13896
+ import { strokeOutline } from '@vielzeug/ink';
13897
+
13898
+ const ring = strokeOutline(samples, widths);
13899
+ const uniform = strokeOutline(samples, 4);
13900
+ ```
13901
+
13902
+ Throws `InkConfigError` when an array `widths` length differs from `points` length or any width is not a positive finite number.
13903
+
13904
+ ---
13905
+
13906
+ ### `simplifyStroke()`
13907
+
13908
+ ```ts
13909
+ function simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[];
13910
+ ```
13911
+
13912
+ Returns a Ramer-Douglas-Peucker decimated subsequence of the input; first and last points are always kept.
13913
+
13914
+ | Parameter | Type | Description |
13915
+ | ----------- | ------------------------ | -------------------------------------------------- |
13916
+ | `points` | `readonly StrokePoint[]` | Stroke samples |
13917
+ | `tolerance` | `number` | Maximum perpendicular deviation to discard, `>= 0` |
13918
+
13919
+ **Returns:** `StrokePoint[]` containing the same object references as the input (metadata such as `pressure` and `time` survives).
13920
+
13921
+ **Example**
13922
+
13923
+ ```ts
13924
+ import { simplifyStroke } from '@vielzeug/ink';
13925
+
13926
+ const decimated = simplifyStroke(samples, 0.5);
13927
+ ```
13928
+
13929
+ Throws `InkConfigError` for a negative or non-finite `tolerance`.
13930
+
13931
+ ---
13932
+
13933
+ ### `polylineToSvgPath()`
13934
+
13935
+ ```ts
13936
+ function polylineToSvgPath(points: readonly Point[], options?: PolylineToSvgPathOptions): string;
13937
+ ```
13938
+
13939
+ Returns 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.
13940
+
13941
+ | Parameter | Type | Description |
13942
+ | --------- | -------------------------- | --------------------------------------------------------------------------- |
13943
+ | `points` | `readonly Point[]` | Stroke samples or ring vertices (at least one) |
13944
+ | `options` | `PolylineToSvgPathOptions` | `close` appends `Z`; `precision` rounds coordinates (`0`–`12`, default `2`) |
13945
+
13946
+ **Returns:** `string` suitable for a `` attribute.
13947
+
13948
+ **Example**
13949
+
13950
+ ```ts
13951
+ import { polylineToSvgPath } from '@vielzeug/ink';
13952
+
13953
+ const d = polylineToSvgPath(samples, { precision: 1 }); // "M 0 0 L 12 3 L 25 -2"
13954
+ const outline = polylineToSvgPath(ring, { close: true }); // "M ... L ... Z"
13955
+ ```
13956
+
13957
+ Throws `InkConfigError` when `points` is empty or `precision` is out of range.
13958
+
13959
+ ## Types
13960
+
13961
+ ```ts
13962
+ type Point = Readonly;
13963
+ ```
13964
+
13965
+ A two-dimensional point. Structural so canvas-toolkit packages can share it without importing each other.
13966
+
13967
+ ```ts
13968
+ type StrokePoint = Readonly;
13969
+ ```
13970
+
13971
+ A sampled stroke point. `time` values only need to share a clock; any monotonic source works.
13972
+
13973
+ ```ts
13974
+ interface StabilizeStrokeOptions {
13975
+ strength?: number; // [0, 1], default 0.5
13976
+ }
13977
+ ```
13978
+
13979
+ ```ts
13980
+ interface SmoothStrokeOptions {
13981
+ tension?: number; // [0, 1], default 1
13982
+ steps?: number; // [2, 1000] integer, default 8
13983
+ }
13984
+ ```
13985
+
13986
+ ```ts
13987
+ interface StrokeWidthOptions {
13988
+ width: number; // required, > 0
13989
+ thinning?: number; // [0, 1], default 0.5
13990
+ referenceSpeed?: number; // > 0, default 0.5 (px per ms)
13991
+ }
13992
+ ```
13993
+
13994
+ ```ts
13995
+ interface PolylineToSvgPathOptions {
13996
+ close?: boolean; // default false
13997
+ precision?: number; // [0, 12] integer, default 2
13998
+ }
13999
+ ```
14000
+
14001
+ ## Errors
14002
+
14003
+ | Error | Trigger |
14004
+ | ---------------- | -------------------------------------------------------------------------------------------------------------- |
14005
+ | `InkError` | Base class; catch all ink errors with `instanceof InkError` |
14006
+ | `InkConfigError` | Invalid options (strength, tension, steps, width, thinning, precision, tolerance, …) or point-count mismatches |
14007
+
14008
+ ### Usage Guide
14009
+
14010
+ ## Basic Usage
14011
+
14012
+ Capture 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.
14013
+
14014
+ ```ts
14015
+ import {
14016
+ polylineToSvgPath,
14017
+ simplifyStroke,
14018
+ stabilizeStroke,
14019
+ strokeOutline,
14020
+ strokeWidths,
14021
+ type StrokePoint,
14022
+ } from '@vielzeug/ink';
14023
+
14024
+ // Capture: PointerEvent.timeStamp is the timestamp ink wants.
14025
+ const samples: StrokePoint[] = [];
14026
+ element.addEventListener('pointermove', (event) => {
14027
+ samples.push({ pressure: event.pressure, time: event.timeStamp, x: event.offsetX, y: event.offsetY });
14028
+ });
14029
+
14030
+ const stabilized = stabilizeStroke(samples);
14031
+ const widths = strokeWidths(stabilized, { width: 6 });
14032
+ const d = polylineToSvgPath(strokeOutline(stabilized, widths), { close: true });
14033
+
14034
+ // Render with any SVG-capable surface.
14035
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
14036
+ path.setAttribute('d', d);
14037
+ ```
14038
+
14039
+ ## Stabilize While Drawing
14040
+
14041
+ `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.
14042
+
14043
+ ```ts
14044
+ import { stabilizeStroke } from '@vielzeug/ink';
14045
+
14046
+ const live = stabilizeStroke(samples, { strength: 0.5 }); // 0 = raw, 1 = maximum smoothing
14047
+ ```
14048
+
14049
+ ## Smooth After Capture
14050
+
14051
+ `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.
14052
+
14053
+ ```ts
14054
+ import { smoothStroke } from '@vielzeug/ink';
14055
+
14056
+ const resampled = smoothStroke(samples, { tension: 1, steps: 8 });
14057
+ ```
14058
+
14059
+ ## Profile Widths From Speed and Pressure
14060
+
14061
+ `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.
14062
+
14063
+ ```ts
14064
+ import { strokeWidths } from '@vielzeug/ink';
14065
+
14066
+ const widths = strokeWidths(stabilized, {
14067
+ width: 6,
14068
+ thinning: 0.5, // 0 disables velocity, 1 is fully inverse-proportional
14069
+ referenceSpeed: 0.5, // neutral pen speed in pixels per millisecond
14070
+ });
14071
+ ```
14072
+
14073
+ When 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.
14074
+
14075
+ ## Build the Outline
14076
+
14077
+ `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.
14078
+
14079
+ ```ts
14080
+ import { strokeOutline } from '@vielzeug/ink';
14081
+
14082
+ const ring = strokeOutline(stabilized, widths); // variable width, closed polygon
14083
+ const uniform = strokeOutline(stabilized, 6); // constant width, no array needed
14084
+ ```
14085
+
14086
+ ## Simplify Before Serializing
14087
+
14088
+ Long 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.
14089
+
14090
+ ```ts
14091
+ import { simplifyStroke, polylineToSvgPath } from '@vielzeug/ink';
14092
+
14093
+ const compact = polylineToSvgPath(simplifyStroke(ring, 0.25), { close: true });
14094
+ ```
14095
+
14096
+ ## Serialize to SVG Paths
14097
+
14098
+ `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.
14099
+
14100
+ ```ts
14101
+ import { polylineToSvgPath } from '@vielzeug/ink';
14102
+
14103
+ const centerline = polylineToSvgPath(simplifyStroke(stabilized, 0.5), { precision: 1 });
14104
+ const outline = polylineToSvgPath(ring, { close: true });
14105
+ ```
14106
+
14107
+ ## Framework Integration
14108
+
14109
+ Ink functions are pure, so they memoize cleanly. Recompute geometry only when the sample array changes.
14110
+
14111
+ ```tsx [React]
14112
+ import { useMemo } from 'react';
14113
+ import { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths, type StrokePoint } from '@vielzeug/ink';
14114
+
14115
+ function InkPath({ samples }: { samples: StrokePoint[] }) {
14116
+ const d = useMemo(() => {
14117
+ const stabilized = stabilizeStroke(samples);
14118
+ return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });
14119
+ }, [samples]);
14120
+
14121
+ return ;
14122
+ }
14123
+ ```
14124
+
14125
+ ```vue [Vue 3]
14126
+
14127
+ import { computed } from 'vue';
14128
+ import {
14129
+ polylineToSvgPath,
14130
+ stabilizeStroke,
14131
+ strokeOutline,
14132
+ strokeWidths,
14133
+ type StrokePoint,
14134
+ } from '@vielzeug/ink';
14135
+
14136
+ const props = defineProps();
14137
+ const d = computed(() => {
14138
+ const stabilized = stabilizeStroke(props.samples);
14139
+ return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });
14140
+ });
14141
+
14142
+
14143
+
14144
+ ```
14145
+
14146
+ ```svelte [Svelte]
14147
+
14148
+ import {
14149
+ polylineToSvgPath,
14150
+ stabilizeStroke,
14151
+ strokeOutline,
14152
+ strokeWidths,
14153
+ type StrokePoint,
14154
+ } from '@vielzeug/ink';
14155
+
14156
+ export let samples: StrokePoint[];
14157
+ $: d = (() => {
14158
+ const stabilized = stabilizeStroke(samples);
14159
+ return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });
14160
+ })();
14161
+
14162
+ ```
14163
+
14164
+ ## Working with Other Vielzeug Libraries
14165
+
14166
+ Gesture 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.
14167
+
14168
+ ```ts
14169
+ import { createDragGesture } from '@vielzeug/gesture';
14170
+ import { polylineToSvgPath, stabilizeStroke, type StrokePoint } from '@vielzeug/ink';
14171
+
14172
+ const samples: StrokePoint[] = [];
14173
+ const drag = createDragGesture(surface, {
14174
+ onMove: ({ currentX, currentY, event }) => samples.push({ time: event.timeStamp, x: currentX, y: currentY }),
14175
+ onEnd: () => {
14176
+ path.setAttribute('d', polylineToSvgPath(stabilizeStroke(samples), { precision: 1 }));
14177
+ },
14178
+ });
14179
+ ```
14180
+
14181
+ ## Best Practices
14182
+
14183
+ - Pass `time` on every sample (`PointerEvent.timeStamp` or `performance.now()`): without it, widths are pressure-only and speed information is thrown away.
14184
+ - Stabilize live, smooth once: run `stabilizeStroke()` per pointer move for a calm preview, and add `smoothStroke()` or `simplifyStroke()` at commit time.
14185
+ - Simplify outlines with a tolerance around `0.2`–`0.5` device pixels; larger tolerances visibly flatten caps.
14186
+ - Keep `precision` at `1`–`2` for display paths; raise it only when another tool re-processes the output.
14187
+ - Treat invalid options errors (`InkConfigError`) as programming bugs: they throw at call time with the offending option named.
14188
+ - Memoize per stroke in UI frameworks; the functions are pure and cheap to cache.
14189
+
14190
+ ### Examples
14191
+
14192
+ ## Examples
14193
+
14194
+ - [Jitter-Free Ink](./examples/jitter-free-ink.md)
14195
+
14196
+ ### REPL Examples
14197
+
14198
+ - stabilizeStroke - Jitter-free ink (id: `ink-smoothing`)
14199
+
14200
+ ---
14201
+
12982
14202
  ## @vielzeug/keymap
12983
14203
 
12984
14204
  **Category:** app-infrastructure
@@ -18633,6 +19853,423 @@ define('signup-form', {
18633
19853
 
18634
19854
  ---
18635
19855
 
19856
+ ## @vielzeug/palette
19857
+
19858
+ **Category:** utilities
19859
+
19860
+ ### Overview
19861
+
19862
+ ## Why Palette?
19863
+
19864
+ Design tools need color math that is correct where it matters — perceptual OKLab mixing, WCAG contrast, lossless extended-range conversions — without pulling in a color library that assumes a DOM, a canvas, or a particular color model.
19865
+
19866
+ ```ts
19867
+ // Before
19868
+ const mid = { r: (a.r + b.r) / 2, g: (a.g + b.g) / 2, b: (a.b + b.b) / 2 }; // gamma-space average, looks wrong
19869
+ const ratio = /* hand-rolled luminance, usually forgets the sRGB transfer function */;
19870
+
19871
+ // After
19872
+ import { contrastRatio, mix, parseColor, ramp } from '@vielzeug/palette';
19873
+
19874
+ const mid = mix(parseColor('#000000'), parseColor('#ffffff'), 0.5); // perceptual OKLab midpoint
19875
+ const ratio = contrastRatio(parseColor('#767676'), parseColor('#ffffff')); // 4.54
19876
+ const shades = ramp(parseColor('#3366cc'), { steps: 9 }); // OKLCH lightness ramp
19877
+ ```
19878
+
19879
+ | Feature | Palette | Ad-hoc color helpers |
19880
+ | --------------------------------------- | --------------------------------------------- | -------------------- |
19881
+ | Bundle size | | n/a |
19882
+ | Zero dependencies | | n/a |
19883
+ | CSS Color 4 `oklab()`/`oklch()` parsing | Built in | Manual |
19884
+ | CSS named colors | Built in | Manual |
19885
+ | OKLab mixing with premultiplied alpha | Built in, matches `color-mix(in oklab)` | Manual |
19886
+ | WCAG 2.x contrast | Built in | Manual |
19887
+ | Perceptual ramps | OKLCH lightness, gamut-fitted | Manual |
19888
+
19889
+ **Use Palette when** an application needs headless color parsing, conversion, mixing, or contrast checks with no DOM or rendering assumptions.
19890
+
19891
+ **Consider a rendering-layer color API when** the work is applying colors to a surface rather than computing them.
19892
+
19893
+ ## Installation
19894
+
19895
+ ```sh [pnpm]
19896
+ pnpm add @vielzeug/palette
19897
+ ```
19898
+
19899
+ ```sh [npm]
19900
+ npm install @vielzeug/palette
19901
+ ```
19902
+
19903
+ ```sh [yarn]
19904
+ yarn add @vielzeug/palette
19905
+ ```
19906
+
19907
+ ## Quick Start
19908
+
19909
+ ```ts
19910
+ import { mix, parseColor, ramp, readableOn, toHex } from '@vielzeug/palette';
19911
+
19912
+ const brand = parseColor('#3366cc');
19913
+ const surface = parseColor('rgb(248 250 252)');
19914
+
19915
+ const ink = readableOn(surface, [parseColor('#0f172a'), parseColor('#334155')]);
19916
+ const midpoint = mix(brand, surface, 0.5); // OKLab interpolation, like color-mix(in oklab)
19917
+ const shades = ramp(brand, { steps: 9 }); // OKLCH lightness ramp
19918
+
19919
+ console.log(toHex(ink ?? brand), toHex(midpoint), shades.map(toHex));
19920
+ ```
19921
+
19922
+ ## Features
19923
+
19924
+ - `parseColor()`: `#rgb`/`#rgba`/`#rrggbb`/`#rrggbbaa`, `rgb()`/`hsl()` comma and space syntax, CSS Color 4 `oklab()`/`oklch()`, and CSS named colors
19925
+ - `toHex()`, `toRgbString()`, `toHslString()`, `toOklchString()`: formatting with documented clamping at the display boundary
19926
+ - `srgbToOklch()` / `oklchToSrgb()`, `srgbToHsl()` / `hslToSrgb()`: lossless round-trippable conversions via the standard Björn Ottosson OKLab matrices
19927
+ - `isDisplayable()`: gamut test for any `Rgba` against sRGB
19928
+ - `mix()`: OKLab interpolation with premultiplied alpha, matching CSS `color-mix(in oklab)`
19929
+ - `contrastRatio()` and `relativeLuminance()`: WCAG 2.x ratios on clamped sRGB
19930
+ - `readableOn()`: picks the first candidate meeting the AA/AAA threshold, with large-text thresholds
19931
+ - `ramp()`: deterministic OKLCH lightness ramps that keep hue and stay inside the gamut
19932
+ - Typed errors: `PaletteParseError` and `PaletteConfigError` share the `PaletteError` base
19933
+ - Pure functions only: no DOM, no disposal contract, zero dependencies
19934
+
19935
+ ## Documentation
19936
+
19937
+ - [Usage Guide](./usage.md)
19938
+ - [API Reference](./api.md)
19939
+ - [Examples](./examples.md)
19940
+ - [Migration Guide](./migration.md)
19941
+
19942
+ ## See Also
19943
+
19944
+ - [Arsenal](/arsenal/): general-purpose utilities that complement headless color math.
19945
+ - [Refine](/refine/): components styled with design tokens that tools like this generate and check.
19946
+
19947
+ ### API Reference
19948
+
19949
+ ## API Overview
19950
+
19951
+ | Symbol | Purpose | Execution | Common gotcha |
19952
+ | --------------------- | -------------------------------------------- | --------- | ------------------------------------------------------- |
19953
+ | `parseColor()` | Parse a CSS color string into `Rgba` | Sync | `color()` is out of scope; named colors are supported |
19954
+ | `toHex()` | Format as `#rrggbb`/`#rrggbbaa` | Sync | Alpha is written when translucent unless `alpha: false` |
19955
+ | `toRgbString()` | Format as CSS `rgb()` space syntax | Sync | Channels are clamped to 0–255 |
19956
+ | `toHslString()` | Format as CSS `hsl()` space syntax | Sync | Channels are clamped before conversion |
19957
+ | `toOklchString()` | Format as CSS `oklch()` syntax | Sync | Writes true channels, even out of gamut |
19958
+ | `srgbToOklch()` | Convert sRGB to OKLCH | Sync | Round-trip drifts up to ±1 per channel |
19959
+ | `oklchToSrgb()` | Convert OKLCH to sRGB | Sync | Out-of-gamut channels stay unclamped, they do not throw |
19960
+ | `isDisplayable()` | Test an `Rgba` against the sRGB gamut | Sync | Allows a small rounding tolerance |
19961
+ | `srgbToHsl()` | Convert sRGB to HSL | Sync | `h` is 0–360, `s`/`l` are 0–100 |
19962
+ | `hslToSrgb()` | Convert HSL to sRGB | Sync | Hue wraps; channels beyond the gamut stay unclamped |
19963
+ | `mix()` | OKLab interpolation with premultiplied alpha | Sync | `t` outside `[0, 1]` throws `PaletteConfigError` |
19964
+ | `relativeLuminance()` | WCAG 2.x relative luminance | Sync | Computed on channels clamped to 0–255 |
19965
+ | `contrastRatio()` | WCAG 2.x contrast ratio (1–21) | Sync | Ignores alpha by design |
19966
+ | `readableOn()` | First candidate meeting a WCAG threshold | Sync | Returns `null` when nothing passes |
19967
+ | `ramp()` | OKLCH lightness ramp of a base color | Sync | `steps` must be an integer ≥ 2 |
19968
+
19969
+ ## Package Entry Point
19970
+
19971
+ | Import | Purpose |
19972
+ | ------------------- | --------------------------- |
19973
+ | `@vielzeug/palette` | Complete public Palette API |
19974
+
19975
+ ## Parsing
19976
+
19977
+ ### `parseColor()`
19978
+
19979
+ ```ts
19980
+ function parseColor(input: string): Rgba;
19981
+ ```
19982
+
19983
+ Parses `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`; `rgb()`/`rgba()` and `hsl()`/`hsla()` in comma and space syntax with optional `/ alpha`; `oklab()`/`oklch()` with alpha per CSS Color 4; and the CSS named colors (case-insensitive, including `transparent`). Percentage `oklab` `a`/`b` and `oklch` `c` map to ±0.4; percentage `rgb` channels map to 0–255. Alpha accepts a number or percentage and clamps to 0–1. Out-of-range channels are kept exactly — nothing clips. Throws `PaletteParseError` including the offending input.
19984
+
19985
+ ## Formatting
19986
+
19987
+ ### `toHex()`
19988
+
19989
+ ```ts
19990
+ function toHex(color: Rgba, options?: FormatOptions): string;
19991
+ ```
19992
+
19993
+ Formats as `#rrggbb`, or `#rrggbbaa` when the color is translucent or `options.alpha` is `true`. Channels clamp to 0–255 and alpha to 0–1.
19994
+
19995
+ ### `toRgbString()`
19996
+
19997
+ ```ts
19998
+ function toRgbString(color: Rgba, options?: FormatOptions): string;
19999
+ ```
20000
+
20001
+ Formats as `rgb(r g b)` or `rgb(r g b / a)` space syntax. Same clamping as `toHex()`.
20002
+
20003
+ ### `toHslString()`
20004
+
20005
+ ```ts
20006
+ function toHslString(color: Rgba, options?: FormatOptions): string;
20007
+ ```
20008
+
20009
+ Formats as `hsl(h s% l%)` or `hsl(h s% l% / a)`. Channels clamp before conversion.
20010
+
20011
+ ### `toOklchString()`
20012
+
20013
+ ```ts
20014
+ function toOklchString(color: Rgba, options?: FormatOptions): string;
20015
+ ```
20016
+
20017
+ Formats as `oklch(l% c h)` or `oklch(l% c h / a)` on the color's true channels — an out-of-gamut color keeps its exact OKLCH values rather than the clamped ones.
20018
+
20019
+ ## Conversion
20020
+
20021
+ ### `srgbToOklch()` / `oklchToSrgb()`
20022
+
20023
+ ```ts
20024
+ function srgbToOklch(color: Rgba): Oklch;
20025
+ function oklchToSrgb(color: Oklch): Rgba;
20026
+ ```
20027
+
20028
+ Standard sRGB → linear → OKLab → OKLCH pipeline (Björn Ottosson's matrices with the sRGB transfer function, sign-extended to negative channels per CSS Color 4). The pipeline is lossless: `oklchToSrgb()` leaves out-of-gamut channels outside 0–255 instead of clipping, so `srgbToOklch()` recovers the original OKLCH values.
20029
+
20030
+ ### `isDisplayable()`
20031
+
20032
+ ```ts
20033
+ function isDisplayable(color: Rgba): boolean;
20034
+ ```
20035
+
20036
+ True when every linear-light channel of `color` falls inside `[0, 1]` (within a `0.00015` rounding tolerance, matching CSS Color 4 implementations). Works on any `Rgba` — parsed, converted, or mixed — so it detects out-of-gamut colors before a formatter clamps them.
20037
+
20038
+ ### `srgbToHsl()` / `hslToSrgb()`
20039
+
20040
+ ```ts
20041
+ function srgbToHsl(color: Rgba): Hsla;
20042
+ function hslToSrgb(color: Hsla): Rgba;
20043
+ ```
20044
+
20045
+ `h` is degrees in `[0, 360)`, `s` and `l` are percentages 0–100. `hslToSrgb()` wraps hue and leaves channels outside 0–255 unclamped (an `l` beyond 100% produces values beyond 255).
20046
+
20047
+ ## Mixing
20048
+
20049
+ ### `mix()`
20050
+
20051
+ ```ts
20052
+ function mix(a: Rgba, b: Rgba, t: number): Rgba;
20053
+ ```
20054
+
20055
+ Interpolates in OKLab with premultiplied alpha, matching CSS `color-mix(in oklab, ...)`. `t` is 0 for `a`, 1 for `b`; outside `[0, 1]` throws `PaletteConfigError`. A fully transparent endpoint contributes no color: mixing red with `rgba(0 0 0 / 0)` yields red at half alpha, not a darkened blend.
20056
+
20057
+ ## Contrast
20058
+
20059
+ ### `relativeLuminance()`
20060
+
20061
+ ```ts
20062
+ function relativeLuminance(color: Rgba): number;
20063
+ ```
20064
+
20065
+ WCAG 2.x relative luminance on channels clamped to 0–255.
20066
+
20067
+ ### `contrastRatio()`
20068
+
20069
+ ```ts
20070
+ function contrastRatio(a: Rgba, b: Rgba): number;
20071
+ ```
20072
+
20073
+ WCAG 2.x contrast ratio: 1 for identical colors, 21 for black on white. Symmetric in its arguments.
20074
+
20075
+ ### `readableOn()`
20076
+
20077
+ ```ts
20078
+ function readableOn(background: Rgba, candidates: readonly Rgba[], options?: ReadableOnOptions): Rgba | null;
20079
+ ```
20080
+
20081
+ Returns the first candidate whose contrast against `background` reaches the threshold: 4.5 (`level: 'AA'`, default) or 7 (`'AAA'`), or 3 / 4.5 with `large: true`. Returns `null` when no candidate passes.
20082
+
20083
+ ## Ramps
20084
+
20085
+ ### `ramp()`
20086
+
20087
+ ```ts
20088
+ function ramp(base: Rgba, options: RampOptions): Rgba[];
20089
+ ```
20090
+
20091
+ Builds `steps` swatches dark to light by interpolating OKLab lightness between `minLightness` (default 0.15) and `maxLightness` (default 0.95) while keeping the base color's hue. Where a swatch would fall outside the sRGB gamut, its chroma is reduced (binary search at fixed lightness and hue) until it fits — so every swatch is displayable and the hue stays stable instead of shifting under clamping. Deterministic. Throws `PaletteConfigError` for non-integer or sub-2 `steps`, bounds outside `[0, 1]`, or `minLightness > maxLightness`.
20092
+
20093
+ ## Types
20094
+
20095
+ ### `Rgba`
20096
+
20097
+ ```ts
20098
+ type Rgba = Readonly;
20099
+ ```
20100
+
20101
+ Extended-range sRGB: `r`/`g`/`b` are 0–255 for displayable colors but may fall outside that range when a color came from an out-of-gamut OKLCH/HSL value or out-of-range channels — the conversion pipeline never clips. `a` is always 0–1. Use `isDisplayable()` to test the gamut and the formatters (which clamp) for display-safe output.
20102
+
20103
+ ### `Hsla`
20104
+
20105
+ ```ts
20106
+ type Hsla = Readonly;
20107
+ ```
20108
+
20109
+ `h` is degrees 0–360, `s` and `l` are percentages 0–100, `a` is 0–1.
20110
+
20111
+ ### `Oklch`
20112
+
20113
+ ```ts
20114
+ type Oklch = Readonly;
20115
+ ```
20116
+
20117
+ `l` is lightness 0–1, `c` is chroma, `h` is hue in degrees, `a` is alpha 0–1. OKLab is the internal waypoint between sRGB and OKLCH and is not part of the public surface.
20118
+
20119
+ ### `FormatOptions`
20120
+
20121
+ ```ts
20122
+ type FormatOptions = Readonly;
20123
+ ```
20124
+
20125
+ When `alpha` is `true` the alpha channel is always written; otherwise it is written only when the color is translucent.
20126
+
20127
+ ### `ReadableOnOptions`
20128
+
20129
+ ```ts
20130
+ type ReadableOnOptions = Readonly;
20131
+ ```
20132
+
20133
+ ### `RampOptions`
20134
+
20135
+ ```ts
20136
+ type RampOptions = Readonly;
20137
+ ```
20138
+
20139
+ ## Errors
20140
+
20141
+ | Error | Thrown by | Meaning |
20142
+ | -------------------- | ----------------- | ----------------------------------------------------------------------------------- |
20143
+ | `PaletteParseError` | `parseColor()` | Input did not match the supported grammar; the message includes the offending input |
20144
+ | `PaletteConfigError` | `mix()`, `ramp()` | Invalid options or positions |
20145
+
20146
+ Both extend `PaletteError`, so `catch (error) { if (error instanceof PaletteError) ... }` narrows both.
20147
+
20148
+ ### Usage Guide
20149
+
20150
+ ## Basic Usage
20151
+
20152
+ ```ts
20153
+ import { parseColor, toHex } from '@vielzeug/palette';
20154
+
20155
+ const brand = parseColor('#3366cc'); // { r: 51, g: 102, b: 204, a: 1 }
20156
+ console.log(toHex(brand)); // "#3366cc"
20157
+ ```
20158
+
20159
+ `parseColor()` accepts hex (3, 4, 6, and 8 digits), `rgb()`/`rgba()` and `hsl()`/`hsla()` in both comma and space syntax, CSS Color 4 `oklab()`/`oklch()`, and the CSS named colors (case-insensitive, including `transparent`). Anything else throws `PaletteParseError` with the offending input in the message. The `color()` notation is out of scope.
20160
+
20161
+ ## Parse CSS Colors
20162
+
20163
+ ```ts
20164
+ import { parseColor } from '@vielzeug/palette';
20165
+
20166
+ parseColor('#f09'); // #rgb: digits are duplicated
20167
+ parseColor('#f098'); // #rgba
20168
+ parseColor('rgb(1, 2, 3)'); // comma syntax
20169
+ parseColor('rgba(1, 2, 3, 0.5)'); // legacy comma alpha
20170
+ parseColor('rgb(1 2 3 / 0.5)'); // space syntax with slash alpha
20171
+ parseColor('rgb(50% 25% 0%)'); // percentages map to 0–255
20172
+ parseColor('hsl(120, 100%, 50%)'); // hue wraps: -120 and 480 are valid
20173
+ parseColor('oklab(0.5 -0.1 0.1 / 0.5)'); // CSS Color 4
20174
+ parseColor('oklch(50% 0.1 240deg)'); // percent lightness, deg hue
20175
+ parseColor('RebeccaPurple'); // named colors, any case
20176
+ parseColor('transparent'); // { r: 0, g: 0, b: 0, a: 0 }
20177
+ ```
20178
+
20179
+ Percentage `oklab` `a`/`b` and `oklch` `c` map to the CSS Color 4 range of ±0.4. Alpha accepts a number or a percentage and is clamped to 0–1. Out-of-range channels (`rgb(300 0 0)`) are kept exactly — parsing never clips.
20180
+
20181
+ ## Convert Between Color Spaces
20182
+
20183
+ ```ts
20184
+ import { hslToSrgb, oklchToSrgb, parseColor, srgbToHsl, srgbToOklch } from '@vielzeug/palette';
20185
+
20186
+ const red = parseColor('#ff0000');
20187
+ const oklch = srgbToOklch(red); // { l: 0.628, c: 0.2577, h: 29.23, a: 1 }
20188
+ const hsl = srgbToHsl(red); // { h: 0, s: 100, l: 50, a: 1 }
20189
+
20190
+ const back = oklchToSrgb(oklch); // round-trips within ±1 per channel
20191
+ ```
20192
+
20193
+ Conversions use the standard sRGB → linear → OKLab → OKLCH pipeline (Björn Ottosson's matrices, sRGB transfer function sign-extended per CSS Color 4). The pipeline is lossless: `oklchToSrgb()` leaves out-of-gamut channels outside 0–255, so `srgbToOklch()` recovers the original values, and `isDisplayable()` tells you whether a color fits the screen.
20194
+
20195
+ ## Format Colors
20196
+
20197
+ ```ts
20198
+ import { parseColor, toHex, toHslString, toOklchString, toRgbString } from '@vielzeug/palette';
20199
+
20200
+ const translucent = parseColor('rgb(222 173 190 / 0.5)');
20201
+ toHex(translucent); // "#deadbe80" — alpha is written when the color is translucent
20202
+ toHex(translucent, { alpha: false }); // "#deadbe" — never write alpha...
20203
+ toHex(parseColor('#deadbeef'), { alpha: true }); // "#deadbeff" — ...or always write it
20204
+ toRgbString(translucent); // "rgb(222 173 190 / 0.5)"
20205
+ toHslString(parseColor('#ff0000')); // "hsl(0 100% 50%)"
20206
+ toOklchString(parseColor('#ff0000')); // "oklch(62.8% 0.2577 29.23)"
20207
+ ```
20208
+
20209
+ `toHex()`, `toRgbString()`, and `toHslString()` clamp out-of-gamut channels to 0–255 and alpha to 0–1 before writing, so their output is always display-safe. A color produced by `parseColor('rgb(300 0 0)')` keeps its out-of-range channel until formatted, where it clamps to `255`. `toOklchString()` writes the color's true OKLCH values — an out-of-gamut color round-trips through `parseColor()` exactly.
20210
+
20211
+ ## Mix in OKLab
20212
+
20213
+ ```ts
20214
+ import { mix, parseColor, toHex } from '@vielzeug/palette';
20215
+
20216
+ const mid = mix(parseColor('#000000'), parseColor('#ffffff'), 0.5);
20217
+ toHex(mid); // "#636363" — the perceptual midpoint, not #808080
20218
+
20219
+ const hover = mix(parseColor('#ff0000'), parseColor('rgb(0 0 0 / 0)'), 0.5);
20220
+ toHex(hover); // "#ff000080" — transparent endpoints don't darken
20221
+ ```
20222
+
20223
+ `mix()` interpolates in OKLab with premultiplied alpha, matching CSS `color-mix(in oklab, ...)`: midpoints are perceptually even, and a transparent endpoint contributes no color instead of pulling the blend toward black. A `t` outside `[0, 1]` throws `PaletteConfigError`.
20224
+
20225
+ ## Check Contrast
20226
+
20227
+ ```ts
20228
+ import { contrastRatio, parseColor, readableOn } from '@vielzeug/palette';
20229
+
20230
+ contrastRatio(parseColor('#000000'), parseColor('#ffffff')); // 21
20231
+ contrastRatio(parseColor('#767676'), parseColor('#ffffff')); // ≈ 4.54 (AA boundary)
20232
+
20233
+ const ink = readableOn(parseColor('#f8fafc'), [parseColor('#94a3b8'), parseColor('#0f172a')]);
20234
+ // → #0f172a: the first candidate that reaches the threshold
20235
+ ```
20236
+
20237
+ `contrastRatio()` uses WCAG 2.x relative luminance on channels clamped to 0–255. `readableOn()` picks the first candidate meeting 4.5 (AA) or 7 (AAA), or 3 / 4.5 with `{ large: true }`, and returns `null` when nothing passes.
20238
+
20239
+ ## Build Lightness Ramps
20240
+
20241
+ ```ts
20242
+ import { parseColor, ramp, toHex } from '@vielzeug/palette';
20243
+
20244
+ const shades = ramp(parseColor('#3366cc'), { steps: 9 });
20245
+ console.log(shades.map(toHex)); // nine swatches, dark to light
20246
+ ```
20247
+
20248
+ `ramp()` interpolates OKLab lightness between `minLightness` (default 0.15) and `maxLightness` (default 0.95) at the base color's hue. Where a swatch would leave the sRGB gamut, its chroma is reduced until it fits — every swatch is displayable and the hue never shifts under clamping. The result is deterministic and runs dark to light. Invalid `steps` or lightness bounds throw `PaletteConfigError`.
20249
+
20250
+ ## Errors
20251
+
20252
+ All failures are `PaletteError` subclasses: `PaletteParseError` for malformed input and `PaletteConfigError` for invalid options. Catch the base class to handle both.
20253
+
20254
+ ## Best Practices
20255
+
20256
+ - Parse once at the boundary, keep `Rgba` values, and format at the edges; conversions are cheap but parsing strings repeatedly is wasteful.
20257
+ - Use `mix()` instead of averaging channels — gamma-space averages look muddy.
20258
+ - Use `ramp()` for tonal scales and `readableOn()` for ink selection instead of hand-tuned hex pairs.
20259
+ - Keep out-of-gamut colors in the pipeline as long as you like — conversions are lossless. Check `isDisplayable()` before handing a color to something that can't represent it, and let the formatters clamp at the display boundary.
20260
+
20261
+ ### Examples
20262
+
20263
+ ## Examples
20264
+
20265
+ - [Parse, Mix and Contrast](./examples/parse-mix-and-contrast.md)
20266
+
20267
+ ### REPL Examples
20268
+
20269
+ - Basics - parse, mix, contrast, ramp (id: `palette-basic`)
20270
+
20271
+ ---
20272
+
18636
20273
  ## @vielzeug/patchwork
18637
20274
 
18638
20275
  **Category:** utilities
@@ -20142,7 +21779,7 @@ chart.dispose();
20142
21779
  | Feature | Prism | Hand-written SVG |
20143
21780
  | ------------------ | ---------------------------------------------------------------- | -------------------------------------------- |
20144
21781
  | Bundle size | | No chart package |
20145
- | Zero dependencies | (uses Orbit) | |
21782
+ | Zero dependencies | (uses Orbit, Palette) | |
20146
21783
  | Data updates | `ChartHandle.update()` replaces chart data | You implement the update path |
20147
21784
  | Responsive sizing | `ResizeObserver` recalculates the chart layout | You implement the resize behavior |
20148
21785
  | Chart interactions | Built-in pointer and keyboard interactions on supported charts | You implement them |
@@ -33264,6 +34901,361 @@ const profile = Profile.parse(await courier.get('/profile'));
33264
34901
 
33265
34902
  ---
33266
34903
 
34904
+ ## @vielzeug/stage
34905
+
34906
+ **Category:** utilities
34907
+
34908
+ ### Overview
34909
+
34910
+ ## Why Stage?
34911
+
34912
+ A `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.
34913
+
34914
+ ## Installation
34915
+
34916
+ ```sh [pnpm]
34917
+ pnpm add @vielzeug/stage
34918
+ ```
34919
+
34920
+ ```sh [npm]
34921
+ npm install @vielzeug/stage
34922
+ ```
34923
+
34924
+ ```sh [yarn]
34925
+ yarn add @vielzeug/stage
34926
+ ```
34927
+
34928
+ ## Quick Start
34929
+
34930
+ ```ts
34931
+ import { createStage } from '@vielzeug/stage';
34932
+
34933
+ const stage = createStage(canvas, {
34934
+ dpr: window.devicePixelRatio,
34935
+ height: 600,
34936
+ layers: [
34937
+ { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },
34938
+ { id: 'tokens', paint: (ctx) => drawTokens(ctx) },
34939
+ ],
34940
+ width: 800,
34941
+ });
34942
+
34943
+ stage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen; DPR applied on top
34944
+ token.x += 10;
34945
+ stage.invalidate('tokens'); // only the tokens layer repaints
34946
+ ```
34947
+
34948
+ ## Features
34949
+
34950
+ - **`createStage()`**: layered retained-mode renderer with cached per-layer surfaces
34951
+ - **Dirty repaints**: invalidate one layer or all; frames coalesce via an injectable scheduler
34952
+ - **DPR-aware transforms**: paint in world units, the stage scales by `dpr × matrix`
34953
+ - **`StageController`**: one control type shared by main-thread and worker stages
34954
+ - **`toBlob()`**: PNG export of the composited canvas, flushing pending frames, with typed unsupported-capability errors
34955
+ - **Injectable surfaces**: `createSurface` factory for tests and `OffscreenCanvas` workers
34956
+ - **`@vielzeug/stage/worker`**: worker-rendered stages via a transferred `OffscreenCanvas` and a typed scene channel
34957
+
34958
+ ## Documentation
34959
+
34960
+ - [Usage Guide](./usage.md)
34961
+ - [API Reference](./api.md)
34962
+ - [Examples](./examples.md)
34963
+
34964
+ ## See Also
34965
+
34966
+ - [Atlas](/atlas/): cameras, spatial index, and tile grids that feed Stage transforms.
34967
+ - [Gesture](/gesture/): pointer drag, pinch, and wheel recognition.
34968
+
34969
+ ### API Reference
34970
+
34971
+ ## API Overview
34972
+
34973
+ | Symbol | Purpose | Execution | Common gotcha |
34974
+ | ----------------------- | ------------------------------------------------------- | --------- | ----------------------------------------------------------------- |
34975
+ | `createStage()` | Retained-mode layered canvas renderer | Sync | Paint callbacks draw in world units; the stage applies the matrix |
34976
+ | `StageController` | Control surface shared by main-thread and worker stages | Type | Both modes are assignable to it; mode extras are not |
34977
+ | `StageError` | Base class for all stage errors | Sync | Narrow with `instanceof StageError` |
34978
+ | `StageConfigError` | Invalid sizes, duplicate/unknown layer ids | Sync | Thrown at call time, in both modes |
34979
+ | `StageDisposedError` | Blob export or worker request after disposal | Sync | Worker blob failures carry a `kind` mapped to this class |
34980
+ | `StageUnsupportedError` | Missing browser capability (2D context, blob export) | Sync | No silent degradation to a lesser path |
34981
+
34982
+ ## Package Entry Point
34983
+
34984
+ | Import | Purpose |
34985
+ | ------------------------ | ------------------------------------------------- |
34986
+ | `@vielzeug/stage` | Stage factory, controller type, and error classes |
34987
+ | `@vielzeug/stage/worker` | Worker-rendered stages over `OffscreenCanvas` |
34988
+
34989
+ Geometry is not re-declared here: `Point`, `Rect`, `Matrix`, and `FrameScheduler` come from
34990
+ [`@vielzeug/atlas`](/atlas/api/), which `@vielzeug/stage` depends on.
34991
+
34992
+ ---
34993
+
34994
+ ## Core Types
34995
+
34996
+ ```ts
34997
+ import type { FrameScheduler, Matrix, Rect, Size } from '@vielzeug/atlas';
34998
+
34999
+ type PaintContext = Readonly;
35000
+
35001
+ /** A backing surface a layer paints into. `OffscreenCanvas` on workers. */
35002
+ type StageSurface = {
35003
+ width: number;
35004
+ height: number;
35005
+ getContext: (type: '2d', attributes?: CanvasRenderingContext2DSettings) => unknown;
35006
+ };
35007
+ type CreateSurface = (width: number, height: number) => StageSurface;
35008
+
35009
+ /**
35010
+ * The control surface both stage modes share. A main-thread `Stage` and a
35011
+ * `WorkerStage` are interchangeable wherever only control is needed.
35012
+ */
35013
+ type StageController = Readonly void;
35014
+ setTransform: (matrix: Matrix) => void;
35015
+ invalidate: (layerId?: string) => void;
35016
+ toBlob: (options?: { type?: string; quality?: number }) => Promise;
35017
+ dispose: () => void;
35018
+ readonly disposed: boolean;
35019
+ readonly disposalSignal: AbortSignal;
35020
+ [Symbol.dispose]: () => void;
35021
+ }>;
35022
+ ```
35023
+
35024
+ `Size` comes from [`@vielzeug/atlas`](/atlas/api/) as well.
35025
+
35026
+ ---
35027
+
35028
+ ## `createStage()`
35029
+
35030
+ ```ts
35031
+ function createStage(
35032
+ canvas: HTMLCanvasElement | OffscreenCanvas,
35033
+ options: StageOptions & Readonly,
35034
+ ): Stage;
35035
+ ```
35036
+
35037
+ Creates 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`.
35038
+
35039
+ | Parameter | Type | Description |
35040
+ | ----------------------- | -------------------------------------- | ---------------------------------------------------------------------- |
35041
+ | `canvas` | `HTMLCanvasElement \| OffscreenCanvas` | Canvas the stage composites into (visible or transferred) |
35042
+ | `options.width` | `number` | CSS width in pixels; must be positive and finite |
35043
+ | `options.height` | `number` | CSS height in pixels; must be positive and finite |
35044
+ | `options.dpr` | `number?` | Device pixel ratio; defaults to `1` |
35045
+ | `options.layers` | `readonly StageLayerOptions[]` | Layers in paint order, fixed at creation; duplicate ids throw |
35046
+ | `options.scheduler` | `FrameScheduler?` | Injectable rAF scheduler for deterministic tests |
35047
+ | `options.createSurface` | `CreateSurface?` | Backing-surface factory; defaults to `OffscreenCanvas`/document canvas |
35048
+ | `options.background` | `string \| null?` | Color cleared under the layers; defaults to transparent |
35049
+
35050
+ **Returns:** `Stage` handle.
35051
+
35052
+ **Example**
35053
+
35054
+ ```ts
35055
+ const stage = createStage(canvas, {
35056
+ width: 800,
35057
+ height: 600,
35058
+ dpr: window.devicePixelRatio,
35059
+ layers: [{ id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) }],
35060
+ });
35061
+ stage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen, CSS pixels
35062
+ stage.invalidate('scene');
35063
+ ```
35064
+
35065
+ ### `Stage` members
35066
+
35067
+ `Stage` extends `StageController` (`resize`, `setTransform`, `invalidate`, `toBlob`, `dispose`, `disposed`, `disposalSignal`, `[Symbol.dispose]`) and adds:
35068
+
35069
+ | Member | Description |
35070
+ | -------------------------------------------- | -------------------------------------------------------------------------------------- |
35071
+ | `render(time?)` | Runs the pending repaint/composite synchronously; `time` defaults to `scheduler.now()` |
35072
+ | `visibleRect` | Visible world-space rect derived from the inverse transform |
35073
+ | `matrix`, `width`, `height`, `dpr`, `canvas` | Current configuration |
35074
+
35075
+ `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.
35076
+
35077
+ ---
35078
+
35079
+ ## Worker Subpath (`@vielzeug/stage/worker`)
35080
+
35081
+ | Export | Description |
35082
+ | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
35083
+ | `createWorkerStage(canvas, worker, options)` | Main-thread client: transfers `canvas` to `worker` once, then drives it; a `StageController` plus `ready` and `sendScene(scene: Scene)` |
35084
+ | `serveStage(scope, setup)` | Worker half: waits for `init`, creates a `createStage` on the transferred `OffscreenCanvas`, and services commands; `setup` returns `{ layers, onScene?, onDispose? }` |
35085
+ | `WorkerScope`, `WorkerSelfScope`, `WorkerStage`, `WorkerStageOptions`, `ServeStageSetup`, `StageServer` | Supporting types for both halves |
35086
+
35087
+ The 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.
35088
+
35089
+ `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.
35090
+
35091
+ `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.
35092
+
35093
+ ## Errors
35094
+
35095
+ | Class | Thrown when |
35096
+ | ----------------------- | ----------------------------------------------------------------- |
35097
+ | `StageError` | Base class; catch all stage failures with `instanceof` |
35098
+ | `StageConfigError` | Non-positive sizes, non-finite matrices, duplicate/unknown ids |
35099
+ | `StageDisposedError` | `toBlob()` after `dispose()`, or worker blob rejected on disposal |
35100
+ | `StageUnsupportedError` | No 2D context on a surface, or `canvas.toBlob` missing/failing |
35101
+
35102
+ ### Usage Guide
35103
+
35104
+ ## Basic Usage
35105
+
35106
+ ```ts
35107
+ import { createStage } from '@vielzeug/stage';
35108
+
35109
+ const stage = createStage(canvas, {
35110
+ width: canvas.clientWidth,
35111
+ height: canvas.clientHeight,
35112
+ dpr: window.devicePixelRatio,
35113
+ layers: [
35114
+ { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },
35115
+ { id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) },
35116
+ { id: 'overlay', paint: (ctx) => drawSelection(ctx) },
35117
+ ],
35118
+ });
35119
+ ```
35120
+
35121
+ Each 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`.
35122
+
35123
+ Layers 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`).
35124
+
35125
+ ## Driving the Transform
35126
+
35127
+ The stage takes a world→screen matrix in CSS pixels (it applies DPR itself). Pair it with an `@vielzeug/atlas` camera:
35128
+
35129
+ ```ts
35130
+ import { createCamera } from '@vielzeug/atlas';
35131
+
35132
+ const camera = createCamera({ maxZoom: 16, minZoom: 0.05 });
35133
+ camera.subscribe(() => stage.setTransform(camera.matrix));
35134
+
35135
+ canvas.addEventListener('wheel', (event) => {
35136
+ event.preventDefault();
35137
+ camera.zoomAt({ x: event.offsetX, y: event.offsetY }, Math.exp(-event.deltaY * 0.0015));
35138
+ });
35139
+ ```
35140
+
35141
+ `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.
35142
+
35143
+ ## Dirty Repaints
35144
+
35145
+ Invalidate the smallest unit that changed:
35146
+
35147
+ ```ts
35148
+ token.x += 10;
35149
+ stage.invalidate('tokens'); // only the tokens layer repaints next frame
35150
+ ```
35151
+
35152
+ Invalidations within one frame coalesce into a single scheduled frame. Call `stage.render()` to force a synchronous repaint (useful in tests).
35153
+
35154
+ ## Resize and DPR Changes
35155
+
35156
+ ```ts
35157
+ new ResizeObserver(([entry]) => {
35158
+ stage.resize({ width: entry.contentRect.width, height: entry.contentRect.height }, window.devicePixelRatio);
35159
+ }).observe(canvas.parentElement!);
35160
+ ```
35161
+
35162
+ `resize()` resizes the canvas backing store and invalidates all layers; surfaces are reallocated at the new pixel size.
35163
+
35164
+ ## Exporting a PNG
35165
+
35166
+ ```ts
35167
+ const blob = await stage.toBlob();
35168
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
35169
+ ```
35170
+
35171
+ `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.
35172
+
35173
+ ## Testing with Injected Surfaces
35174
+
35175
+ Inject a fake surface factory and scheduler to unit-test paint behaviour without a GPU:
35176
+
35177
+ ```ts
35178
+ const frames = { queued: new Set void>() };
35179
+ const stage = createStage(fakeCanvas, {
35180
+ createSurface: (w, h) => fakeSurface(w, h),
35181
+ height: 200,
35182
+ scheduler: {
35183
+ cancelFrame: (id) => frames.queued.delete(id),
35184
+ now: () => 0,
35185
+ requestFrame: (cb) => {
35186
+ frames.queued.add(cb);
35187
+ return frames.queued.size;
35188
+ },
35189
+ },
35190
+ width: 400,
35191
+ });
35192
+ ```
35193
+
35194
+ The default factory uses `OffscreenCanvas` when present, else a canvas from the document; in environments with neither, it throws `StageUnsupportedError`.
35195
+
35196
+ ## Worker Rendering
35197
+
35198
+ The `@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.
35199
+
35200
+ ```ts
35201
+ // main.ts
35202
+ import { createWorkerStage } from '@vielzeug/stage/worker';
35203
+
35204
+ type Scene = Readonly;
35205
+
35206
+ const worker = new Worker(new URL('./stage.worker.ts', import.meta.url), { type: 'module' });
35207
+ const stage = createWorkerStage(canvas, worker, {
35208
+ height: 600,
35209
+ width: 800,
35210
+ });
35211
+ // The creator owns the worker: terminate it when the stage is disposed.
35212
+ stage.disposalSignal.addEventListener('abort', () => worker.terminate());
35213
+
35214
+ await stage.ready; // the worker created its stage
35215
+ stage.setTransform([1, 0, 0, 1, 0, 0]);
35216
+ stage.sendScene({ col: 3, id: 'hero', row: 2, type: 'move' });
35217
+ const blob = await stage.toBlob({ type: 'image/png' }); // correlated round-trip
35218
+ stage.dispose(); // also rejects any in-flight blob requests
35219
+ ```
35220
+
35221
+ ```ts
35222
+ // stage.worker.ts
35223
+ import { serveStage } from '@vielzeug/stage/worker';
35224
+
35225
+ serveStage(self, () => ({
35226
+ layers: [{ id: 'scene', paint: (ctx) => ctx.fillRect(0, 0, 800, 600) }],
35227
+ onScene: (scene, stage) => {
35228
+ applyMove(scene);
35229
+ stage.invalidate('scene'); // the handler owns repaints
35230
+ },
35231
+ }));
35232
+ ```
35233
+
35234
+ Notes:
35235
+
35236
+ - The worker owns its painters. `serveStage`'s `setup` returns the `layers` (and optional `onScene`/`onDispose` hooks); the main thread never names layers.
35237
+ - The canvas transfer is **one-shot**: `createWorkerStage` calls `transferControlToOffscreen()` on construction. To go back to main-thread rendering, mount a fresh `` element.
35238
+ - `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.
35239
+ - `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.
35240
+ - Invalid size, DPR, or matrix input throws `StageConfigError` on the main thread, exactly like `createStage`.
35241
+ - 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.
35242
+
35243
+ ## Best Practices
35244
+
35245
+ - 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.
35246
+ - Put rarely-changing content (tile grids, backgrounds) on lower layers so pointer-driven changes only repaint upper layers.
35247
+ - Dispose the stage when the view unmounts: `using stage = createStage(...)` or `stage.dispose()`. Disposal cancels scheduled frames and releases every backing surface.
35248
+ - Treat `StageUnsupportedError` as a hard capability gap (feature-detect or surface it to the user); there is deliberately no fallback path.
35249
+ - In worker mode, invalidate only the layers a scene message changed — `onScene` runs on every forwarded payload.
35250
+
35251
+ ### Examples
35252
+
35253
+ ## Examples
35254
+
35255
+ - [Layered Repaints](./examples/layered-repaints.md)
35256
+
35257
+ ---
35258
+
33267
35259
  ## @vielzeug/tabula
33268
35260
 
33269
35261
  **Category:** utilities
@@ -38358,3 +40350,361 @@ router.subscribe((state) => {
38358
40350
  - Query Parameters: Coercion and URL State (id: `query-params`)
38359
40351
  - Route Context: Full Context Access (id: `route-context`)
38360
40352
  - URL Building: Path Matching and Active State (id: `url-building`)
40353
+
40354
+ ---
40355
+
40356
+ ## @vielzeug/wire
40357
+
40358
+ **Category:** utilities
40359
+
40360
+ ### Overview
40361
+
40362
+ ## Why Wire?
40363
+
40364
+ Node editors always rediscover the same hard parts: wires that route _around_ nodes instead of through them, bend counts that change every frame, and ordering or cycle checks that recurse until the stack dies on a big graph. Wire computes all of it as pure functions: cubic bezier geometry anchored to port sides, A\* Manhattan routes over a padded-obstacle visibility graph with a per-bend penalty, input-order-stable topological sorting, and Tarjan SCC cycle detection — iterative, so 50,000-node chains are fine.
40365
+
40366
+ ```ts
40367
+ // Before
40368
+ // Straight lines through nodes, hand-rolled A* with nondeterministic tie
40369
+ // breaks, and recursive DFS that stack-overflows on deep graphs.
40370
+
40371
+ // After
40372
+ import { bezierRoute, findCyclicGroups, orthogonalRoute, topologicalOrder } from '@vielzeug/wire';
40373
+
40374
+ const curve = bezierRoute({ side: 'right', x: 100, y: 40 }, { side: 'left', x: 320, y: 120 });
40375
+
40376
+ // Pass every node bound; the router exempts each port's own node for its exit.
40377
+ const waypoints = orthogonalRoute(fromPort, toPort, { obstacles: nodeBounds });
40378
+ // waypoints is null when every route is blocked — render a dashed fallback.
40379
+ ```
40380
+
40381
+ | Feature | Wire | Ad-hoc routing | Graph libraries |
40382
+ | ---------------------------- | -------------------------------------------- | -------------- | ------------------ |
40383
+ | Bundle size | | n/a | Typically 10–80 kB |
40384
+ | External dependencies | | n/a | Varies |
40385
+ | Obstacle-avoiding orthogonal | Built in (A\* + bend penalty) | Rare | Sometimes |
40386
+ | Deterministic output | | Rare | Varies |
40387
+ | Iterative cycle detection | | Recursive DFS | Varies |
40388
+ | Headless: no DOM or renderer | | Varies | Usually coupled |
40389
+
40390
+ **Use Wire when** you own the node layout and rendering but want production-grade edge geometry and graph ordering as pure functions.
40391
+
40392
+ **Consider a graph-drawing library when** you also want automatic layout (dagre-style ranking, force simulation) — Wire routes the edges you place, it does not place the nodes.
40393
+
40394
+ ## Installation
40395
+
40396
+ ```sh [pnpm]
40397
+ pnpm add @vielzeug/wire
40398
+ ```
40399
+
40400
+ ```sh [npm]
40401
+ npm install @vielzeug/wire
40402
+ ```
40403
+
40404
+ ```sh [yarn]
40405
+ yarn add @vielzeug/wire
40406
+ ```
40407
+
40408
+ ## Quick Start
40409
+
40410
+ ```ts
40411
+ import { bezierRoute, bezierToSvgPath, findCyclicGroups, orthogonalRoute, topologicalOrder } from '@vielzeug/wire';
40412
+
40413
+ // Curved wire from a right-facing port to a left-facing port.
40414
+ const curve = bezierRoute({ side: 'right', x: 100, y: 40 }, { side: 'left', x: 320, y: 120 });
40415
+ const d = bezierToSvgPath(curve); // or draw curve.c1/curve.c2 on a canvas
40416
+
40417
+ // Manhattan wire that avoids the node boxes.
40418
+ const points = orthogonalRoute(
40419
+ { side: 'right', x: 100, y: 40 },
40420
+ { side: 'left', x: 320, y: 120 },
40421
+ { obstacles: nodeBounds },
40422
+ );
40423
+
40424
+ // Execution order and cycles for a validation pass.
40425
+ const order = topologicalOrder(
40426
+ ['b', 'a', 'c'],
40427
+ [
40428
+ { from: 'a', to: 'b' },
40429
+ { from: 'b', to: 'c' },
40430
+ ],
40431
+ );
40432
+ const groups = findCyclicGroups(
40433
+ ['a', 'b'],
40434
+ [
40435
+ { from: 'a', to: 'b' },
40436
+ { from: 'b', to: 'a' },
40437
+ ],
40438
+ ); // [['a', 'b']]
40439
+ ```
40440
+
40441
+ ## Features
40442
+
40443
+ - `bezierRoute()`: cubic bezier geometry with control points anchored to port sides
40444
+ - `orthogonalRoute()`: A\* Manhattan polyline over a visibility graph built from obstacle corners, with a per-bend penalty, owner-obstacle exemption, and deterministic expansion order
40445
+ - `bezierToSvgPath()` / `polylineToSvgPath()`: SVG `d` serialization with micro-precision formatting
40446
+ - `topologicalOrder()`: Kahn ordering with stable input-order tie breaks; throws `WireGraphError` on cycles
40447
+ - `findCyclicGroups()`: iterative Tarjan SCCs — each cyclic group reported once, ordered deterministically
40448
+ - `WireError` / `WireGraphError` / `WireConfigError`: typed errors
40449
+ - Zero runtime dependencies, no DOM requirement: routes and orders are pure computations
40450
+
40451
+ ## Documentation
40452
+
40453
+ - [Usage Guide](./usage.md)
40454
+ - [API Reference](./api.md)
40455
+ - [Examples](./examples.md)
40456
+ - [Migration Guide](./migration.md)
40457
+
40458
+ ## See Also
40459
+
40460
+ - [Atlas](/atlas/): the camera and rect shapes Wire's obstacles reuse.
40461
+
40462
+ ### API Reference
40463
+
40464
+ ## API Overview
40465
+
40466
+ | Symbol | Purpose | Execution | Common gotcha |
40467
+ | --------------------------------------------------------------------- | ------------------------------------------------- | --------- | -------------------------------------------------------------------------- |
40468
+ | `bezierRoute()` | Cubic bezier geometry between two ports | Sync | Returns a `CubicBezier`, not a string — serialize with `bezierToSvgPath()` |
40469
+ | `orthogonalRoute()` | A\* Manhattan polyline avoiding padded obstacles | Sync | Returns `null` when blocked; waypoints appear only at bends |
40470
+ | `portAnchor()` | World position of a port on a node rect | Sync | `offset` is a 0..1 fraction along the side, not a distance |
40471
+ | `bezierToSvgPath()` | SVG `d` string from a `CubicBezier` | Sync | Emits one absolute `M`/`C` pair |
40472
+ | `polylineToSvgPath()` | SVG `d` string from a polyline | Sync | Empty input returns `''`, not an error |
40473
+ | `topologicalOrder()` | Kahn ordering with input-order tie breaks | Sync | Throws `WireGraphError` on any cycle |
40474
+ | `findCyclicGroups()` | Cyclic SCCs via iterative Tarjan | Sync | Reports components (sets), not every elementary cycle |
40475
+ | `WireError` | Base class for all wire errors | Sync | Narrow with `instanceof WireError` |
40476
+ | `WireGraphError` | Unknown endpoints, duplicate ids, cyclic ordering | Sync | Thrown at call time |
40477
+ | `WireConfigError` | Invalid routing options | Sync | Thrown at call time |
40478
+ | `Point` / `Rect` / `PortAnchor` / `PortSide` / `CubicBezier` / `Edge` | Structural graph shapes | Sync | All readonly; treat as values |
40479
+
40480
+ ## Package Entry Point
40481
+
40482
+ | Import | Purpose |
40483
+ | ---------------- | ---------------------------------------------------------------------------------- |
40484
+ | `@vielzeug/wire` | Bezier and orthogonal routing, path serialization, ordering, cycles, types, errors |
40485
+
40486
+ ---
40487
+
40488
+ ## Core Types
40489
+
40490
+ ```ts
40491
+ type Point = Readonly;
40492
+ type Rect = Readonly;
40493
+ type PortSide = 'top' | 'right' | 'bottom' | 'left';
40494
+ type PortAnchor = Point & Readonly;
40495
+ type CubicBezier = Readonly;
40496
+ type Edge = Readonly;
40497
+ ```
40498
+
40499
+ Coordinates are screen convention: `top` is smaller y.
40500
+
40501
+ ---
40502
+
40503
+ ## Routing Functions
40504
+
40505
+ ### `portAnchor()`
40506
+
40507
+ ```ts
40508
+ function portAnchor(rect: Rect, side: PortSide, offset?: number): PortAnchor;
40509
+ ```
40510
+
40511
+ Places a port on `side` of `rect` and returns its world position together with the side it faces, ready to pass to `bezierRoute()` or `orthogonalRoute()`.
40512
+
40513
+ | Parameter | Type | Description |
40514
+ | --------- | ---------- | ------------------------------------------------------ |
40515
+ | `rect` | `Rect` | Node bounding box the port sits on |
40516
+ | `side` | `PortSide` | Node edge the port faces |
40517
+ | `offset` | `number` | 0..1 fraction along the side (default 0.5, the middle) |
40518
+
40519
+ **Returns:** a `PortAnchor` — the point plus its `side`. Throws `WireConfigError` for an `offset` outside 0..1 or non-finite.
40520
+
40521
+ ### `bezierRoute()`
40522
+
40523
+ ```ts
40524
+ function bezierRoute(from: PortAnchor, to: PortAnchor, options?: BezierRouteOptions): CubicBezier;
40525
+ ```
40526
+
40527
+ Builds a cubic bezier segment whose control points extend `handleLength` units outward from each port along its side, so the curve leaves and enters ports perpendicular to the node edge.
40528
+
40529
+ | Parameter | Type | Description |
40530
+ | --------- | -------------------- | ----------------------------------------------- |
40531
+ | `from` | `PortAnchor` | Source port with its side |
40532
+ | `to` | `PortAnchor` | Target port with its side |
40533
+ | `options` | `BezierRouteOptions` | `handleLength` (default 40) control-point reach |
40534
+
40535
+ **Returns:** a `CubicBezier` (`from`, `c1`, `c2`, `to`) for canvas or SVG rendering; use `bezierToSvgPath()` for an SVG `d` string. Throws `WireConfigError` for a negative or non-finite `handleLength`.
40536
+
40537
+ ### `orthogonalRoute()`
40538
+
40539
+ ```ts
40540
+ function orthogonalRoute(from: PortAnchor, to: PortAnchor, options?: OrthogonalRouteOptions): Point[] | null;
40541
+ ```
40542
+
40543
+ Routes an axis-aligned polyline over a visibility graph of obstacle corners and exit-tip rows/columns using A\*. Cost is length plus `bendPenalty` per bend; expansion order is deterministic. The route runs `stub` units straight out of each port before bending, so wires never peel off a port sideways.
40544
+
40545
+ Pass every node's raw rect as `obstacles`. The obstacles whose padded interior contains a port are exempted for that port's straight exit segment only — the searched route never enters any padded obstacle interior, including its own nodes.
40546
+
40547
+ | Parameter | Type | Description |
40548
+ | --------- | ------------------------ | ------------------------------------------------------------------------------------------------- |
40549
+ | `from` | `PortAnchor` | Start port; its `side` fixes the direction the route leaves it |
40550
+ | `to` | `PortAnchor` | Goal port; its `side` fixes the direction the route enters it |
40551
+ | `options` | `OrthogonalRouteOptions` | `obstacles`, `padding` (default 8), `bendPenalty` (default 12), `stub` (default 16, `0` disables) |
40552
+
40553
+ **Returns:** waypoints (`from` first, `to` last, bends only) or `null` when a port's exit is blocked by a non-owner obstacle or every route is sealed off. Points exactly on a padded boundary are free: routes may hug obstacle margins.
40554
+
40555
+ ### `bezierToSvgPath()`
40556
+
40557
+ ```ts
40558
+ function bezierToSvgPath(curve: CubicBezier): string;
40559
+ ```
40560
+
40561
+ Serializes as an absolute `M`/`C` command, rounded to six decimals with no `-0` or exponent noise.
40562
+
40563
+ ### `polylineToSvgPath()`
40564
+
40565
+ ```ts
40566
+ function polylineToSvgPath(points: readonly Point[]): string;
40567
+ ```
40568
+
40569
+ Serializes as absolute `M`/`L` commands, rounded to six decimals with no `-0` or exponent noise.
40570
+
40571
+ ---
40572
+
40573
+ ## Graph Functions
40574
+
40575
+ ### `topologicalOrder()`
40576
+
40577
+ ```ts
40578
+ function topologicalOrder(nodeIds: readonly string[], edges: readonly Edge[]): string[];
40579
+ ```
40580
+
40581
+ Kahn's algorithm with a heap keyed by input index; ready nodes are always consumed in input order. Parallel edges are tolerated. Throws `WireGraphError` on duplicate node ids, edges referencing unknown nodes, or cycles.
40582
+
40583
+ ### `findCyclicGroups()`
40584
+
40585
+ ```ts
40586
+ function findCyclicGroups(nodeIds: readonly string[], edges: readonly Edge[]): string[][];
40587
+ ```
40588
+
40589
+ Iterative Tarjan SCCs. Each returned group is an SCC with more than one node, or a single node with a self-loop. A group is a set of mutually reachable nodes, not a path through them. Members are sorted by input position; groups are ordered by their first member. Same validation errors as `topologicalOrder()`.
40590
+
40591
+ ---
40592
+
40593
+ ## Errors
40594
+
40595
+ | Class | Thrown when |
40596
+ | ----------------- | ------------------------------------------------------------------------------------------- |
40597
+ | `WireError` | Base class; catch-all via `instanceof WireError` |
40598
+ | `WireGraphError` | Unknown edge endpoints, duplicate node ids, cyclic `topologicalOrder()` |
40599
+ | `WireConfigError` | Negative or non-finite `handleLength`, `padding`, `stub`, or `bendPenalty`; bad port offset |
40600
+
40601
+ ### Usage Guide
40602
+
40603
+ ## Basic Usage
40604
+
40605
+ Wire is headless: it turns port positions, node bounds, and edge lists into path data and orderings. You own the rendering.
40606
+
40607
+ ```ts
40608
+ import { bezierRoute, bezierToSvgPath, orthogonalRoute, polylineToSvgPath, topologicalOrder } from '@vielzeug/wire';
40609
+
40610
+ // A curved wire from a right-facing port to a left-facing port.
40611
+ const curve = bezierRoute({ side: 'right', x: 100, y: 40 }, { side: 'left', x: 320, y: 120 });
40612
+ pathElement.setAttribute('d', bezierToSvgPath(curve));
40613
+
40614
+ // A Manhattan wire that routes around the node boxes.
40615
+ const points = orthogonalRoute(
40616
+ { side: 'right', x: 100, y: 40 },
40617
+ { side: 'left', x: 320, y: 120 },
40618
+ { obstacles: nodeBounds },
40619
+ );
40620
+ if (points) pathElement.setAttribute('d', polylineToSvgPath(points));
40621
+ ```
40622
+
40623
+ Both routers return geometry — a `CubicBezier` and a waypoint array — and the two serializers in `path.ts` turn them into SVG `d` strings. Canvas renderers consume the geometry directly (`ctx.bezierCurveTo(curve.c1.x, ...)`).
40624
+
40625
+ ## Port Sides
40626
+
40627
+ A port is a `Point` plus a required `side` naming the node edge it faces. `portAnchor()` computes that point from a node rect, so you never hand-derive "right side means `x + width`":
40628
+
40629
+ ```ts
40630
+ import { portAnchor } from '@vielzeug/wire';
40631
+
40632
+ // Middle of the node's right edge, facing right.
40633
+ const out = portAnchor(nodeBounds, 'right'); // { side: 'right', x, y }
40634
+ // Quarter along the top edge.
40635
+ const top = portAnchor(nodeBounds, 'top', 0.25);
40636
+ ```
40637
+
40638
+ `bezierRoute()` extends each control point outward along its port's side, so wires leave and enter nodes perpendicular to the edge:
40639
+
40640
+ ```ts
40641
+ // Bottom port of A into top port of B (top-to-bottom flow).
40642
+ bezierRoute({ side: 'bottom', x: 60, y: 100 }, { side: 'top', x: 60, y: 220 });
40643
+ ```
40644
+
40645
+ A free endpoint that is not on a node — the cursor while dragging a wire, say — picks a side explicitly: `{ ...cursor, side: 'left' }`.
40646
+
40647
+ ## Routing Around Obstacles
40648
+
40649
+ `orthogonalRoute()` searches a visibility graph built from the obstacle corners with A\*, costing path length plus `bendPenalty` per bend — so among equally long routes, the one with fewer bends wins:
40650
+
40651
+ Pass every node's raw bounding box as `obstacles` — the same list for every edge. `padding` supplies the clearance, so do not inflate the rects yourself:
40652
+
40653
+ ```ts
40654
+ const points = orthogonalRoute(outPort, inPort, {
40655
+ bendPenalty: 12, // cost of one extra bend, in the same units as distance
40656
+ obstacles: nodes.map((node) => node.bounds),
40657
+ padding: 8, // keep routes this far from obstacle edges
40658
+ });
40659
+ ```
40660
+
40661
+ Four contracts matter for editors:
40662
+
40663
+ - **Your own nodes are exempted for the exit only.** A port sits on its node's boundary, inside that node's padded obstacle. The router exempts the obstacles that contain a port for that port's straight exit segment; the rest of the route never enters any padded obstacle interior, including its own nodes. No per-edge filtering.
40664
+ - **Unreachable returns `null`.** When a port's exit is blocked by another obstacle, or every route around the obstacles is sealed off, you get `null` — never a path through a wall. Show a dashed straight-line fallback while the user drags.
40665
+ - **Port sides add stubs.** The route runs `stub` units (default 16) straight out of each port before bending, and straight into the target port, so wires leave and enter ports perpendicular to the node edge. Pass `stub: 0` to opt out; a port inside an obstacle still exits straight far enough to clear it.
40666
+ - **Output is deterministic.** The same inputs always produce the same polyline, so edges don't shimmer between frames. The returned polyline carries waypoints only at bends.
40667
+
40668
+ Routes may hug the padded boundary exactly; raise `padding` if you want more clearance.
40669
+
40670
+ ## Ordering the Graph
40671
+
40672
+ `topologicalOrder()` returns node ids in dependency order. Ties break by position in the input array, so the same editor state always produces the same order:
40673
+
40674
+ ```ts
40675
+ const order = topologicalOrder(
40676
+ ['render', 'layout', 'parse'],
40677
+ [
40678
+ { from: 'parse', to: 'layout' },
40679
+ { from: 'layout', to: 'render' },
40680
+ ],
40681
+ ); // ['parse', 'layout', 'render']
40682
+ ```
40683
+
40684
+ A cyclic graph has no topological order and throws `WireGraphError`. For validation UI, use `findCyclicGroups()` instead — it returns each cyclic part once as a strongly connected component:
40685
+
40686
+ ```ts
40687
+ import { findCyclicGroups } from '@vielzeug/wire';
40688
+
40689
+ const groups = findCyclicGroups(nodeIds, edges);
40690
+ // [['a', 'b']] — a two-node loop; a self-loop appears as [['a']].
40691
+ ```
40692
+
40693
+ A group is a _set_ of mutually reachable nodes, not a path through them — display it as `a, b`, not `a → b`. Highlight every node in a returned group; edges inside the group are the ones to flag.
40694
+
40695
+ ## Best Practices
40696
+
40697
+ - Route during drag with cheap settings (or a straight dashed line) and run the full `orthogonalRoute()` on drop; A\* over a few hundred obstacles is fast, but not free at 60 fps for every edge.
40698
+ - Feed only the obstacles near the edge's corridor, not the whole document — cull with an atlas spatial index for large graphs.
40699
+ - Treat `topologicalOrder()` as the execution-order oracle for dataflow editors, and `findCyclicGroups()` as the validator that explains _why_ it threw.
40700
+ - Round-trip path strings through `polylineToSvgPath()` and `bezierToSvgPath()` rather than assembling `d` strings by hand; they keep precision stable for diffing and serialization.
40701
+
40702
+ ### Examples
40703
+
40704
+ ## Examples
40705
+
40706
+ - [Edges Around Nodes](./examples/edges-around-nodes.md)
40707
+
40708
+ ### REPL Examples
40709
+
40710
+ - orthogonalRoute - Edges around nodes (id: `wire-routing`)