@vielzeug/codex 26.11.22 → 26.11.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  # Vielzeug: Full Documentation
2
2
 
3
- > Complete documentation for 47 packages. Version: 26.11.21
3
+ > Complete documentation for 52 packages. Version: 26.11.23
4
4
 
5
5
  ---
6
6
 
@@ -2784,6 +2784,576 @@ 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
+ - Frames: `frameMatrix()` local→world placement, `boundsOfFrame()` world AABBs, and `resizeRect()` editor resize math with min and aspect locks
2864
+ - `AtlasError` / `AtlasConfigError`: typed errors; the camera follows the Vielzeug disposal contract
2865
+ - Zero runtime dependencies, no DOM requirement: works in Node, Workers, and SSR
2866
+
2867
+ ## Documentation
2868
+
2869
+ - [Usage Guide](./usage.md)
2870
+ - [API Reference](./api.md)
2871
+ - [Examples](./examples.md)
2872
+ - [Migration Guide](./migration.md)
2873
+
2874
+ ## See Also
2875
+
2876
+ - [Gesture](/gesture/): pinch and wheel handles feed `zoomAt()` and `panBy()` directly.
2877
+ - [Ink](/ink/): stroke geometry whose bounds and outlines Atlas hit-tests.
2878
+ - [Wire](/wire/): edge routing for node editors sharing the same world coordinates.
2879
+
2880
+ ### API Reference
2881
+
2882
+ ## API Overview
2883
+
2884
+ | Symbol | Purpose | Execution | Common gotcha |
2885
+ | ------------------------------------ | ---------------------------------------------------------- | --------- | ----------------------------------------------------------- |
2886
+ | `createCamera()` | Pan/zoom/rotate camera with anchor-preserving transforms | Sync | `x`/`y` is the world point at the viewport centre |
2887
+ | `createSpatialIndex()` | Dynamic R-tree over world-space rects | Sync | Broad-phase only: bounds overlap, not exact shape hits |
2888
+ | `multiply()` etc. | Canvas2D-order matrix composition | Sync | Element order is `[a,b,c,d,e,f]`, not row-major 3×3 |
2889
+ | `rectFromPoints()` | AABB of a point set | Sync | Returns `null` only for iterable input that may be empty |
2890
+ | `pointInPolygon()` | Even-odd ray-cast containment | Sync | Boundary points are implementation-defined; add tolerance |
2891
+ | `distanceToPolyline()` | Distance to the nearest segment | Sync | Returns `Infinity` for empty paths |
2892
+ | `snapRect()` | Alignment, grid, and equal-gap snapping with guides | Sync | Each axis resolves independently; alignment wins |
2893
+ | `alignRects()` | Align rects to a shared edge or center | Sync | Pure: returns new rects, input untouched |
2894
+ | `distributeRects()` | Equalize gaps along one axis | Sync | Needs 3+ rects; outermost rects stay fixed |
2895
+ | `frameMatrix()` | Local→world matrix for a positioned, rotated, scaled frame | Sync | `origin` is a world pivot; defaults to `{ x, y }` |
2896
+ | `boundsOfFrame()` | AABB of a rect under a frame matrix | Sync | Grows the bounds for rotation; not a tight oriented box |
2897
+ | `resizeRect()` | Resize a rect by dragging named edges | Sync | `aspect` is width/height; corner drags derive the free axis |
2898
+ | `AtlasError` | Base class for all atlas errors | Sync | Narrow with `instanceof AtlasError` |
2899
+ | `AtlasConfigError` | Invalid options and negative tolerances | Sync | Thrown at call time |
2900
+ | `Point` / `Rect` / `Size` / `Matrix` | Structural shapes shared across the canvas toolkit | Sync | All readonly; treat as values |
2901
+
2902
+ ## Package Entry Point
2903
+
2904
+ | Import | Purpose |
2905
+ | ---------------------- | ---------------------------------------------------------------------- |
2906
+ | `@vielzeug/atlas` | Camera, spatial index, matrix/rect/geometry helpers, types, and errors |
2907
+ | `@vielzeug/atlas/grid` | Square-tile math, recursive shadowcasting FOV, and fog-of-war state |
2908
+
2909
+ ---
2910
+
2911
+ ## Core Types
2912
+
2913
+ ```ts
2914
+ type Point = Readonly;
2915
+ type Size = Readonly;
2916
+ type Rect = Readonly;
2917
+ /** Canvas2D/DOMMatrix element order: [a, b, c, d, e, f]. */
2918
+ type Matrix = readonly [number, number, number, number, number, number];
2919
+ ```
2920
+
2921
+ ---
2922
+
2923
+ ## `createCamera()`
2924
+
2925
+ ```ts
2926
+ function createCamera(options?: CameraOptions): Camera;
2927
+ ```
2928
+
2929
+ 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.
2930
+
2931
+ | Parameter | Type | Description |
2932
+ | --------- | --------------- | ----------------------------------------------------------------------------------- |
2933
+ | `options` | `CameraOptions` | `initial` state, `viewport` size in CSS px, `minZoom`/`maxZoom` clamps, `scheduler` |
2934
+
2935
+ **Returns:** `Camera` handle.
2936
+
2937
+ **Example**
2938
+
2939
+ ```ts
2940
+ import { createCamera } from '@vielzeug/atlas';
2941
+
2942
+ const camera = createCamera({
2943
+ initial: { zoom: 1.5 },
2944
+ maxZoom: 8,
2945
+ minZoom: 0.1,
2946
+ viewport: { height: 600, width: 800 },
2947
+ });
2948
+ camera.zoomAt({ x: 400, y: 300 }, 1.2);
2949
+ ```
2950
+
2951
+ 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).
2952
+
2953
+ Throws `AtlasConfigError` when clamps violate `0 (options?: SpatialIndexOptions): SpatialIndex;
2954
+ ```
2955
+
2956
+ 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.
2957
+
2958
+ | Parameter | Type | Description |
2959
+ | --------- | --------------------- | -------------------------------------------- |
2960
+ | `options` | `SpatialIndexOptions` | `maxEntriesPerNode` (integer ≥ 4, default 8) |
2961
+
2962
+ **Returns:** `SpatialIndex` handle.
2963
+
2964
+ **Example**
2965
+
2966
+ ```ts
2967
+ import { createSpatialIndex } from '@vielzeug/atlas';
2968
+
2969
+ const shapes = new Map();
2970
+ const index = createSpatialIndex();
2971
+ index.set('a', { height: 10, width: 10, x: 0, y: 0 });
2972
+ const hits = index.queryRect(marquee); // string[] of ids
2973
+ const shape = shapes.get(hits[0]);
2974
+ ```
2975
+
2976
+ ### SpatialIndex members
2977
+
2978
+ | Member | Description |
2979
+ | ----------------------------------- | ----------------------------------------------------------------------------------- |
2980
+ | `set(id, rect)` | Insert, or move an existing id; a no-op when the rect is unchanged |
2981
+ | `delete(id)` | `true` when removed, `false` when unknown |
2982
+ | `get(id)` | The current `Rect` for an id, or `undefined` |
2983
+ | `has(id)` | Membership test |
2984
+ | `queryRect(rect)` | Ids whose bounds overlap **or touch** `rect` (closed intervals) |
2985
+ | `queryPoint(point, { tolerance? })` | Ids within `tolerance` of `point` (default 0, inclusive); throws on negative values |
2986
+ | `clear()` / `size` / `bounds` | Reset, entry count, aggregate bounds (`null` when empty) |
2987
+
2988
+ 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.
2989
+
2990
+ ---
2991
+
2992
+ ## Matrix Functions
2993
+
2994
+ 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).
2995
+
2996
+ | Function | Description |
2997
+ | ------------------------ | ------------------------------------------------- |
2998
+ | `IDENTITY` | Frozen identity matrix |
2999
+ | `multiply(a, b)` | Compose two matrices |
3000
+ | `apply(matrix, point)` | Transform a point |
3001
+ | `translate(tx, ty)` | Translation builder |
3002
+ | `scale(sx, sy?)` | Scale builder (`sy` defaults to `sx`) |
3003
+ | `rotate(radians)` | Rotation builder; positive is clockwise on screen |
3004
+ | `invert(matrix)` | Inverse; `null` for zero determinant |
3005
+ | `around(anchor, matrix)` | `translate(anchor) · matrix · translate(-anchor)` |
3006
+ | `scaleOf(matrix)` | Average axis scale (0 for degenerate matrices) |
3007
+ | `toCssMatrix(matrix)` | `matrix(...)` CSS value |
3008
+
3009
+ ---
3010
+
3011
+ ## Rect Functions
3012
+
3013
+ | Function | Description |
3014
+ | ----------------------------------------------------------- | ------------------------------------------------------------------------------ |
3015
+ | `rectFromPoints(points)` | AABB of a point set; `null` for iterable input, non-null for a non-empty tuple |
3016
+ | `rectRight(rect)` / `rectBottom(rect)` / `rectCenter(rect)` | Edge and center accessors |
3017
+ | `unionRect(a, b)` | Smallest rect containing both |
3018
+ | `intersectRect(a, b)` | Overlap rect; `null` only when disjoint; touching yields a zero-area rect |
3019
+ | `rectsIntersect(a, b)` | Overlap-or-touch test (closed intervals) |
3020
+ | `containsRect(outer, inner)` / `containsPoint(rect, point)` | Inclusive containment tests |
3021
+ | `inflateRect(rect, amount)` | Grow every edge by `amount` |
3022
+
3023
+ `rectFromPoints` has two overloads: pass a literal non-empty tuple (`rectFromPoints([a, b])`) for a guaranteed `Rect`, or any `Iterable` for `Rect | null`.
3024
+
3025
+ ---
3026
+
3027
+ ## Frame Functions
3028
+
3029
+ A frame places a local shape in world space: a position, an optional clockwise rotation (radians), and an optional scale pivoting around a world `origin`.
3030
+
3031
+ ```ts
3032
+ function frameMatrix(options: FrameOptions): Matrix;
3033
+ function boundsOfFrame(rect: Rect, matrix: Matrix): Rect;
3034
+ function resizeRect(rect: Rect, edges: ResizeEdges, point: Point, options?: ResizeOptions): Rect;
3035
+ ```
3036
+
3037
+ | Function | Description |
3038
+ | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
3039
+ | `frameMatrix({ x, y, rotation?, scale?, origin? })` | Local→world matrix: `around(origin, rotate · scale) · translate(x, y)`; `origin` defaults to `{ x, y }`, `scale` is a number or `{ x?, y? }` |
3040
+ | `boundsOfFrame(rect, matrix)` | Axis-aligned world bounds: the AABB of the four transformed corners |
3041
+ | `resizeRect(rect, edges, point, { min?, aspect? })` | Resized rect dragging the edge(s) named by `edges` (`'e'`, `'w'`, `'n'`, `'s'`, or a corner like `'nw'`) to `point`; opposite edge(s) stay fixed |
3042
+
3043
+ `frameMatrix` composes the matrix helpers for the common positioned-shape case, so `apply(frameMatrix({ rotation, scale, x, y }), localPoint)` places a shape's local coordinates in the world. `boundsOfFrame` pairs with it for culling and selection: rotation grows the AABB, which is what a spatial index needs.
3044
+
3045
+ `resizeRect` is the resize-handle math for editors. `min` (default 0) keeps the result from collapsing on either axis. `aspect` (width/height) locks the ratio: a corner drag derives the free axis from the axis that moved further, an edge drag grows the free dimension about its centre.
3046
+
3047
+ ```ts
3048
+ import { boundsOfFrame, frameMatrix, resizeRect } from '@vielzeug/atlas';
3049
+
3050
+ const frame = frameMatrix({ rotation: Math.PI / 6, scale: 2, x: 100, y: 50 });
3051
+ boundsOfFrame({ height: 40, width: 100, x: 0, y: 0 }, frame); // world AABB
3052
+ resizeRect(selection, 'se', worldPointer, { min: 4 }); // drag the bottom-right corner
3053
+ ```
3054
+
3055
+ All three throw `AtlasConfigError` on non-finite inputs; `resizeRect` also throws for unknown `edges`, a negative `min`, or a non-positive `aspect`.
3056
+
3057
+ ---
3058
+
3059
+ ## Geometry Functions
3060
+
3061
+ | Function | Description |
3062
+ | --------------------------------------------- | --------------------------------------------------------------------------- |
3063
+ | `pointInPolygon(polygon, point)` | Even-odd ray-cast containment |
3064
+ | `distanceToPolyline(path, point)` | Distance to the nearest segment; `Infinity` for empty paths |
3065
+ | `pointNearPolygon(polygon, point, tolerance)` | Inside the polygon OR within `tolerance` of its outline; throws on negative |
3066
+
3067
+ ---
3068
+
3069
+ ## Snapping Functions
3070
+
3071
+ | Function | Description |
3072
+ | ------------------------------ | ---------------------------------------------------------------------------------------------- |
3073
+ | `snapRect(rect, options)` | Snapped `{ delta, guides }` against candidate rects, grid lines, and equal gaps |
3074
+ | `alignRects(rects, edge)` | Copies aligned to a shared `left`/`horizontal-center`/`right`/`top`/`vertical-center`/`bottom` |
3075
+ | `distributeRects(rects, axis)` | Copies with equalized gaps along `'x'` or `'y'` |
3076
+
3077
+ `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.
3078
+
3079
+ 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.
3080
+
3081
+ ---
3082
+
3083
+ ## Grid Functions
3084
+
3085
+ From the `@vielzeug/atlas/grid` subpath:
3086
+
3087
+ | Function | Returns |
3088
+ | -------------------------------------- | ----------------------------------------------------------------------------------------------- |
3089
+ | `worldToTile(point, grid)` | `TileCoord` (`{ col, row }`) containing the point (floor division) |
3090
+ | `tileToRect(coord, grid)` | World `Rect` of the tile |
3091
+ | `tileCenter(coord, grid)` | World `Point` at the tile's centre |
3092
+ | `visibleTileRange(view, grid)` | `TileRange` (`minCol/maxCol/minRow/maxRow`) intersecting a world rect |
3093
+ | `iterateTileRange(range)` | Generator over every `TileCoord` in a range |
3094
+ | `tileKey(coord)` | Stable `"col:row"` string |
3095
+ | `computeFov(origin, radius, options?)` | `Set` of visible `tileKey`s (8-octant recursive shadowcasting) |
3096
+ | `createFog()` | Three-state fog tracker over tile keys: `update`/`state`/`visible`, `exportState`/`importState` |
3097
+
3098
+ `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`.
3099
+
3100
+ ---
3101
+
3102
+ ## Errors
3103
+
3104
+ | Class | Thrown when |
3105
+ | ------------------ | ------------------------------------------------------------------------------- |
3106
+ | `AtlasError` | Base class; catch-all via `instanceof AtlasError` |
3107
+ | `AtlasConfigError` | Invalid options/clamps, negative snap or query tolerances, and bad frame inputs |
3108
+
3109
+ ### Usage Guide
3110
+
3111
+ ## Basic Usage
3112
+
3113
+ 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.
3114
+
3115
+ ```ts
3116
+ import { createCamera, createSpatialIndex } from '@vielzeug/atlas';
3117
+
3118
+ // Camera: (x, y) is the world point shown at the viewport centre.
3119
+ const camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });
3120
+ camera.resize({ height: viewport.clientHeight, width: viewport.clientWidth });
3121
+
3122
+ // Screen → world for input handling.
3123
+ const world = camera.toWorld({ x: event.offsetX, y: event.offsetY });
3124
+
3125
+ // World → screen for positioning DOM overlays.
3126
+ const screen = camera.toScreen(shape.position);
3127
+ ```
3128
+
3129
+ ## Coordinate Spaces
3130
+
3131
+ Atlas works in three spaces and never guesses between them:
3132
+
3133
+ - **Client space**: `PointerEvent.clientX/Y`. Subtract the viewport's `getBoundingClientRect()` offset before handing coordinates to the camera.
3134
+ - **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.
3135
+ - **World space**: your scene coordinates. `camera.matrix` maps world → screen; `zoom` is screen pixels per world unit.
3136
+
3137
+ 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.
3138
+
3139
+ ## Zooming to the Cursor
3140
+
3141
+ `zoomAt()` keeps the world point under a screen point fixed while the zoom changes — the standard infinite-canvas feel:
3142
+
3143
+ ```ts
3144
+ wheelElement.addEventListener('wheel', (event) => {
3145
+ const factor = Math.exp(-event.deltaY * 0.0015);
3146
+ camera.zoomAt({ x: event.offsetX, y: event.offsetY }, factor);
3147
+ });
3148
+ ```
3149
+
3150
+ `rotateAt()` does the same for rotation. Both clamp against `minZoom`/`maxZoom` and still hold the anchor exactly at the clamp.
3151
+
3152
+ ## Panning and Fitting
3153
+
3154
+ `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:
3155
+
3156
+ ```ts
3157
+ camera.panBy(event.movementX, event.movementY);
3158
+ camera.fitBounds(selectionBounds, { padding: 48 });
3159
+ ```
3160
+
3161
+ 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.
3162
+
3163
+ ## Animating the Camera
3164
+
3165
+ `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:
3166
+
3167
+ ```ts
3168
+ camera.animateTo(
3169
+ { x: 250, y: 100, zoom: 2 },
3170
+ {
3171
+ duration: 300,
3172
+ signal: controller.signal, // abort mid-flight; the animation stops where it is
3173
+ },
3174
+ );
3175
+ ```
3176
+
3177
+ ## Indexing the Scene
3178
+
3179
+ `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:
3180
+
3181
+ ```ts
3182
+ const index = createSpatialIndex(); // keys default to string
3183
+
3184
+ index.set(shape.id, shape.bounds); // insert, and again after every move
3185
+ index.delete(shape.id); // on delete
3186
+
3187
+ // Viewport culling each frame.
3188
+ const visibleIds = index.queryRect(camera.visibleRect);
3189
+
3190
+ // Marquee selection — the index returns ids; your own Map holds the data.
3191
+ const selected = index.queryRect(marquee).map((id) => shapes.get(id));
3192
+
3193
+ // Hover: tolerance widens the point into a box for fat-finger targets.
3194
+ const hovered = index.queryPoint(worldPoint, { tolerance: 4 / camera.state.zoom });
3195
+ ```
3196
+
3197
+ 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.
3198
+
3199
+ ## Exact Hit-Testing
3200
+
3201
+ ```ts
3202
+ import { pointNearPolygon, pointInPolygon } from '@vielzeug/atlas';
3203
+
3204
+ pointInPolygon(polygon, worldPoint); // even-odd ray cast
3205
+ pointNearPolygon(polygon, worldPoint, 2); // inside OR within 2 units of the outline
3206
+ ```
3207
+
3208
+ 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.
3209
+
3210
+ ## Snapping and Alignment
3211
+
3212
+ 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:
3213
+
3214
+ ```ts
3215
+ import { snapRect } from '@vielzeug/atlas';
3216
+
3217
+ const snap = snapRect(dragRect, {
3218
+ candidates: otherSelectedOutRects,
3219
+ grid: { x: 50, y: 50 },
3220
+ spacing: true, // opt into equal-gap spacing between neighbors
3221
+ threshold: 8,
3222
+ });
3223
+ const snapped = { ...dragRect, x: dragRect.x + snap.delta.x, y: dragRect.y + snap.delta.y };
3224
+ // snap.guides: [{ axis, kind, position, from, to, marks? }] in world coordinates — draw them through the camera.
3225
+ ```
3226
+
3227
+ 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.
3228
+
3229
+ 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.
3230
+
3231
+ After a multi-select, align or distribute with the pure helpers and record one command:
3232
+
3233
+ ```ts
3234
+ import { alignRects, distributeRects } from '@vielzeug/atlas';
3235
+
3236
+ const aligned = alignRects(selectedRects, 'horizontal-center'); // copies, same order
3237
+ const spread = distributeRects(selectedRects, 'x'); // equal gaps, outermost fixed
3238
+ ```
3239
+
3240
+ ## Matrix Helpers
3241
+
3242
+ For custom transforms, the matrix functions use Canvas2D order and compose left-to-right like `ctx.transform()`:
3243
+
3244
+ ```ts
3245
+ import {
3246
+ apply,
3247
+ around,
3248
+ IDENTITY,
3249
+ invert,
3250
+ multiply,
3251
+ rotate,
3252
+ scale,
3253
+ scaleOf,
3254
+ toCssMatrix,
3255
+ translate,
3256
+ } from '@vielzeug/atlas';
3257
+
3258
+ const transform = multiply(multiply(scale(2), rotate(Math.PI / 4)), translate(10, 5));
3259
+ apply(transform, { x: 1, y: 0 }); // transformed point
3260
+ invert(transform); // null for degenerate matrices
3261
+ around({ x: 100, y: 100 }, scale(2)); // scale about a point, not the origin
3262
+ scaleOf(transform); // average axis scale
3263
+ toCssMatrix(transform); // 'matrix(...)' for CSS transforms
3264
+ ```
3265
+
3266
+ ## Frames and Resizing
3267
+
3268
+ Shapes on a board are placed with a position, an optional rotation, and an optional scale. `frameMatrix()` composes that into one local→world matrix, and `boundsOfFrame()` turns a local rect into the world AABB your spatial index and selection queries need:
3269
+
3270
+ ```ts
3271
+ import { apply, boundsOfFrame, frameMatrix } from '@vielzeug/atlas';
3272
+
3273
+ const frame = frameMatrix({ rotation: Math.PI / 6, scale: 2, x: 100, y: 50 });
3274
+ const world = apply(frame, localPoint); // local → world
3275
+ const aabb = boundsOfFrame(localRect, frame); // world AABB, ready for index.set()
3276
+ ```
3277
+
3278
+ `origin` pivots rotation and scale around a world point; it defaults to `{ x, y }`, which makes rotation and scale pure post-transforms of the placement. `toCssMatrix(frame)` feeds the same transform straight to a DOM overlay.
3279
+
3280
+ Resize handles are the other half of editor math. `resizeRect()` takes the dragged handle's direction (`'e'`, `'nw'`, …), the pointer's world position, and keeps the opposite edge(s) fixed:
3281
+
3282
+ ```ts
3283
+ import { resizeRect } from '@vielzeug/atlas';
3284
+
3285
+ // Dragging the bottom-right handle; shapes never collapse below 4 units.
3286
+ const next = resizeRect(selection, 'se', worldPointer, { min: 4 });
3287
+ // Shift-drag convention: lock the selection's current ratio.
3288
+ const square = resizeRect(selection, 'se', worldPointer, {
3289
+ aspect: selection.width / selection.height,
3290
+ min: 4,
3291
+ });
3292
+ ```
3293
+
3294
+ On a corner drag with `aspect` set, the axis the pointer moved further along drives the other, so the drag feels direct from either side. Commit the returned rect to your model on pointer-up, the same way you commit a snapped move.
3295
+
3296
+ ## Tile Grids
3297
+
3298
+ 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:
3299
+
3300
+ ```ts
3301
+ import { iterateTileRange, tileCenter, tileKey, tileToRect, visibleTileRange, worldToTile } from '@vielzeug/atlas/grid';
3302
+
3303
+ const grid = { tileSize: 32 };
3304
+
3305
+ worldToTile({ x: 40, y: -1 }, grid); // { col: 1, row: -1 }
3306
+ tileToRect({ col: 1, row: -1 }, grid); // { x: 32, y: -32, width: 32, height: 32 }
3307
+ tileCenter({ col: 1, row: -1 }, grid); // { x: 48, y: -16 }
3308
+
3309
+ // Render loop: iterate the tiles intersecting the camera's world rect.
3310
+ for (const coord of iterateTileRange(visibleTileRange(camera.visibleRect, grid))) {
3311
+ drawTile(coord);
3312
+ }
3313
+ ```
3314
+
3315
+ `tileKey(coord)` yields the stable `"col:row"` string used by the FOV and fog APIs (and convenient as a `Map` key).
3316
+
3317
+ ## Field of View and Fog
3318
+
3319
+ `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:
3320
+
3321
+ ```ts
3322
+ import { computeFov, createFog } from '@vielzeug/atlas/grid';
3323
+
3324
+ const fov = computeFov({ col: 10, row: 8 }, 6, { blocks: (c) => walls.has(`${c.col}:${c.row}`) });
3325
+
3326
+ const fog = createFog();
3327
+ fog.update(fov); // demotes the previous frame's visible tiles to 'seen'
3328
+ fog.state(tileKey({ col: 10, row: 8 })); // 'visible' | 'seen' | 'unseen'
3329
+ saveGame(fog.exportState()); // serializable { seen, visible } key lists
3330
+ ```
3331
+
3332
+ `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.
3333
+
3334
+ ## Best Practices
3335
+
3336
+ - Subtract the viewport rect once at the input boundary; never mix client and screen coordinates inside camera calls.
3337
+ - Call `camera.resize()` from a `ResizeObserver` on the viewport element; the camera cannot anchor zooms to the centre without knowing its size.
3338
+ - Call `index.set(id, rect)` after every committed move — stale bounds silently break marquee and culling queries.
3339
+ - Use `camera.visibleRect` (the world AABB of the rotated viewport) for culling; it is conservative by design, so no visible shape is ever dropped.
3340
+ - 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.
3341
+ - 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.
3342
+
3343
+ ### Examples
3344
+
3345
+ ## Examples
3346
+
3347
+ - [Pan, Zoom and Culling](./examples/pan-zoom-and-culling.md)
3348
+
3349
+ ### REPL Examples
3350
+
3351
+ - createCamera - Pan, zoom and culling (id: `atlas-camera`)
3352
+ - frameMatrix + resizeRect - Rotated frame with resize handles (id: `atlas-frames`)
3353
+ - snapRect - Magnetic snapping and guides (id: `atlas-snap`)
3354
+
3355
+ ---
3356
+
2787
3357
  ## @vielzeug/bard
2788
3358
 
2789
3359
  **Category:** utilities
@@ -4010,7 +4580,7 @@ onScopeDispose(unsubscribe);
4010
4580
 
4011
4581
  ## Examples
4012
4582
 
4013
- - [Getting Started](./examples/getting-started.md)
4583
+ - [Guided Tour](./examples/guided-tour.md)
4014
4584
 
4015
4585
  ### REPL Examples
4016
4586
 
@@ -5123,6 +5693,8 @@ npx -y @vielzeug/codex skills install --force # overwrite an existing copy
5123
5693
 
5124
5694
  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
5695
 
5696
+ 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`.
5697
+
5126
5698
  ## Local Development
5127
5699
 
5128
5700
  Requires Node 22+ and root setup:
@@ -10820,6 +11392,8 @@ window.addEventListener('pagehide', () => pan.dispose(), { once: true });
10820
11392
  - `createDragGesture()`: unrestricted two-dimensional pointer movement tracking
10821
11393
  - `createPanGesture()`: one-axis pointer movement with direction intent recognition
10822
11394
  - `createLongPress()`: hold recognition with slop cancellation and click swallowing
11395
+ - `createPinchGesture()`: two-pointer scale and rotation with per-frame deltas
11396
+ - `createWheelGesture()`: wheel and trackpad input with pixel-normalized deltas
10823
11397
  - Direction locking: activates only when movement favors the configured axis
10824
11398
  - Configurable pointer capture: own the pointer by default or preserve native targeting
10825
11399
  - Configurable `activationDistance`: tune slop for touch density and component needs
@@ -10844,21 +11418,26 @@ window.addEventListener('pagehide', () => pan.dispose(), { once: true });
10844
11418
 
10845
11419
  ## API Overview
10846
11420
 
10847
- | Symbol | Purpose | Execution mode | Common gotcha |
10848
- | ------------------------------------------ | --------------------------------------------------- | -------------- | ------------------------------------------------------- |
10849
- | `createDragGesture()` | Track unrestricted two-dimensional pointer movement | Sync | Does not provide DOM movement or drop semantics |
10850
- | `createPanGesture()` | Track pointer movement projected onto one axis | Sync | Cross-axis intent ends a pending interaction |
10851
- | `createLongPress()` | Recognize a primary pointer held in place | Sync | The click that follows a fired hold is swallowed |
10852
- | `DragGesture` / `PanGesture` / `LongPress` | Control recognition lifecycle | Sync | `dispose()` does not invoke `onEnd` |
10853
- | `DragGestureOptions` | Configure free-drag recognition | Sync | `activationDistance` uses Euclidean distance |
10854
- | `PanGestureOptions` | Configure axis-locked recognition | Sync | Completion thresholds belong in `onEnd` |
10855
- | `LongPressOptions` | Configure hold recognition | Sync | `durationMs` and `slopPx` are validated at construction |
11421
+ | Symbol | Purpose | Execution mode | Common gotcha |
11422
+ | ------------------------------------------ | --------------------------------------------------- | -------------- | -------------------------------------------------------- |
11423
+ | `createDragGesture()` | Track unrestricted two-dimensional pointer movement | Sync | Does not provide DOM movement or drop semantics |
11424
+ | `createPanGesture()` | Track pointer movement projected onto one axis | Sync | Cross-axis intent ends a pending interaction |
11425
+ | `createLongPress()` | Recognize a primary pointer held in place | Sync | The click that follows a fired hold is swallowed |
11426
+ | `createPinchGesture()` | Track two-pointer scale and rotation | Sync | Ends when either pointer lifts |
11427
+ | `createWheelGesture()` | Track wheel input with pixel-normalized deltas | Sync | Never prevents scrolling unless `preventDefault` opts in |
11428
+ | `normalizeWheel()` | Convert wheel deltas to CSS pixels for any mode | Sync | Page-mode scaling uses the target's client box |
11429
+ | `DragGesture` / `PanGesture` / `LongPress` | Control recognition lifecycle | Sync | `dispose()` does not invoke `onEnd` |
11430
+ | `DragGestureOptions` | Configure free-drag recognition | Sync | `activationDistance` uses Euclidean distance |
11431
+ | `PanGestureOptions` | Configure axis-locked recognition | Sync | Completion thresholds belong in `onEnd` |
11432
+ | `LongPressOptions` | Configure hold recognition | Sync | `durationMs` and `slopPx` are validated at construction |
11433
+ | `PinchGestureOptions` | Configure pinch/rotate recognition | Sync | `activationDistance` is a span change, not pointer move |
11434
+ | `WheelOptions` | Configure wheel recognition | Sync | `preventDefault` accepts a per-event predicate |
10856
11435
 
10857
11436
  ## Package Entry Point
10858
11437
 
10859
- | Import | Purpose |
10860
- | ------------------- | ----------------------------------------------------------------------------------------- |
10861
- | `@vielzeug/gesture` | Drag and pan factories, handles, callback details, options, axes, points, and end reasons |
11438
+ | Import | Purpose |
11439
+ | ------------------- | -------------------------------------------------------------------------------------------------------------- |
11440
+ | `@vielzeug/gesture` | Drag, pan, long-press, pinch, and wheel factories, handles, callback details, options, points, and end reasons |
10862
11441
 
10863
11442
  ## Core Functions
10864
11443
 
@@ -10966,6 +11545,82 @@ const hold = createLongPress(list, {
10966
11545
 
10967
11546
  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.
10968
11547
 
11548
+ ---
11549
+
11550
+ ### `createPinchGesture()`
11551
+
11552
+ ```ts
11553
+ function createPinchGesture(target: Element, options?: PinchGestureOptions): PinchGesture;
11554
+ ```
11555
+
11556
+ Tracks two pointers and reports scale and rotation relative to the positions where they went down.
11557
+
11558
+ | Parameter | Type | Description |
11559
+ | --------- | --------------------- | --------------------------------------------------------------------- |
11560
+ | `target` | `Element` | Element that owns pointer admission and optional capture |
11561
+ | `options` | `PinchGestureOptions` | Activation, admission, capture, callback, and lifecycle configuration |
11562
+
11563
+ **Returns:** A lifecycle-owned `PinchGesture` handle with the same members as the other gestures.
11564
+
11565
+ **Example**
11566
+
11567
+ ```ts
11568
+ import { createPinchGesture } from '@vielzeug/gesture';
11569
+
11570
+ const pinch = createPinchGesture(stage, {
11571
+ onMove: ({ deltaScale, deltaRotation, deltaCentroid }) => {
11572
+ camera.zoomBy(1 + deltaScale);
11573
+ camera.rotateBy(deltaRotation);
11574
+ camera.panBy(deltaCentroid.x, deltaCentroid.y);
11575
+ },
11576
+ });
11577
+ ```
11578
+
11579
+ 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.
11580
+
11581
+ ---
11582
+
11583
+ ### `createWheelGesture()`
11584
+
11585
+ ```ts
11586
+ function createWheelGesture(target: Element, options?: WheelOptions): WheelGesture;
11587
+ ```
11588
+
11589
+ 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.
11590
+
11591
+ | Parameter | Type | Description |
11592
+ | --------- | -------------- | ------------------------------------------------------------ |
11593
+ | `target` | `Element` | Element the `wheel` listener is attached to |
11594
+ | `options` | `WheelOptions` | Prevention, admission, callback, and lifecycle configuration |
11595
+
11596
+ **Returns:** A disposal-only `WheelGesture` handle.
11597
+
11598
+ **Example**
11599
+
11600
+ ```ts
11601
+ import { createWheelGesture } from '@vielzeug/gesture';
11602
+
11603
+ const wheel = createWheelGesture(stage, {
11604
+ preventDefault: true,
11605
+ onWheel: ({ deltaX, deltaY, pinch }) => {
11606
+ if (pinch) camera.zoomBy(Math.exp(-deltaY * 0.01));
11607
+ else camera.panBy(-deltaX, -deltaY);
11608
+ },
11609
+ });
11610
+ ```
11611
+
11612
+ `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.
11613
+
11614
+ ---
11615
+
11616
+ ### `normalizeWheel()`
11617
+
11618
+ ```ts
11619
+ function normalizeWheel(event: WheelEvent, target: Element): { deltaX: number; deltaY: number };
11620
+ ```
11621
+
11622
+ 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.
11623
+
10969
11624
  ## Types
10970
11625
 
10971
11626
  ### Drag types
@@ -11035,6 +11690,49 @@ type LongPressOptions = Readonly boolean | undefined);
11035
11690
 
11036
11691
  `durationMs` defaults to `500` and `slopPx` to `8`. `event` is the pointerdown that started the hold, so `event.target` is the pressed element.
11037
11692
 
11693
+ ### Pinch types
11694
+
11695
+ ```ts
11696
+ type PinchEndReason = 'cancel' | 'release';
11697
+
11698
+ type PinchPoint = Readonly;
11699
+
11700
+ type PinchGestureDetail = Readonly;
11701
+
11702
+ type PinchGestureEndDetail = PinchGestureDetail &
11703
+ Readonly;
11704
+
11705
+ type PinchGestureOptions = Readonly boolean | undefined);
11706
+ onEnd?: (detail: PinchGestureEndDetail) => void;
11707
+ onMove?: (detail: PinchGestureDetail) => void;
11708
+ onStart?: (detail: PinchGestureDetail) => void;
11709
+ pointerCapture?: boolean;
11710
+ signal?: AbortSignal;
11711
+ }>;
11712
+ ```
11713
+
11714
+ `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.
11715
+
11716
+ ### Wheel types
11717
+
11718
+ ```ts
11719
+ type WheelDetail = Readonly;
11720
+
11721
+ type WheelOptions = Readonly boolean | undefined);
11722
+ onWheel?: (detail: WheelDetail) => void;
11723
+ preventDefault?: boolean | ((event: WheelEvent) => boolean);
11724
+ signal?: AbortSignal;
11725
+ }>;
11726
+
11727
+ type WheelGesture = Readonly void;
11728
+ readonly disposalSignal: AbortSignal;
11729
+ dispose(): void;
11730
+ readonly disposed: boolean;
11731
+ }>;
11732
+ ```
11733
+
11734
+ `deltaX`/`deltaY` are normalized to CSS pixels (see `normalizeWheel()`); positive moves content right/down. `pinch` mirrors `ctrlKey`.
11735
+
11038
11736
  ### Handle types
11039
11737
 
11040
11738
  ```ts
@@ -11048,6 +11746,8 @@ type DragGesture = {
11048
11746
  };
11049
11747
 
11050
11748
  type PanGesture = DragGesture;
11749
+
11750
+ type PinchGesture = DragGesture;
11051
11751
  ```
11052
11752
 
11053
11753
  ### Shared option behavior
@@ -11154,6 +11854,57 @@ const hold = createLongPress(grid, {
11154
11854
 
11155
11855
  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.
11156
11856
 
11857
+ ## Recognize Pinch and Rotate
11858
+
11859
+ 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:
11860
+
11861
+ ```ts
11862
+ import { createPinchGesture } from '@vielzeug/gesture';
11863
+
11864
+ const stage = document.querySelector('[data-stage]');
11865
+ if (!stage) throw new Error('Missing [data-stage] element');
11866
+
11867
+ const card = stage.querySelector('[data-card]');
11868
+ if (!card) throw new Error('Missing [data-card] element');
11869
+
11870
+ let x = 0;
11871
+ let y = 0;
11872
+ createPinchGesture(stage, {
11873
+ onMove: ({ scale, rotation, deltaCentroid }) => {
11874
+ x += deltaCentroid.x;
11875
+ y += deltaCentroid.y;
11876
+ card.style.transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotation}rad)`;
11877
+ },
11878
+ });
11879
+ ```
11880
+
11881
+ 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.
11882
+
11883
+ 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.
11884
+
11885
+ 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.
11886
+
11887
+ ## Recognize Wheel and Trackpad Zoom
11888
+
11889
+ 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:
11890
+
11891
+ ```ts
11892
+ import { createWheelGesture } from '@vielzeug/gesture';
11893
+
11894
+ const wheel = createWheelGesture(stage, {
11895
+ preventDefault: (event) => event.ctrlKey || stage.contains(event.target as Node),
11896
+ onWheel: ({ deltaX, deltaY, pinch }) => {
11897
+ if (pinch) {
11898
+ camera.zoomBy(Math.exp(-deltaY * 0.01));
11899
+ } else {
11900
+ camera.panBy(-deltaX, -deltaY);
11901
+ }
11902
+ },
11903
+ });
11904
+ ```
11905
+
11906
+ 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.
11907
+
11157
11908
  ## Completion Rules
11158
11909
 
11159
11910
  Gesture reports movement and terminal state but does not decide what constitutes a swipe. Apply thresholds and allowed directions in `onEnd`.
@@ -11339,6 +12090,8 @@ Gesture owns pointer recognition: unrestricted two-dimensional drag and one-axis
11339
12090
 
11340
12091
  - createDragGesture - Basic (id: `drag-basic`)
11341
12092
  - createPanGesture - Basic (id: `pan-basic`)
12093
+ - createPinchGesture - Basic (id: `pinch-basic`)
12094
+ - createWheelGesture - Basic (id: `wheel-basic`)
11342
12095
 
11343
12096
  ---
11344
12097
 
@@ -12986,6 +13739,586 @@ const customers = Array.from({ length: 100 }, () => ({
12986
13739
 
12987
13740
  ---
12988
13741
 
13742
+ ## @vielzeug/ink
13743
+
13744
+ **Category:** data
13745
+
13746
+ ### Overview
13747
+
13748
+ ## Why Ink?
13749
+
13750
+ 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.
13751
+
13752
+ ```ts
13753
+ // Before
13754
+ // Hand-rolled filter math, per-point width heuristics, and manual path assembly
13755
+ // in every drawing surface, each with its own jitter and nondeterminism.
13756
+
13757
+ // After
13758
+ import { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';
13759
+
13760
+ const stabilized = stabilizeStroke(samples);
13761
+ const d = polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 4 })), {
13762
+ close: true,
13763
+ });
13764
+ ```
13765
+
13766
+ | Feature | Ink | Ad-hoc smoothing | Sketch libraries |
13767
+ | ------------------------------ | -------------------------------------------- | ---------------- | -------------------- |
13768
+ | Bundle size | | n/a | Typically 10–50 kB |
13769
+ | External dependencies | | n/a | Varies |
13770
+ | Deterministic pure functions | | Rarely | Often randomized |
13771
+ | Variable-width outline polygon | Built in | Manual | Rare |
13772
+ | Runs without a DOM | | Varies | Usually browser-only |
13773
+
13774
+ **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.
13775
+
13776
+ **Consider direct polyline rendering when** the input is already clean (vector tools with their own smoothing) and a plain segment path is visually sufficient.
13777
+
13778
+ ## Installation
13779
+
13780
+ ```sh [pnpm]
13781
+ pnpm add @vielzeug/ink
13782
+ ```
13783
+
13784
+ ```sh [npm]
13785
+ npm install @vielzeug/ink
13786
+ ```
13787
+
13788
+ ```sh [yarn]
13789
+ yarn add @vielzeug/ink
13790
+ ```
13791
+
13792
+ ## Quick Start
13793
+
13794
+ ```ts
13795
+ import { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';
13796
+
13797
+ // Raw samples from a pointer stream (see @vielzeug/gesture for capture),
13798
+ // timestamped with PointerEvent.timeStamp.
13799
+ const samples = [
13800
+ { time: 0, x: 0, y: 0 },
13801
+ { time: 16, x: 12, y: 3 },
13802
+ { time: 32, x: 25, y: -2 },
13803
+ { time: 48, x: 40, y: 1 },
13804
+ ];
13805
+
13806
+ const stabilized = stabilizeStroke(samples); // causal jitter removal
13807
+ const widths = strokeWidths(stabilized, { width: 6 }); // speed-derived widths
13808
+ const ring = strokeOutline(stabilized, widths); // closed variable-width polygon
13809
+ const d = polylineToSvgPath(ring, { close: true }); // SVG `d` string
13810
+ ```
13811
+
13812
+ ## Features
13813
+
13814
+ - `stabilizeStroke()`: causal Streamline-style averaging for live drawing; the stroke ends exactly where the pen lifted
13815
+ - `smoothStroke()`: deterministic Catmull-Rom resampling after capture
13816
+ - `strokeWidths()`: real-speed-derived widths (`distance / Δtime`) with pressure modulation and clamped scaling
13817
+ - `strokeOutline()`: closed variable-width polygon offset along local normals with capped ends; constant width with a single number
13818
+ - `simplifyStroke()`: iterative Ramer-Douglas-Peucker decimation preserving endpoints
13819
+ - `polylineToSvgPath()`: SVG `d` strings for open strokes and closed outline rings, with configurable precision
13820
+ - `InkError` / `InkConfigError`: typed configuration errors thrown at call time
13821
+ - Determinism: identical input always yields identical output; no randomness, no clocks
13822
+ - Zero runtime dependencies and no DOM requirement: works in Node, Workers, and SSR
13823
+
13824
+ ## Documentation
13825
+
13826
+ - [Usage Guide](./usage.md)
13827
+ - [API Reference](./api.md)
13828
+ - [Examples](./examples.md)
13829
+ - [Migration Guide](./migration.md)
13830
+
13831
+ ## See Also
13832
+
13833
+ - [Gesture](/gesture/): captures the pointer samples Ink consumes; pan handles produce the raw point streams.
13834
+ - [Prism](/prism/): SVG rendering primitives; Ink's `d` strings drop straight into its path elements.
13835
+
13836
+ ### API Reference
13837
+
13838
+ ## API Overview
13839
+
13840
+ | Symbol | Purpose | Execution | Common gotcha |
13841
+ | ----------------------- | -------------------------------------------------------- | --------- | ----------------------------------------------------------------- |
13842
+ | `stabilizeStroke()` | Causal jitter removal while drawing | Sync | One output point per input; last point snaps to the pen-up spot |
13843
+ | `smoothStroke()` | Catmull-Rom resampling after capture | Sync | Adds points: `steps` samples per input segment |
13844
+ | `strokeWidths()` | Per-point widths from real speed (`time`) and pressure | Sync | Velocity is off for the whole stroke if any point lacks `time` |
13845
+ | `strokeOutline()` | Closed variable-width polygon around a stroke | Sync | Array `widths` must match point count; a number is constant |
13846
+ | `simplifyStroke()` | Ramer-Douglas-Peucker decimation | Sync | Returns input references, not copies |
13847
+ | `polylineToSvgPath()` | SVG `d` string for polylines and closed outline rings | Sync | Requires at least one point; pass `close: true` for rings |
13848
+ | `InkError` | Base class for all ink errors | Sync | Narrow with `instanceof InkError` |
13849
+ | `InkConfigError` | Invalid options or point counts | Sync | Thrown at call time, not construction |
13850
+ | `Point` / `StrokePoint` | Structural point shapes shared across the canvas toolkit | Sync | `pressure` and `time` are optional; `time` unlocks width velocity |
13851
+
13852
+ ## Package Entry Point
13853
+
13854
+ | Import | Purpose |
13855
+ | --------------- | ---------------------------------------------------------------------------------------------------- |
13856
+ | `@vielzeug/ink` | Stabilization, smoothing, width profiling, outline, simplification, SVG serialization, types, errors |
13857
+
13858
+ ---
13859
+
13860
+ ## Core Functions
13861
+
13862
+ ### `stabilizeStroke()`
13863
+
13864
+ ```ts
13865
+ function stabilizeStroke(points: readonly StrokePoint[], options?: StabilizeStrokeOptions): StrokePoint[];
13866
+ ```
13867
+
13868
+ 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.
13869
+
13870
+ | Parameter | Type | Description |
13871
+ | --------- | ------------------------ | ----------------------------------------------------------- |
13872
+ | `points` | `readonly StrokePoint[]` | Input samples |
13873
+ | `options` | `StabilizeStrokeOptions` | `strength` in `[0, 1]`; `0` is the raw input, default `0.5` |
13874
+
13875
+ **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.
13876
+
13877
+ **Example**
13878
+
13879
+ ```ts
13880
+ import { stabilizeStroke } from '@vielzeug/ink';
13881
+
13882
+ const live = stabilizeStroke(samples, { strength: 0.6 });
13883
+ ```
13884
+
13885
+ Throws `InkConfigError` for a `strength` outside `[0, 1]`.
13886
+
13887
+ ---
13888
+
13889
+ ### `smoothStroke()`
13890
+
13891
+ ```ts
13892
+ function smoothStroke(points: readonly StrokePoint[], options?: SmoothStrokeOptions): StrokePoint[];
13893
+ ```
13894
+
13895
+ 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.
13896
+
13897
+ | Parameter | Type | Description |
13898
+ | --------- | ------------------------ | ------------------------------------------------------------------------------ |
13899
+ | `points` | `readonly StrokePoint[]` | Input samples; fewer than three are returned as copies |
13900
+ | `options` | `SmoothStrokeOptions` | `tension` in `[0, 1]` (default `1`), `steps` integer `[2, 1000]` (default `8`) |
13901
+
13902
+ **Returns:** New `StrokePoint[]` with `steps` samples per input segment plus the exact final point.
13903
+
13904
+ **Example**
13905
+
13906
+ ```ts
13907
+ import { smoothStroke } from '@vielzeug/ink';
13908
+
13909
+ const resampled = smoothStroke(samples, { tension: 1, steps: 8 });
13910
+ ```
13911
+
13912
+ Throws `InkConfigError` for a `tension` outside `[0, 1]` or a `steps` value outside `[2, 1000]` or non-integer.
13913
+
13914
+ ---
13915
+
13916
+ ### `strokeWidths()`
13917
+
13918
+ ```ts
13919
+ function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[];
13920
+ ```
13921
+
13922
+ 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.
13923
+
13924
+ | Parameter | Type | Description |
13925
+ | --------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
13926
+ | `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |
13927
+ | `options` | `StrokeWidthOptions` | `width` (required, > 0), `thinning` in `[0, 1]` (default `0.5`), `referenceSpeed` in px/ms (default `0.5`), `taper`, `simulatePressure` |
13928
+
13929
+ **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.
13930
+
13931
+ 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.
13932
+
13933
+ `taper` fades the width in over `taper.start` and out over `taper.end` units of arc length (same units as `width`): a smoothstep ramp from a `0.15` floor at the tip to full width at the taper length, multiplied on top of the speed/pressure profile. `simulatePressure` (default `false`) synthesizes pressure for points that have none on a timed stroke: the width multiplier ramps from `0.5` at each tip to neutral across the first and last 15% of arc length, so mouse strokes thin at the ends. Points that carry real `pressure` always use it, and untimed strokes ignore the option.
13934
+
13935
+ **Example**
13936
+
13937
+ ```ts
13938
+ import { strokeWidths } from '@vielzeug/ink';
13939
+
13940
+ const widths = strokeWidths(samples, { width: 6, thinning: 0.5 });
13941
+ const tapered = strokeWidths(samples, { width: 6, taper: { start: 30, end: 30 }, simulatePressure: true });
13942
+ ```
13943
+
13944
+ Throws `InkConfigError` for a non-positive `width` or `referenceSpeed`, a `thinning` outside `[0, 1]`, a negative or non-finite `taper` length, or an empty `points` array.
13945
+
13946
+ ---
13947
+
13948
+ ### `strokeOutline()`
13949
+
13950
+ ```ts
13951
+ function strokeOutline(
13952
+ points: readonly StrokePoint[],
13953
+ widths: number | readonly number[],
13954
+ options?: StrokeOutlineOptions,
13955
+ ): Point[];
13956
+ ```
13957
+
13958
+ 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.
13959
+
13960
+ | Parameter | Type | Description |
13961
+ | --------- | ----------------------------- | --------------------------------------------------------------------------------- |
13962
+ | `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |
13963
+ | `widths` | `number \| readonly number[]` | Constant width, or per-point widths from `strokeWidths()` |
13964
+ | `options` | `StrokeOutlineOptions` | `cap` (default `'round'`), `join` (default `'round'`), `miterLimit` (default `4`) |
13965
+
13966
+ `cap` selects the end treatment: `'round'` half-circle caps, `'butt'` no cap points, `'square'` a half-width tangent extension at each end. `join` handles turns sharper than 90°, where naive offsetting makes the inner side cross itself: `'round'` keeps the plain offset samples (current default output), `'bevel'` replaces each sharp joint with the two adjacent segment-offset points, dropping the crossing spike, and `'miter'` extends to the offset-line intersection while the miter length stays within `miterLimit` × half width, falling back to bevel beyond it.
13967
+
13968
+ **Returns:** `Point[]` ring, deterministic for deterministic input.
13969
+
13970
+ **Example**
13971
+
13972
+ ```ts
13973
+ import { strokeOutline } from '@vielzeug/ink';
13974
+
13975
+ const ring = strokeOutline(samples, widths);
13976
+ const uniform = strokeOutline(samples, 4);
13977
+ const marker = strokeOutline(samples, 4, { cap: 'square', join: 'miter', miterLimit: 6 });
13978
+ ```
13979
+
13980
+ Throws `InkConfigError` when an array `widths` length differs from `points` length or any width is not a positive finite number, when `cap` or `join` is not a known variant, or when `miterLimit` is not a positive finite number.
13981
+
13982
+ ---
13983
+
13984
+ ### `simplifyStroke()`
13985
+
13986
+ ```ts
13987
+ function simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[];
13988
+ ```
13989
+
13990
+ Returns a Ramer-Douglas-Peucker decimated subsequence of the input; first and last points are always kept.
13991
+
13992
+ | Parameter | Type | Description |
13993
+ | ----------- | ------------------------ | -------------------------------------------------- |
13994
+ | `points` | `readonly StrokePoint[]` | Stroke samples |
13995
+ | `tolerance` | `number` | Maximum perpendicular deviation to discard, `>= 0` |
13996
+
13997
+ **Returns:** `StrokePoint[]` containing the same object references as the input (metadata such as `pressure` and `time` survives).
13998
+
13999
+ **Example**
14000
+
14001
+ ```ts
14002
+ import { simplifyStroke } from '@vielzeug/ink';
14003
+
14004
+ const decimated = simplifyStroke(samples, 0.5);
14005
+ ```
14006
+
14007
+ Throws `InkConfigError` for a negative or non-finite `tolerance`.
14008
+
14009
+ ---
14010
+
14011
+ ### `polylineToSvgPath()`
14012
+
14013
+ ```ts
14014
+ function polylineToSvgPath(points: readonly Point[], options?: PolylineToSvgPathOptions): string;
14015
+ ```
14016
+
14017
+ 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.
14018
+
14019
+ | Parameter | Type | Description |
14020
+ | --------- | -------------------------- | --------------------------------------------------------------------------- |
14021
+ | `points` | `readonly Point[]` | Stroke samples or ring vertices (at least one) |
14022
+ | `options` | `PolylineToSvgPathOptions` | `close` appends `Z`; `precision` rounds coordinates (`0`–`12`, default `2`) |
14023
+
14024
+ **Returns:** `string` suitable for a `` attribute.
14025
+
14026
+ **Example**
14027
+
14028
+ ```ts
14029
+ import { polylineToSvgPath } from '@vielzeug/ink';
14030
+
14031
+ const d = polylineToSvgPath(samples, { precision: 1 }); // "M 0 0 L 12 3 L 25 -2"
14032
+ const outline = polylineToSvgPath(ring, { close: true }); // "M ... L ... Z"
14033
+ ```
14034
+
14035
+ Throws `InkConfigError` when `points` is empty or `precision` is out of range.
14036
+
14037
+ ## Types
14038
+
14039
+ ```ts
14040
+ type Point = Readonly;
14041
+ ```
14042
+
14043
+ A two-dimensional point. Structural so canvas-toolkit packages can share it without importing each other.
14044
+
14045
+ ```ts
14046
+ type StrokePoint = Readonly;
14047
+ ```
14048
+
14049
+ A sampled stroke point. `time` values only need to share a clock; any monotonic source works.
14050
+
14051
+ ```ts
14052
+ interface StabilizeStrokeOptions {
14053
+ strength?: number; // [0, 1], default 0.5
14054
+ }
14055
+ ```
14056
+
14057
+ ```ts
14058
+ interface SmoothStrokeOptions {
14059
+ tension?: number; // [0, 1], default 1
14060
+ steps?: number; // [2, 1000] integer, default 8
14061
+ }
14062
+ ```
14063
+
14064
+ ```ts
14065
+ interface StrokeWidthOptions {
14066
+ width: number; // required, > 0
14067
+ thinning?: number; // [0, 1], default 0.5
14068
+ referenceSpeed?: number; // > 0, default 0.5 (px per ms)
14069
+ taper?: StrokeTaperOptions; // arc-length end fade, default none
14070
+ simulatePressure?: boolean; // default false; timed strokes only
14071
+ }
14072
+ ```
14073
+
14074
+ ```ts
14075
+ interface StrokeTaperOptions {
14076
+ start?: number; // fade-in length along arc length, >= 0, default 0
14077
+ end?: number; // fade-out length along arc length, >= 0, default 0
14078
+ }
14079
+ ```
14080
+
14081
+ ```ts
14082
+ type StrokeCap = 'round' | 'butt' | 'square';
14083
+ ```
14084
+
14085
+ ```ts
14086
+ type StrokeJoin = 'round' | 'bevel' | 'miter';
14087
+ ```
14088
+
14089
+ ```ts
14090
+ interface StrokeOutlineOptions {
14091
+ cap?: StrokeCap; // default 'round'
14092
+ join?: StrokeJoin; // default 'round'
14093
+ miterLimit?: number; // > 0, default 4 (miter length / half width)
14094
+ }
14095
+ ```
14096
+
14097
+ ```ts
14098
+ interface PolylineToSvgPathOptions {
14099
+ close?: boolean; // default false
14100
+ precision?: number; // [0, 12] integer, default 2
14101
+ }
14102
+ ```
14103
+
14104
+ ## Errors
14105
+
14106
+ | Error | Trigger |
14107
+ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
14108
+ | `InkError` | Base class; catch all ink errors with `instanceof InkError` |
14109
+ | `InkConfigError` | Invalid options (strength, tension, steps, width, thinning, precision, tolerance, cap, join, miterLimit, taper, …) or point-count mismatches |
14110
+
14111
+ ### Usage Guide
14112
+
14113
+ ## Basic Usage
14114
+
14115
+ 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.
14116
+
14117
+ ```ts
14118
+ import {
14119
+ polylineToSvgPath,
14120
+ simplifyStroke,
14121
+ stabilizeStroke,
14122
+ strokeOutline,
14123
+ strokeWidths,
14124
+ type StrokePoint,
14125
+ } from '@vielzeug/ink';
14126
+
14127
+ // Capture: PointerEvent.timeStamp is the timestamp ink wants.
14128
+ const samples: StrokePoint[] = [];
14129
+ element.addEventListener('pointermove', (event) => {
14130
+ samples.push({ pressure: event.pressure, time: event.timeStamp, x: event.offsetX, y: event.offsetY });
14131
+ });
14132
+
14133
+ const stabilized = stabilizeStroke(samples);
14134
+ const widths = strokeWidths(stabilized, { width: 6 });
14135
+ const d = polylineToSvgPath(strokeOutline(stabilized, widths), { close: true });
14136
+
14137
+ // Render with any SVG-capable surface.
14138
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
14139
+ path.setAttribute('d', d);
14140
+ ```
14141
+
14142
+ ## Stabilize While Drawing
14143
+
14144
+ `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.
14145
+
14146
+ ```ts
14147
+ import { stabilizeStroke } from '@vielzeug/ink';
14148
+
14149
+ const live = stabilizeStroke(samples, { strength: 0.5 }); // 0 = raw, 1 = maximum smoothing
14150
+ ```
14151
+
14152
+ ## Smooth After Capture
14153
+
14154
+ `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.
14155
+
14156
+ ```ts
14157
+ import { smoothStroke } from '@vielzeug/ink';
14158
+
14159
+ const resampled = smoothStroke(samples, { tension: 1, steps: 8 });
14160
+ ```
14161
+
14162
+ ## Profile Widths From Speed and Pressure
14163
+
14164
+ `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.
14165
+
14166
+ ```ts
14167
+ import { strokeWidths } from '@vielzeug/ink';
14168
+
14169
+ const widths = strokeWidths(stabilized, {
14170
+ width: 6,
14171
+ thinning: 0.5, // 0 disables velocity, 1 is fully inverse-proportional
14172
+ referenceSpeed: 0.5, // neutral pen speed in pixels per millisecond
14173
+ });
14174
+ ```
14175
+
14176
+ 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.
14177
+
14178
+ `taper` fades the ends: within the first `taper.start` and last `taper.end` units of arc length, the width is multiplied by a smoothstep ramp that bottoms out at `0.15` of full width at the tips. `simulatePressure` gives mouse strokes the same in/out feel by synthesizing pressure for points that have none (ramping to `0.5×` width at each tip over the last 15% of arc length); points with real `pressure` always keep it.
14179
+
14180
+ ```ts
14181
+ const tapered = strokeWidths(stabilized, {
14182
+ width: 6,
14183
+ taper: { start: 40, end: 40 }, // 40 px of arc length faded at each end
14184
+ simulatePressure: true, // thin the ends of pressure-less mouse strokes
14185
+ });
14186
+ ```
14187
+
14188
+ ## Build the Outline
14189
+
14190
+ `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.
14191
+
14192
+ ```ts
14193
+ import { strokeOutline } from '@vielzeug/ink';
14194
+
14195
+ const ring = strokeOutline(stabilized, widths); // variable width, closed polygon
14196
+ const uniform = strokeOutline(stabilized, 6); // constant width, no array needed
14197
+ ```
14198
+
14199
+ `cap` changes the ends: `'butt'` stops at the last offsets, `'square'` extends each end by half the width along the tangent. `join` fixes the crossing spike naive offsetting produces at turns sharper than 90°: `'bevel'` cuts the corner with the two adjacent offset points, and `'miter'` extends to the exact intersection while its length stays within `miterLimit` × half width, falling back to bevel beyond that.
14200
+
14201
+ ```ts
14202
+ const marker = strokeOutline(stabilized, 6, { cap: 'square', join: 'miter', miterLimit: 6 });
14203
+ ```
14204
+
14205
+ ## Simplify Before Serializing
14206
+
14207
+ 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.
14208
+
14209
+ ```ts
14210
+ import { simplifyStroke, polylineToSvgPath } from '@vielzeug/ink';
14211
+
14212
+ const compact = polylineToSvgPath(simplifyStroke(ring, 0.25), { close: true });
14213
+ ```
14214
+
14215
+ ## Serialize to SVG Paths
14216
+
14217
+ `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.
14218
+
14219
+ ```ts
14220
+ import { polylineToSvgPath } from '@vielzeug/ink';
14221
+
14222
+ const centerline = polylineToSvgPath(simplifyStroke(stabilized, 0.5), { precision: 1 });
14223
+ const outline = polylineToSvgPath(ring, { close: true });
14224
+ ```
14225
+
14226
+ ## Framework Integration
14227
+
14228
+ Ink functions are pure, so they memoize cleanly. Recompute geometry only when the sample array changes.
14229
+
14230
+ ```tsx [React]
14231
+ import { useMemo } from 'react';
14232
+ import { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths, type StrokePoint } from '@vielzeug/ink';
14233
+
14234
+ function InkPath({ samples }: { samples: StrokePoint[] }) {
14235
+ const d = useMemo(() => {
14236
+ const stabilized = stabilizeStroke(samples);
14237
+ return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });
14238
+ }, [samples]);
14239
+
14240
+ return ;
14241
+ }
14242
+ ```
14243
+
14244
+ ```vue [Vue 3]
14245
+
14246
+ import { computed } from 'vue';
14247
+ import {
14248
+ polylineToSvgPath,
14249
+ stabilizeStroke,
14250
+ strokeOutline,
14251
+ strokeWidths,
14252
+ type StrokePoint,
14253
+ } from '@vielzeug/ink';
14254
+
14255
+ const props = defineProps();
14256
+ const d = computed(() => {
14257
+ const stabilized = stabilizeStroke(props.samples);
14258
+ return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });
14259
+ });
14260
+
14261
+
14262
+
14263
+ ```
14264
+
14265
+ ```svelte [Svelte]
14266
+
14267
+ import {
14268
+ polylineToSvgPath,
14269
+ stabilizeStroke,
14270
+ strokeOutline,
14271
+ strokeWidths,
14272
+ type StrokePoint,
14273
+ } from '@vielzeug/ink';
14274
+
14275
+ export let samples: StrokePoint[];
14276
+ $: d = (() => {
14277
+ const stabilized = stabilizeStroke(samples);
14278
+ return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });
14279
+ })();
14280
+
14281
+ ```
14282
+
14283
+ ## Working with Other Vielzeug Libraries
14284
+
14285
+ 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.
14286
+
14287
+ ```ts
14288
+ import { createDragGesture } from '@vielzeug/gesture';
14289
+ import { polylineToSvgPath, stabilizeStroke, type StrokePoint } from '@vielzeug/ink';
14290
+
14291
+ const samples: StrokePoint[] = [];
14292
+ const drag = createDragGesture(surface, {
14293
+ onMove: ({ currentX, currentY, event }) => samples.push({ time: event.timeStamp, x: currentX, y: currentY }),
14294
+ onEnd: () => {
14295
+ path.setAttribute('d', polylineToSvgPath(stabilizeStroke(samples), { precision: 1 }));
14296
+ },
14297
+ });
14298
+ ```
14299
+
14300
+ ## Best Practices
14301
+
14302
+ - Pass `time` on every sample (`PointerEvent.timeStamp` or `performance.now()`): without it, widths are pressure-only and speed information is thrown away.
14303
+ - Stabilize live, smooth once: run `stabilizeStroke()` per pointer move for a calm preview, and add `smoothStroke()` or `simplifyStroke()` at commit time.
14304
+ - Simplify outlines with a tolerance around `0.2`–`0.5` device pixels; larger tolerances visibly flatten caps.
14305
+ - Keep `precision` at `1`–`2` for display paths; raise it only when another tool re-processes the output.
14306
+ - Treat invalid options errors (`InkConfigError`) as programming bugs: they throw at call time with the offending option named.
14307
+ - Memoize per stroke in UI frameworks; the functions are pure and cheap to cache.
14308
+
14309
+ ### Examples
14310
+
14311
+ ## Examples
14312
+
14313
+ - [Jitter-Free Ink](./examples/jitter-free-ink.md)
14314
+
14315
+ ### REPL Examples
14316
+
14317
+ - strokeOutline options - caps, joins, and taper (id: `ink-outline-options`)
14318
+ - stabilizeStroke - Jitter-free ink (id: `ink-smoothing`)
14319
+
14320
+ ---
14321
+
12989
14322
  ## @vielzeug/keymap
12990
14323
 
12991
14324
  **Category:** app-infrastructure
@@ -18640,6 +19973,423 @@ define('signup-form', {
18640
19973
 
18641
19974
  ---
18642
19975
 
19976
+ ## @vielzeug/palette
19977
+
19978
+ **Category:** utilities
19979
+
19980
+ ### Overview
19981
+
19982
+ ## Why Palette?
19983
+
19984
+ 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.
19985
+
19986
+ ```ts
19987
+ // Before
19988
+ 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
19989
+ const ratio = /* hand-rolled luminance, usually forgets the sRGB transfer function */;
19990
+
19991
+ // After
19992
+ import { contrastRatio, mix, parseColor, ramp } from '@vielzeug/palette';
19993
+
19994
+ const mid = mix(parseColor('#000000'), parseColor('#ffffff'), 0.5); // perceptual OKLab midpoint
19995
+ const ratio = contrastRatio(parseColor('#767676'), parseColor('#ffffff')); // 4.54
19996
+ const shades = ramp(parseColor('#3366cc'), { steps: 9 }); // OKLCH lightness ramp
19997
+ ```
19998
+
19999
+ | Feature | Palette | Ad-hoc color helpers |
20000
+ | --------------------------------------- | --------------------------------------------- | -------------------- |
20001
+ | Bundle size | | n/a |
20002
+ | Zero dependencies | | n/a |
20003
+ | CSS Color 4 `oklab()`/`oklch()` parsing | Built in | Manual |
20004
+ | CSS named colors | Built in | Manual |
20005
+ | OKLab mixing with premultiplied alpha | Built in, matches `color-mix(in oklab)` | Manual |
20006
+ | WCAG 2.x contrast | Built in | Manual |
20007
+ | Perceptual ramps | OKLCH lightness, gamut-fitted | Manual |
20008
+
20009
+ **Use Palette when** an application needs headless color parsing, conversion, mixing, or contrast checks with no DOM or rendering assumptions.
20010
+
20011
+ **Consider a rendering-layer color API when** the work is applying colors to a surface rather than computing them.
20012
+
20013
+ ## Installation
20014
+
20015
+ ```sh [pnpm]
20016
+ pnpm add @vielzeug/palette
20017
+ ```
20018
+
20019
+ ```sh [npm]
20020
+ npm install @vielzeug/palette
20021
+ ```
20022
+
20023
+ ```sh [yarn]
20024
+ yarn add @vielzeug/palette
20025
+ ```
20026
+
20027
+ ## Quick Start
20028
+
20029
+ ```ts
20030
+ import { mix, parseColor, ramp, readableOn, toHex } from '@vielzeug/palette';
20031
+
20032
+ const brand = parseColor('#3366cc');
20033
+ const surface = parseColor('rgb(248 250 252)');
20034
+
20035
+ const ink = readableOn(surface, [parseColor('#0f172a'), parseColor('#334155')]);
20036
+ const midpoint = mix(brand, surface, 0.5); // OKLab interpolation, like color-mix(in oklab)
20037
+ const shades = ramp(brand, { steps: 9 }); // OKLCH lightness ramp
20038
+
20039
+ console.log(toHex(ink ?? brand), toHex(midpoint), shades.map(toHex));
20040
+ ```
20041
+
20042
+ ## Features
20043
+
20044
+ - `parseColor()`: `#rgb`/`#rgba`/`#rrggbb`/`#rrggbbaa`, `rgb()`/`hsl()` comma and space syntax, CSS Color 4 `oklab()`/`oklch()`, and CSS named colors
20045
+ - `toHex()`, `toRgbString()`, `toHslString()`, `toOklchString()`: formatting with documented clamping at the display boundary
20046
+ - `srgbToOklch()` / `oklchToSrgb()`, `srgbToHsl()` / `hslToSrgb()`: lossless round-trippable conversions via the standard Björn Ottosson OKLab matrices
20047
+ - `isDisplayable()`: gamut test for any `Rgba` against sRGB
20048
+ - `mix()`: OKLab interpolation with premultiplied alpha, matching CSS `color-mix(in oklab)`
20049
+ - `contrastRatio()` and `relativeLuminance()`: WCAG 2.x ratios on clamped sRGB
20050
+ - `readableOn()`: picks the first candidate meeting the AA/AAA threshold, with large-text thresholds
20051
+ - `ramp()`: deterministic OKLCH lightness ramps that keep hue and stay inside the gamut
20052
+ - Typed errors: `PaletteParseError` and `PaletteConfigError` share the `PaletteError` base
20053
+ - Pure functions only: no DOM, no disposal contract, zero dependencies
20054
+
20055
+ ## Documentation
20056
+
20057
+ - [Usage Guide](./usage.md)
20058
+ - [API Reference](./api.md)
20059
+ - [Examples](./examples.md)
20060
+ - [Migration Guide](./migration.md)
20061
+
20062
+ ## See Also
20063
+
20064
+ - [Arsenal](/arsenal/): general-purpose utilities that complement headless color math.
20065
+ - [Refine](/refine/): components styled with design tokens that tools like this generate and check.
20066
+
20067
+ ### API Reference
20068
+
20069
+ ## API Overview
20070
+
20071
+ | Symbol | Purpose | Execution | Common gotcha |
20072
+ | --------------------- | -------------------------------------------- | --------- | ------------------------------------------------------- |
20073
+ | `parseColor()` | Parse a CSS color string into `Rgba` | Sync | `color()` is out of scope; named colors are supported |
20074
+ | `toHex()` | Format as `#rrggbb`/`#rrggbbaa` | Sync | Alpha is written when translucent unless `alpha: false` |
20075
+ | `toRgbString()` | Format as CSS `rgb()` space syntax | Sync | Channels are clamped to 0–255 |
20076
+ | `toHslString()` | Format as CSS `hsl()` space syntax | Sync | Channels are clamped before conversion |
20077
+ | `toOklchString()` | Format as CSS `oklch()` syntax | Sync | Writes true channels, even out of gamut |
20078
+ | `srgbToOklch()` | Convert sRGB to OKLCH | Sync | Round-trip drifts up to ±1 per channel |
20079
+ | `oklchToSrgb()` | Convert OKLCH to sRGB | Sync | Out-of-gamut channels stay unclamped, they do not throw |
20080
+ | `isDisplayable()` | Test an `Rgba` against the sRGB gamut | Sync | Allows a small rounding tolerance |
20081
+ | `srgbToHsl()` | Convert sRGB to HSL | Sync | `h` is 0–360, `s`/`l` are 0–100 |
20082
+ | `hslToSrgb()` | Convert HSL to sRGB | Sync | Hue wraps; channels beyond the gamut stay unclamped |
20083
+ | `mix()` | OKLab interpolation with premultiplied alpha | Sync | `t` outside `[0, 1]` throws `PaletteConfigError` |
20084
+ | `relativeLuminance()` | WCAG 2.x relative luminance | Sync | Computed on channels clamped to 0–255 |
20085
+ | `contrastRatio()` | WCAG 2.x contrast ratio (1–21) | Sync | Ignores alpha by design |
20086
+ | `readableOn()` | First candidate meeting a WCAG threshold | Sync | Returns `null` when nothing passes |
20087
+ | `ramp()` | OKLCH lightness ramp of a base color | Sync | `steps` must be an integer ≥ 2 |
20088
+
20089
+ ## Package Entry Point
20090
+
20091
+ | Import | Purpose |
20092
+ | ------------------- | --------------------------- |
20093
+ | `@vielzeug/palette` | Complete public Palette API |
20094
+
20095
+ ## Parsing
20096
+
20097
+ ### `parseColor()`
20098
+
20099
+ ```ts
20100
+ function parseColor(input: string): Rgba;
20101
+ ```
20102
+
20103
+ 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.
20104
+
20105
+ ## Formatting
20106
+
20107
+ ### `toHex()`
20108
+
20109
+ ```ts
20110
+ function toHex(color: Rgba, options?: FormatOptions): string;
20111
+ ```
20112
+
20113
+ 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.
20114
+
20115
+ ### `toRgbString()`
20116
+
20117
+ ```ts
20118
+ function toRgbString(color: Rgba, options?: FormatOptions): string;
20119
+ ```
20120
+
20121
+ Formats as `rgb(r g b)` or `rgb(r g b / a)` space syntax. Same clamping as `toHex()`.
20122
+
20123
+ ### `toHslString()`
20124
+
20125
+ ```ts
20126
+ function toHslString(color: Rgba, options?: FormatOptions): string;
20127
+ ```
20128
+
20129
+ Formats as `hsl(h s% l%)` or `hsl(h s% l% / a)`. Channels clamp before conversion.
20130
+
20131
+ ### `toOklchString()`
20132
+
20133
+ ```ts
20134
+ function toOklchString(color: Rgba, options?: FormatOptions): string;
20135
+ ```
20136
+
20137
+ 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.
20138
+
20139
+ ## Conversion
20140
+
20141
+ ### `srgbToOklch()` / `oklchToSrgb()`
20142
+
20143
+ ```ts
20144
+ function srgbToOklch(color: Rgba): Oklch;
20145
+ function oklchToSrgb(color: Oklch): Rgba;
20146
+ ```
20147
+
20148
+ 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.
20149
+
20150
+ ### `isDisplayable()`
20151
+
20152
+ ```ts
20153
+ function isDisplayable(color: Rgba): boolean;
20154
+ ```
20155
+
20156
+ 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.
20157
+
20158
+ ### `srgbToHsl()` / `hslToSrgb()`
20159
+
20160
+ ```ts
20161
+ function srgbToHsl(color: Rgba): Hsla;
20162
+ function hslToSrgb(color: Hsla): Rgba;
20163
+ ```
20164
+
20165
+ `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).
20166
+
20167
+ ## Mixing
20168
+
20169
+ ### `mix()`
20170
+
20171
+ ```ts
20172
+ function mix(a: Rgba, b: Rgba, t: number): Rgba;
20173
+ ```
20174
+
20175
+ 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.
20176
+
20177
+ ## Contrast
20178
+
20179
+ ### `relativeLuminance()`
20180
+
20181
+ ```ts
20182
+ function relativeLuminance(color: Rgba): number;
20183
+ ```
20184
+
20185
+ WCAG 2.x relative luminance on channels clamped to 0–255.
20186
+
20187
+ ### `contrastRatio()`
20188
+
20189
+ ```ts
20190
+ function contrastRatio(a: Rgba, b: Rgba): number;
20191
+ ```
20192
+
20193
+ WCAG 2.x contrast ratio: 1 for identical colors, 21 for black on white. Symmetric in its arguments.
20194
+
20195
+ ### `readableOn()`
20196
+
20197
+ ```ts
20198
+ function readableOn(background: Rgba, candidates: readonly Rgba[], options?: ReadableOnOptions): Rgba | null;
20199
+ ```
20200
+
20201
+ 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.
20202
+
20203
+ ## Ramps
20204
+
20205
+ ### `ramp()`
20206
+
20207
+ ```ts
20208
+ function ramp(base: Rgba, options: RampOptions): Rgba[];
20209
+ ```
20210
+
20211
+ 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`.
20212
+
20213
+ ## Types
20214
+
20215
+ ### `Rgba`
20216
+
20217
+ ```ts
20218
+ type Rgba = Readonly;
20219
+ ```
20220
+
20221
+ 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.
20222
+
20223
+ ### `Hsla`
20224
+
20225
+ ```ts
20226
+ type Hsla = Readonly;
20227
+ ```
20228
+
20229
+ `h` is degrees 0–360, `s` and `l` are percentages 0–100, `a` is 0–1.
20230
+
20231
+ ### `Oklch`
20232
+
20233
+ ```ts
20234
+ type Oklch = Readonly;
20235
+ ```
20236
+
20237
+ `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.
20238
+
20239
+ ### `FormatOptions`
20240
+
20241
+ ```ts
20242
+ type FormatOptions = Readonly;
20243
+ ```
20244
+
20245
+ When `alpha` is `true` the alpha channel is always written; otherwise it is written only when the color is translucent.
20246
+
20247
+ ### `ReadableOnOptions`
20248
+
20249
+ ```ts
20250
+ type ReadableOnOptions = Readonly;
20251
+ ```
20252
+
20253
+ ### `RampOptions`
20254
+
20255
+ ```ts
20256
+ type RampOptions = Readonly;
20257
+ ```
20258
+
20259
+ ## Errors
20260
+
20261
+ | Error | Thrown by | Meaning |
20262
+ | -------------------- | ----------------- | ----------------------------------------------------------------------------------- |
20263
+ | `PaletteParseError` | `parseColor()` | Input did not match the supported grammar; the message includes the offending input |
20264
+ | `PaletteConfigError` | `mix()`, `ramp()` | Invalid options or positions |
20265
+
20266
+ Both extend `PaletteError`, so `catch (error) { if (error instanceof PaletteError) ... }` narrows both.
20267
+
20268
+ ### Usage Guide
20269
+
20270
+ ## Basic Usage
20271
+
20272
+ ```ts
20273
+ import { parseColor, toHex } from '@vielzeug/palette';
20274
+
20275
+ const brand = parseColor('#3366cc'); // { r: 51, g: 102, b: 204, a: 1 }
20276
+ console.log(toHex(brand)); // "#3366cc"
20277
+ ```
20278
+
20279
+ `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.
20280
+
20281
+ ## Parse CSS Colors
20282
+
20283
+ ```ts
20284
+ import { parseColor } from '@vielzeug/palette';
20285
+
20286
+ parseColor('#f09'); // #rgb: digits are duplicated
20287
+ parseColor('#f098'); // #rgba
20288
+ parseColor('rgb(1, 2, 3)'); // comma syntax
20289
+ parseColor('rgba(1, 2, 3, 0.5)'); // legacy comma alpha
20290
+ parseColor('rgb(1 2 3 / 0.5)'); // space syntax with slash alpha
20291
+ parseColor('rgb(50% 25% 0%)'); // percentages map to 0–255
20292
+ parseColor('hsl(120, 100%, 50%)'); // hue wraps: -120 and 480 are valid
20293
+ parseColor('oklab(0.5 -0.1 0.1 / 0.5)'); // CSS Color 4
20294
+ parseColor('oklch(50% 0.1 240deg)'); // percent lightness, deg hue
20295
+ parseColor('RebeccaPurple'); // named colors, any case
20296
+ parseColor('transparent'); // { r: 0, g: 0, b: 0, a: 0 }
20297
+ ```
20298
+
20299
+ 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.
20300
+
20301
+ ## Convert Between Color Spaces
20302
+
20303
+ ```ts
20304
+ import { hslToSrgb, oklchToSrgb, parseColor, srgbToHsl, srgbToOklch } from '@vielzeug/palette';
20305
+
20306
+ const red = parseColor('#ff0000');
20307
+ const oklch = srgbToOklch(red); // { l: 0.628, c: 0.2577, h: 29.23, a: 1 }
20308
+ const hsl = srgbToHsl(red); // { h: 0, s: 100, l: 50, a: 1 }
20309
+
20310
+ const back = oklchToSrgb(oklch); // round-trips within ±1 per channel
20311
+ ```
20312
+
20313
+ 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.
20314
+
20315
+ ## Format Colors
20316
+
20317
+ ```ts
20318
+ import { parseColor, toHex, toHslString, toOklchString, toRgbString } from '@vielzeug/palette';
20319
+
20320
+ const translucent = parseColor('rgb(222 173 190 / 0.5)');
20321
+ toHex(translucent); // "#deadbe80" — alpha is written when the color is translucent
20322
+ toHex(translucent, { alpha: false }); // "#deadbe" — never write alpha...
20323
+ toHex(parseColor('#deadbeef'), { alpha: true }); // "#deadbeff" — ...or always write it
20324
+ toRgbString(translucent); // "rgb(222 173 190 / 0.5)"
20325
+ toHslString(parseColor('#ff0000')); // "hsl(0 100% 50%)"
20326
+ toOklchString(parseColor('#ff0000')); // "oklch(62.8% 0.2577 29.23)"
20327
+ ```
20328
+
20329
+ `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.
20330
+
20331
+ ## Mix in OKLab
20332
+
20333
+ ```ts
20334
+ import { mix, parseColor, toHex } from '@vielzeug/palette';
20335
+
20336
+ const mid = mix(parseColor('#000000'), parseColor('#ffffff'), 0.5);
20337
+ toHex(mid); // "#636363" — the perceptual midpoint, not #808080
20338
+
20339
+ const hover = mix(parseColor('#ff0000'), parseColor('rgb(0 0 0 / 0)'), 0.5);
20340
+ toHex(hover); // "#ff000080" — transparent endpoints don't darken
20341
+ ```
20342
+
20343
+ `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`.
20344
+
20345
+ ## Check Contrast
20346
+
20347
+ ```ts
20348
+ import { contrastRatio, parseColor, readableOn } from '@vielzeug/palette';
20349
+
20350
+ contrastRatio(parseColor('#000000'), parseColor('#ffffff')); // 21
20351
+ contrastRatio(parseColor('#767676'), parseColor('#ffffff')); // ≈ 4.54 (AA boundary)
20352
+
20353
+ const ink = readableOn(parseColor('#f8fafc'), [parseColor('#94a3b8'), parseColor('#0f172a')]);
20354
+ // → #0f172a: the first candidate that reaches the threshold
20355
+ ```
20356
+
20357
+ `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.
20358
+
20359
+ ## Build Lightness Ramps
20360
+
20361
+ ```ts
20362
+ import { parseColor, ramp, toHex } from '@vielzeug/palette';
20363
+
20364
+ const shades = ramp(parseColor('#3366cc'), { steps: 9 });
20365
+ console.log(shades.map(toHex)); // nine swatches, dark to light
20366
+ ```
20367
+
20368
+ `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`.
20369
+
20370
+ ## Errors
20371
+
20372
+ All failures are `PaletteError` subclasses: `PaletteParseError` for malformed input and `PaletteConfigError` for invalid options. Catch the base class to handle both.
20373
+
20374
+ ## Best Practices
20375
+
20376
+ - Parse once at the boundary, keep `Rgba` values, and format at the edges; conversions are cheap but parsing strings repeatedly is wasteful.
20377
+ - Use `mix()` instead of averaging channels — gamma-space averages look muddy.
20378
+ - Use `ramp()` for tonal scales and `readableOn()` for ink selection instead of hand-tuned hex pairs.
20379
+ - 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.
20380
+
20381
+ ### Examples
20382
+
20383
+ ## Examples
20384
+
20385
+ - [Parse, Mix and Contrast](./examples/parse-mix-and-contrast.md)
20386
+
20387
+ ### REPL Examples
20388
+
20389
+ - Basics - parse, mix, contrast, ramp (id: `palette-basic`)
20390
+
20391
+ ---
20392
+
18643
20393
  ## @vielzeug/patchwork
18644
20394
 
18645
20395
  **Category:** utilities
@@ -20149,7 +21899,7 @@ chart.dispose();
20149
21899
  | Feature | Prism | Hand-written SVG |
20150
21900
  | ------------------ | ---------------------------------------------------------------- | -------------------------------------------- |
20151
21901
  | Bundle size | | No chart package |
20152
- | Zero dependencies | (uses Orbit) | |
21902
+ | Zero dependencies | (uses Orbit, Palette) | |
20153
21903
  | Data updates | `ChartHandle.update()` replaces chart data | You implement the update path |
20154
21904
  | Responsive sizing | `ResizeObserver` recalculates the chart layout | You implement the resize behavior |
20155
21905
  | Chart interactions | Built-in pointer and keyboard interactions on supported charts | You implement them |
@@ -33271,6 +35021,386 @@ const profile = Profile.parse(await courier.get('/profile'));
33271
35021
 
33272
35022
  ---
33273
35023
 
35024
+ ## @vielzeug/stage
35025
+
35026
+ **Category:** utilities
35027
+
35028
+ ### Overview
35029
+
35030
+ ## Why Stage?
35031
+
35032
+ 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.
35033
+
35034
+ ## Installation
35035
+
35036
+ ```sh [pnpm]
35037
+ pnpm add @vielzeug/stage
35038
+ ```
35039
+
35040
+ ```sh [npm]
35041
+ npm install @vielzeug/stage
35042
+ ```
35043
+
35044
+ ```sh [yarn]
35045
+ yarn add @vielzeug/stage
35046
+ ```
35047
+
35048
+ ## Quick Start
35049
+
35050
+ ```ts
35051
+ import { createStage } from '@vielzeug/stage';
35052
+
35053
+ const stage = createStage(canvas, {
35054
+ dpr: window.devicePixelRatio,
35055
+ height: 600,
35056
+ layers: [
35057
+ { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },
35058
+ { id: 'tokens', paint: (ctx) => drawTokens(ctx) },
35059
+ ],
35060
+ width: 800,
35061
+ });
35062
+
35063
+ stage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen; DPR applied on top
35064
+ token.x += 10;
35065
+ stage.invalidate('tokens'); // only the tokens layer repaints
35066
+ ```
35067
+
35068
+ ## Features
35069
+
35070
+ - **`createStage()`**: layered retained-mode renderer with cached per-layer surfaces
35071
+ - **Dirty repaints**: invalidate one layer or all; frames coalesce via an injectable scheduler
35072
+ - **DPR-aware transforms**: paint in world units, the stage scales by `dpr × matrix`
35073
+ - **`StageController`**: one control type shared by main-thread and worker stages
35074
+ - **`toBlob()`**: PNG export of the composited canvas, flushing pending frames, with optional world-space `region`/`scale` re-render and typed unsupported-capability errors
35075
+ - **Injectable surfaces**: `createSurface` factory for tests and `OffscreenCanvas` workers
35076
+ - **`@vielzeug/stage/worker`**: worker-rendered stages via a transferred `OffscreenCanvas` and a typed scene channel
35077
+
35078
+ ## Documentation
35079
+
35080
+ - [Usage Guide](./usage.md)
35081
+ - [API Reference](./api.md)
35082
+ - [Examples](./examples.md)
35083
+
35084
+ ## See Also
35085
+
35086
+ - [Atlas](/atlas/): cameras, spatial index, and tile grids that feed Stage transforms.
35087
+ - [Gesture](/gesture/): pointer drag, pinch, and wheel recognition.
35088
+
35089
+ ### API Reference
35090
+
35091
+ ## API Overview
35092
+
35093
+ | Symbol | Purpose | Execution | Common gotcha |
35094
+ | ----------------------- | ------------------------------------------------------- | --------- | ----------------------------------------------------------------- |
35095
+ | `createStage()` | Retained-mode layered canvas renderer | Sync | Paint callbacks draw in world units; the stage applies the matrix |
35096
+ | `StageController` | Control surface shared by main-thread and worker stages | Type | Both modes are assignable to it; mode extras are not |
35097
+ | `StageError` | Base class for all stage errors | Sync | Narrow with `instanceof StageError` |
35098
+ | `StageConfigError` | Invalid sizes, duplicate/unknown layer ids | Sync | Thrown at call time, in both modes |
35099
+ | `StageDisposedError` | Blob export or worker request after disposal | Sync | Worker blob failures carry a `kind` mapped to this class |
35100
+ | `StageUnsupportedError` | Missing browser capability (2D context, blob export) | Sync | No silent degradation to a lesser path |
35101
+
35102
+ ## Package Entry Point
35103
+
35104
+ | Import | Purpose |
35105
+ | ------------------------ | ------------------------------------------------- |
35106
+ | `@vielzeug/stage` | Stage factory, controller type, and error classes |
35107
+ | `@vielzeug/stage/worker` | Worker-rendered stages over `OffscreenCanvas` |
35108
+
35109
+ Geometry is not re-declared here: `Point`, `Rect`, `Matrix`, and `FrameScheduler` come from
35110
+ [`@vielzeug/atlas`](/atlas/api/), which `@vielzeug/stage` depends on.
35111
+
35112
+ ---
35113
+
35114
+ ## Core Types
35115
+
35116
+ ```ts
35117
+ import type { FrameScheduler, Matrix, Rect, Size } from '@vielzeug/atlas';
35118
+
35119
+ type PaintContext = Readonly;
35120
+
35121
+ /** A backing surface a layer paints into. `OffscreenCanvas` on workers. */
35122
+ type StageSurface = {
35123
+ width: number;
35124
+ height: number;
35125
+ getContext: (type: '2d', attributes?: CanvasRenderingContext2DSettings) => unknown;
35126
+ };
35127
+ type CreateSurface = (width: number, height: number) => StageSurface;
35128
+
35129
+ /** Options for `toBlob()`: blob encoding plus an optional world-space crop and density. */
35130
+ type StageBlobOptions = Readonly;
35131
+
35132
+ /**
35133
+ * The control surface both stage modes share. A main-thread `Stage` and a
35134
+ * `WorkerStage` are interchangeable wherever only control is needed.
35135
+ */
35136
+ type StageController = Readonly void;
35137
+ setTransform: (matrix: Matrix) => void;
35138
+ invalidate: (layerId?: string) => void;
35139
+ toBlob: (options?: StageBlobOptions) => Promise;
35140
+ dispose: () => void;
35141
+ readonly disposed: boolean;
35142
+ readonly disposalSignal: AbortSignal;
35143
+ [Symbol.dispose]: () => void;
35144
+ }>;
35145
+ ```
35146
+
35147
+ `Size` comes from [`@vielzeug/atlas`](/atlas/api/) as well.
35148
+
35149
+ ---
35150
+
35151
+ ## `createStage()`
35152
+
35153
+ ```ts
35154
+ function createStage(
35155
+ canvas: HTMLCanvasElement | OffscreenCanvas,
35156
+ options: StageOptions & Readonly,
35157
+ ): Stage;
35158
+ ```
35159
+
35160
+ 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`.
35161
+
35162
+ | Parameter | Type | Description |
35163
+ | ----------------------- | -------------------------------------- | ---------------------------------------------------------------------- |
35164
+ | `canvas` | `HTMLCanvasElement \| OffscreenCanvas` | Canvas the stage composites into (visible or transferred) |
35165
+ | `options.width` | `number` | CSS width in pixels; must be positive and finite |
35166
+ | `options.height` | `number` | CSS height in pixels; must be positive and finite |
35167
+ | `options.dpr` | `number?` | Device pixel ratio; defaults to `1` |
35168
+ | `options.layers` | `readonly StageLayerOptions[]` | Layers in paint order, fixed at creation; duplicate ids throw |
35169
+ | `options.scheduler` | `FrameScheduler?` | Injectable rAF scheduler for deterministic tests |
35170
+ | `options.createSurface` | `CreateSurface?` | Backing-surface factory; defaults to `OffscreenCanvas`/document canvas |
35171
+ | `options.background` | `string \| null?` | Color cleared under the layers; defaults to transparent |
35172
+
35173
+ **Returns:** `Stage` handle.
35174
+
35175
+ **Example**
35176
+
35177
+ ```ts
35178
+ const stage = createStage(canvas, {
35179
+ width: 800,
35180
+ height: 600,
35181
+ dpr: window.devicePixelRatio,
35182
+ layers: [{ id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) }],
35183
+ });
35184
+ stage.setTransform([2, 0, 0, 2, 40, 10]); // world→screen, CSS pixels
35185
+ stage.invalidate('scene');
35186
+ ```
35187
+
35188
+ ### `Stage` members
35189
+
35190
+ `Stage` extends `StageController` (`resize`, `setTransform`, `invalidate`, `toBlob`, `dispose`, `disposed`, `disposalSignal`, `[Symbol.dispose]`) and adds:
35191
+
35192
+ | Member | Description |
35193
+ | -------------------------------------------- | -------------------------------------------------------------------------------------- |
35194
+ | `render(time?)` | Runs the pending repaint/composite synchronously; `time` defaults to `scheduler.now()` |
35195
+ | `visibleRect` | Visible world-space rect derived from the inverse transform |
35196
+ | `matrix`, `width`, `height`, `dpr`, `canvas` | Current configuration |
35197
+
35198
+ `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.
35199
+
35200
+ ### `toBlob(options?)`
35201
+
35202
+ ```ts
35203
+ type StageBlobOptions = Readonly;
35204
+ ```
35205
+
35206
+ Without `region`/`scale`, the stage exports its current canvas at the current device scale. With them, the stage re-paints every layer into scratch surfaces against `translate(-region) × scale` and composites the result into an offscreen surface sized `region.width × scale` by `region.height × scale` (rounded, at least 1 pixel per side) — layer caches are keyed to the live viewport transform, so a crop cannot reuse the cached composite. The cost is a full repaint; the live viewport, caches, and dirty flags are untouched. `scale` defaults to the current device pixels per world unit (`dpr × matrix scale`), which matches the on-screen density; paint callbacks see `frame.dpr = 1` and `frame.visibleRect = region` during an export.
35207
+
35208
+ Invalid `region` (non-finite coordinates or non-positive size) or `scale` (non-positive or non-finite) throws `StageConfigError`; on a worker stage the failure arrives as `StageError`.
35209
+
35210
+ ---
35211
+
35212
+ ## Worker Subpath (`@vielzeug/stage/worker`)
35213
+
35214
+ | Export | Description |
35215
+ | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
35216
+ | `createWorkerStage(canvas, worker, options)` | Main-thread client: transfers `canvas` to `worker` once, then drives it; a `StageController` plus `ready` and `sendScene(scene: Scene)` |
35217
+ | `serveStage(scope, setup)` | Worker half: waits for `init`, creates a `createStage` on the transferred `OffscreenCanvas`, and services commands; `setup` returns `{ layers, onScene?, onDispose? }` |
35218
+ | `WorkerScope`, `WorkerSelfScope`, `WorkerStage`, `WorkerStageOptions`, `ServeStageSetup`, `StageServer` | Supporting types for both halves |
35219
+
35220
+ 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.
35221
+
35222
+ `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.
35223
+
35224
+ `createWorkerStage` throws `StageUnsupportedError` when the canvas cannot transfer control (`transferControlToOffscreen` missing). `dispose()` posts a final `dispose` command, rejects in-flight `toBlob()` promises with `StageDisposedError`, aborts `disposalSignal` (terminate the worker from there — the creator owns it), and makes later calls inert. `toBlob(options?)` forwards `StageBlobOptions` — including `region` and `scale` — verbatim; the worker performs the same region re-paint export on its `OffscreenCanvas` pipeline.
35225
+
35226
+ ## Errors
35227
+
35228
+ | Class | Thrown when |
35229
+ | ----------------------- | ----------------------------------------------------------------------------------------- |
35230
+ | `StageError` | Base class; catch all stage failures with `instanceof` |
35231
+ | `StageConfigError` | Non-positive sizes, non-finite matrices, duplicate/unknown ids, bad `toBlob` region/scale |
35232
+ | `StageDisposedError` | `toBlob()` after `dispose()`, or worker blob rejected on disposal |
35233
+ | `StageUnsupportedError` | No 2D context on a surface, or `canvas.toBlob` missing/failing |
35234
+
35235
+ ### Usage Guide
35236
+
35237
+ ## Basic Usage
35238
+
35239
+ ```ts
35240
+ import { createStage } from '@vielzeug/stage';
35241
+
35242
+ const stage = createStage(canvas, {
35243
+ width: canvas.clientWidth,
35244
+ height: canvas.clientHeight,
35245
+ dpr: window.devicePixelRatio,
35246
+ layers: [
35247
+ { id: 'grid', paint: (ctx, { visibleRect }) => drawGrid(ctx, visibleRect) },
35248
+ { id: 'scene', paint: (ctx, { visibleRect }) => drawScene(ctx, visibleRect) },
35249
+ { id: 'overlay', paint: (ctx) => drawSelection(ctx) },
35250
+ ],
35251
+ });
35252
+ ```
35253
+
35254
+ 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`.
35255
+
35256
+ 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`).
35257
+
35258
+ ## Driving the Transform
35259
+
35260
+ The stage takes a world→screen matrix in CSS pixels (it applies DPR itself). Pair it with an `@vielzeug/atlas` camera:
35261
+
35262
+ ```ts
35263
+ import { createCamera } from '@vielzeug/atlas';
35264
+
35265
+ const camera = createCamera({ maxZoom: 16, minZoom: 0.05 });
35266
+ camera.subscribe(() => stage.setTransform(camera.matrix));
35267
+
35268
+ canvas.addEventListener('wheel', (event) => {
35269
+ event.preventDefault();
35270
+ camera.zoomAt({ x: event.offsetX, y: event.offsetY }, Math.exp(-event.deltaY * 0.0015));
35271
+ });
35272
+ ```
35273
+
35274
+ `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.
35275
+
35276
+ ## Dirty Repaints
35277
+
35278
+ Invalidate the smallest unit that changed:
35279
+
35280
+ ```ts
35281
+ token.x += 10;
35282
+ stage.invalidate('tokens'); // only the tokens layer repaints next frame
35283
+ ```
35284
+
35285
+ Invalidations within one frame coalesce into a single scheduled frame. Call `stage.render()` to force a synchronous repaint (useful in tests).
35286
+
35287
+ ## Resize and DPR Changes
35288
+
35289
+ ```ts
35290
+ new ResizeObserver(([entry]) => {
35291
+ stage.resize({ width: entry.contentRect.width, height: entry.contentRect.height }, window.devicePixelRatio);
35292
+ }).observe(canvas.parentElement!);
35293
+ ```
35294
+
35295
+ `resize()` resizes the canvas backing store and invalidates all layers; surfaces are reallocated at the new pixel size.
35296
+
35297
+ ## Exporting a PNG
35298
+
35299
+ ```ts
35300
+ const blob = await stage.toBlob();
35301
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
35302
+ ```
35303
+
35304
+ `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.
35305
+
35306
+ For a crop or a higher resolution, pass `region` (world units) and `scale` (export pixels per world unit):
35307
+
35308
+ ```ts
35309
+ // Export the visible area at 2× the on-screen density.
35310
+ const blob = await stage.toBlob({
35311
+ region: stage.visibleRect,
35312
+ scale: stage.dpr * cameraZoom * 2,
35313
+ });
35314
+ ```
35315
+
35316
+ The stage re-paints every layer into scratch surfaces against the region transform, so the cost is a full repaint rather than a blit of the cached composite; the live viewport and its caches are untouched. `scale` defaults to the current device pixels per world unit, and omitting `region` exports the visible rect. A non-positive or non-finite `region`/`scale` throws `StageConfigError`.
35317
+
35318
+ ## Testing with Injected Surfaces
35319
+
35320
+ Inject a fake surface factory and scheduler to unit-test paint behaviour without a GPU:
35321
+
35322
+ ```ts
35323
+ const frames = { queued: new Set void>() };
35324
+ const stage = createStage(fakeCanvas, {
35325
+ createSurface: (w, h) => fakeSurface(w, h),
35326
+ height: 200,
35327
+ scheduler: {
35328
+ cancelFrame: (id) => frames.queued.delete(id),
35329
+ now: () => 0,
35330
+ requestFrame: (cb) => {
35331
+ frames.queued.add(cb);
35332
+ return frames.queued.size;
35333
+ },
35334
+ },
35335
+ width: 400,
35336
+ });
35337
+ ```
35338
+
35339
+ The default factory uses `OffscreenCanvas` when present, else a canvas from the document; in environments with neither, it throws `StageUnsupportedError`.
35340
+
35341
+ ## Worker Rendering
35342
+
35343
+ 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.
35344
+
35345
+ ```ts
35346
+ // main.ts
35347
+ import { createWorkerStage } from '@vielzeug/stage/worker';
35348
+
35349
+ type Scene = Readonly;
35350
+
35351
+ const worker = new Worker(new URL('./stage.worker.ts', import.meta.url), { type: 'module' });
35352
+ const stage = createWorkerStage(canvas, worker, {
35353
+ height: 600,
35354
+ width: 800,
35355
+ });
35356
+ // The creator owns the worker: terminate it when the stage is disposed.
35357
+ stage.disposalSignal.addEventListener('abort', () => worker.terminate());
35358
+
35359
+ await stage.ready; // the worker created its stage
35360
+ stage.setTransform([1, 0, 0, 1, 0, 0]);
35361
+ stage.sendScene({ col: 3, id: 'hero', row: 2, type: 'move' });
35362
+ const blob = await stage.toBlob({ type: 'image/png' }); // correlated round-trip
35363
+ stage.dispose(); // also rejects any in-flight blob requests
35364
+ ```
35365
+
35366
+ ```ts
35367
+ // stage.worker.ts
35368
+ import { serveStage } from '@vielzeug/stage/worker';
35369
+
35370
+ serveStage(self, () => ({
35371
+ layers: [{ id: 'scene', paint: (ctx) => ctx.fillRect(0, 0, 800, 600) }],
35372
+ onScene: (scene, stage) => {
35373
+ applyMove(scene);
35374
+ stage.invalidate('scene'); // the handler owns repaints
35375
+ },
35376
+ }));
35377
+ ```
35378
+
35379
+ Notes:
35380
+
35381
+ - The worker owns its painters. `serveStage`'s `setup` returns the `layers` (and optional `onScene`/`onDispose` hooks); the main thread never names layers.
35382
+ - The canvas transfer is **one-shot**: `createWorkerStage` calls `transferControlToOffscreen()` on construction. To go back to main-thread rendering, mount a fresh `` element.
35383
+ - `toBlob()` sends a `blob` command and resolves with the worker's response; requests are correlated by id and reject with `StageDisposedError` if the client is disposed while one is in flight. `region` and `scale` are forwarded verbatim and applied worker-side.
35384
+ - `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.
35385
+ - Invalid size, DPR, or matrix input throws `StageConfigError` on the main thread, exactly like `createStage`.
35386
+ - 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.
35387
+
35388
+ ## Best Practices
35389
+
35390
+ - 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.
35391
+ - Put rarely-changing content (tile grids, backgrounds) on lower layers so pointer-driven changes only repaint upper layers.
35392
+ - Dispose the stage when the view unmounts: `using stage = createStage(...)` or `stage.dispose()`. Disposal cancels scheduled frames and releases every backing surface.
35393
+ - Treat `StageUnsupportedError` as a hard capability gap (feature-detect or surface it to the user); there is deliberately no fallback path.
35394
+ - In worker mode, invalidate only the layers a scene message changed — `onScene` runs on every forwarded payload.
35395
+
35396
+ ### Examples
35397
+
35398
+ ## Examples
35399
+
35400
+ - [Layered Repaints](./examples/layered-repaints.md)
35401
+
35402
+ ---
35403
+
33274
35404
  ## @vielzeug/tabula
33275
35405
 
33276
35406
  **Category:** utilities
@@ -38365,3 +40495,484 @@ router.subscribe((state) => {
38365
40495
  - Query Parameters: Coercion and URL State (id: `query-params`)
38366
40496
  - Route Context: Full Context Access (id: `route-context`)
38367
40497
  - URL Building: Path Matching and Active State (id: `url-building`)
40498
+
40499
+ ---
40500
+
40501
+ ## @vielzeug/wire
40502
+
40503
+ **Category:** utilities
40504
+
40505
+ ### Overview
40506
+
40507
+ ## Why Wire?
40508
+
40509
+ 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.
40510
+
40511
+ ```ts
40512
+ // Before
40513
+ // Straight lines through nodes, hand-rolled A* with nondeterministic tie
40514
+ // breaks, and recursive DFS that stack-overflows on deep graphs.
40515
+
40516
+ // After
40517
+ import { bezierRoute, findCyclicGroups, orthogonalRoute, topologicalOrder } from '@vielzeug/wire';
40518
+
40519
+ const curve = bezierRoute({ side: 'right', x: 100, y: 40 }, { side: 'left', x: 320, y: 120 });
40520
+
40521
+ // Pass every node bound; the router exempts each port's own node for its exit.
40522
+ const waypoints = orthogonalRoute(fromPort, toPort, { obstacles: nodeBounds });
40523
+ // waypoints is null when every route is blocked — render a dashed fallback.
40524
+ ```
40525
+
40526
+ | Feature | Wire | Ad-hoc routing | Graph libraries |
40527
+ | ---------------------------- | -------------------------------------------- | -------------- | ------------------ |
40528
+ | Bundle size | | n/a | Typically 10–80 kB |
40529
+ | External dependencies | | n/a | Varies |
40530
+ | Obstacle-avoiding orthogonal | Built in (A\* + bend penalty) | Rare | Sometimes |
40531
+ | Deterministic output | | Rare | Varies |
40532
+ | Iterative cycle detection | | Recursive DFS | Varies |
40533
+ | Headless: no DOM or renderer | | Varies | Usually coupled |
40534
+
40535
+ **Use Wire when** you own the node layout and rendering but want production-grade edge geometry and graph ordering as pure functions.
40536
+
40537
+ **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.
40538
+
40539
+ ## Installation
40540
+
40541
+ ```sh [pnpm]
40542
+ pnpm add @vielzeug/wire
40543
+ ```
40544
+
40545
+ ```sh [npm]
40546
+ npm install @vielzeug/wire
40547
+ ```
40548
+
40549
+ ```sh [yarn]
40550
+ yarn add @vielzeug/wire
40551
+ ```
40552
+
40553
+ ## Quick Start
40554
+
40555
+ ```ts
40556
+ import { bezierRoute, bezierToSvgPath, findCyclicGroups, orthogonalRoute, topologicalOrder } from '@vielzeug/wire';
40557
+
40558
+ // Curved wire from a right-facing port to a left-facing port.
40559
+ const curve = bezierRoute({ side: 'right', x: 100, y: 40 }, { side: 'left', x: 320, y: 120 });
40560
+ const d = bezierToSvgPath(curve); // or draw curve.c1/curve.c2 on a canvas
40561
+
40562
+ // Manhattan wire that avoids the node boxes.
40563
+ const points = orthogonalRoute(
40564
+ { side: 'right', x: 100, y: 40 },
40565
+ { side: 'left', x: 320, y: 120 },
40566
+ { obstacles: nodeBounds },
40567
+ );
40568
+
40569
+ // Execution order and cycles for a validation pass.
40570
+ const order = topologicalOrder(
40571
+ ['b', 'a', 'c'],
40572
+ [
40573
+ { from: 'a', to: 'b' },
40574
+ { from: 'b', to: 'c' },
40575
+ ],
40576
+ );
40577
+ const groups = findCyclicGroups(
40578
+ ['a', 'b'],
40579
+ [
40580
+ { from: 'a', to: 'b' },
40581
+ { from: 'b', to: 'a' },
40582
+ ],
40583
+ ); // [['a', 'b']]
40584
+ ```
40585
+
40586
+ ## Features
40587
+
40588
+ - `bezierRoute()`: cubic bezier geometry with control points anchored to port sides
40589
+ - `orthogonalRoute()`: A\* Manhattan polyline over a visibility graph built from obstacle corners, with a per-bend penalty, owner-obstacle exemption, and deterministic expansion order
40590
+ - `bezierToSvgPath()` / `polylineToSvgPath()`: SVG `d` serialization with micro-precision formatting
40591
+ - `topologicalOrder()`: Kahn ordering with stable input-order tie breaks; throws `WireGraphError` on cycles
40592
+ - `findCyclicGroups()`: iterative Tarjan SCCs — each cyclic group reported once, ordered deterministically
40593
+ - `WireError` / `WireGraphError` / `WireConfigError`: typed errors
40594
+ - Zero runtime dependencies, no DOM requirement: routes and orders are pure computations
40595
+
40596
+ ## Documentation
40597
+
40598
+ - [Usage Guide](./usage.md)
40599
+ - [API Reference](./api.md)
40600
+ - [Examples](./examples.md)
40601
+ - [Migration Guide](./migration.md)
40602
+
40603
+ ## See Also
40604
+
40605
+ - [Atlas](/atlas/): the camera and rect shapes Wire's obstacles reuse.
40606
+
40607
+ ### API Reference
40608
+
40609
+ ## API Overview
40610
+
40611
+ | Symbol | Purpose | Execution | Common gotcha |
40612
+ | --------------------------------------------------------------------- | ------------------------------------------------- | --------- | -------------------------------------------------------------------------- |
40613
+ | `bezierRoute()` | Cubic bezier geometry between two ports | Sync | Returns a `CubicBezier`, not a string — serialize with `bezierToSvgPath()` |
40614
+ | `orthogonalRoute()` | A\* Manhattan polyline avoiding padded obstacles | Sync | Returns `null` when blocked; waypoints appear only at bends |
40615
+ | `portAnchor()` | World position of a port on a node rect | Sync | `offset` is a 0..1 fraction along the side, not a distance |
40616
+ | `floatingSide()` | Rect side facing a world point | Sync | Dominant axis from the rect center; ties go horizontal |
40617
+ | `bezierToSvgPath()` | SVG `d` string from a `CubicBezier` | Sync | Emits one absolute `M`/`C` pair |
40618
+ | `polylineToSvgPath()` | SVG `d` string from a polyline | Sync | Empty input returns `''`, not an error; `cornerRadius` adds `Q` arcs |
40619
+ | `arrowhead()` | Triangle points capping a line at its tip | Sync | `direction` is normalized; returns points, not an SVG path |
40620
+ | `pointOnBezier()` / `pointOnPolyline()` | Point at a length-normalized `t` on a shape | Sync | `t` is arc length, not the raw bezier parameter |
40621
+ | `hitBezier()` / `hitPolyline()` | Closest point within a threshold | Sync | Returns `null` past the threshold; bezier `t` is sampled |
40622
+ | `topologicalOrder()` | Kahn ordering with input-order tie breaks | Sync | Throws `WireGraphError` on any cycle |
40623
+ | `findCyclicGroups()` | Cyclic SCCs via iterative Tarjan | Sync | Reports components (sets), not every elementary cycle |
40624
+ | `WireError` | Base class for all wire errors | Sync | Narrow with `instanceof WireError` |
40625
+ | `WireGraphError` | Unknown endpoints, duplicate ids, cyclic ordering | Sync | Thrown at call time |
40626
+ | `WireConfigError` | Invalid routing options | Sync | Thrown at call time |
40627
+ | `Point` / `Rect` / `PortAnchor` / `PortSide` / `CubicBezier` / `Edge` | Structural graph shapes | Sync | All readonly; treat as values |
40628
+
40629
+ ## Package Entry Point
40630
+
40631
+ | Import | Purpose |
40632
+ | ---------------- | ---------------------------------------------------------------------------------- |
40633
+ | `@vielzeug/wire` | Bezier and orthogonal routing, path serialization, ordering, cycles, types, errors |
40634
+
40635
+ ---
40636
+
40637
+ ## Core Types
40638
+
40639
+ ```ts
40640
+ type Point = Readonly;
40641
+ type Rect = Readonly;
40642
+ type PortSide = 'top' | 'right' | 'bottom' | 'left';
40643
+ type PortAnchor = Point & Readonly;
40644
+ type CubicBezier = Readonly;
40645
+ type Edge = Readonly;
40646
+ ```
40647
+
40648
+ Coordinates are screen convention: `top` is smaller y.
40649
+
40650
+ ---
40651
+
40652
+ ## Routing Functions
40653
+
40654
+ ### `portAnchor()`
40655
+
40656
+ ```ts
40657
+ function portAnchor(rect: Rect, side: PortSide, offset?: number): PortAnchor;
40658
+ ```
40659
+
40660
+ 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()`.
40661
+
40662
+ | Parameter | Type | Description |
40663
+ | --------- | ---------- | ------------------------------------------------------ |
40664
+ | `rect` | `Rect` | Node bounding box the port sits on |
40665
+ | `side` | `PortSide` | Node edge the port faces |
40666
+ | `offset` | `number` | 0..1 fraction along the side (default 0.5, the middle) |
40667
+
40668
+ **Returns:** a `PortAnchor` — the point plus its `side`. Throws `WireConfigError` for an `offset` outside 0..1 or non-finite.
40669
+
40670
+ ### `bezierRoute()`
40671
+
40672
+ ```ts
40673
+ function bezierRoute(from: PortAnchor, to: PortAnchor, options?: BezierRouteOptions): CubicBezier;
40674
+ ```
40675
+
40676
+ 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.
40677
+
40678
+ | Parameter | Type | Description |
40679
+ | --------- | -------------------- | --------------------------------------------------------------------------- |
40680
+ | `from` | `PortAnchor` | Source port with its side |
40681
+ | `to` | `PortAnchor` | Target port with its side |
40682
+ | `options` | `BezierRouteOptions` | `handleLength` (default 40) control-point reach; `selfLoop` (default false) |
40683
+
40684
+ **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`.
40685
+
40686
+ With `selfLoop: true` and both ports on the same side, each handle grows to `1.5 ×` the distance between the ports (never below `handleLength`), so a from→to pair on one node bulges outward into a visible loop instead of collapsing onto the node edge. The shape is deterministic: both handles use the same widened length, keeping the loop symmetric about the port midpoint. The option is ignored when the ports face different sides.
40687
+
40688
+ ### `floatingSide()`
40689
+
40690
+ ```ts
40691
+ function floatingSide(rect: Rect, toward: Point): PortSide;
40692
+ ```
40693
+
40694
+ Returns the side of `rect` facing the point `toward`, chosen by the dominant axis from the rect's center — the larger of `|dx|` and `|dy|` wins. Useful for ports that follow the pointer ("floating" edges) without storing a fixed side.
40695
+
40696
+ | Parameter | Type | Description |
40697
+ | --------- | ------- | -------------------------------- |
40698
+ | `rect` | `Rect` | Node bounding box |
40699
+ | `toward` | `Point` | World point the side should face |
40700
+
40701
+ **Returns:** the facing `PortSide`. Ties (`|dx| === |dy|`, including a target exactly on the center) resolve to the horizontal side, with `right` for a zero offset. Throws `WireConfigError` for non-finite rect or point coordinates.
40702
+
40703
+ ### `orthogonalRoute()`
40704
+
40705
+ ```ts
40706
+ function orthogonalRoute(from: PortAnchor, to: PortAnchor, options?: OrthogonalRouteOptions): Point[] | null;
40707
+ ```
40708
+
40709
+ 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.
40710
+
40711
+ 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.
40712
+
40713
+ | Parameter | Type | Description |
40714
+ | --------- | ------------------------ | ------------------------------------------------------------------------------------------------- |
40715
+ | `from` | `PortAnchor` | Start port; its `side` fixes the direction the route leaves it |
40716
+ | `to` | `PortAnchor` | Goal port; its `side` fixes the direction the route enters it |
40717
+ | `options` | `OrthogonalRouteOptions` | `obstacles`, `padding` (default 8), `bendPenalty` (default 12), `stub` (default 16, `0` disables) |
40718
+
40719
+ **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.
40720
+
40721
+ ### `bezierToSvgPath()`
40722
+
40723
+ ```ts
40724
+ function bezierToSvgPath(curve: CubicBezier): string;
40725
+ ```
40726
+
40727
+ Serializes as an absolute `M`/`C` command, rounded to six decimals with no `-0` or exponent noise.
40728
+
40729
+ ### `polylineToSvgPath()`
40730
+
40731
+ ```ts
40732
+ function polylineToSvgPath(points: readonly Point[], options?: PolylinePathOptions): string;
40733
+ ```
40734
+
40735
+ Serializes as absolute `M`/`L` commands, rounded to six decimals with no `-0` or exponent noise.
40736
+
40737
+ | Parameter | Type | Description |
40738
+ | --------- | --------------------- | ---------------------------------------------------------------- |
40739
+ | `points` | `readonly Point[]` | Waypoints, bends included |
40740
+ | `options` | `PolylinePathOptions` | `cornerRadius` (default 0) rounds interior corners with `Q` arcs |
40741
+
40742
+ With `cornerRadius > 0`, each interior corner is replaced by a straight run into the corner, a quadratic `Q` arc through it, and a run out — the corner point itself is not emitted. The radius is clamped per corner to half of its shortest adjacent run, so tight bends never overlap; collinear waypoints and zero-length runs are skipped, keeping the path continuous. `orthogonalRoute()` output stays a raw waypoint polyline — rounding is a rendering decision applied here at serialization time. Throws `WireConfigError` for a negative or non-finite `cornerRadius`.
40743
+
40744
+ ---
40745
+
40746
+ ## Editing Geometry
40747
+
40748
+ These helpers are DOM-free and node-model-free: they work on the raw geometry `bezierRoute()` and `orthogonalRoute()` produce, for editors that need hit-testing, markers, and drag feedback.
40749
+
40750
+ ### `arrowhead()`
40751
+
40752
+ ```ts
40753
+ function arrowhead(tip: Point, direction: Point, options?: ArrowheadOptions): Point[];
40754
+ ```
40755
+
40756
+ Builds a filled triangle capping a line at `tip`. The apex sits at `tip`; the base sits `length` behind it along `-direction`, `width` apart. `direction` may be any non-zero vector — it is normalized internally — and points the way the line arrives at the tip.
40757
+
40758
+ | Parameter | Type | Description |
40759
+ | ----------- | ------------------ | ----------------------------------------------------------------- |
40760
+ | `tip` | `Point` | Apex of the arrowhead |
40761
+ | `direction` | `Point` | Arrival direction toward the tip (normalized) |
40762
+ | `options` | `ArrowheadOptions` | `length` (default 10) shaft reach; `width` (default 6) base width |
40763
+
40764
+ **Returns:** `[tip, baseLeft, baseRight]` — three points to fill as a polygon. Throws `WireConfigError` for non-finite points, a zero `direction`, or non-positive/non-finite `length`/`width`.
40765
+
40766
+ ### `pointOnBezier()` / `pointOnPolyline()`
40767
+
40768
+ ```ts
40769
+ function pointOnBezier(curve: CubicBezier, t: number): Point;
40770
+ function pointOnPolyline(points: readonly Point[], t: number): Point;
40771
+ ```
40772
+
40773
+ Point at parameter `t` where `t` is normalized by total arc length, not by the raw bezier parameter or segment index: `t = 0.5` is the point halfway along the drawn wire. Polyline results are exact; the bezier mapping uses a fixed 64-sample arc-length lookup table, so `t` lands within roughly one sample cell of the true length fraction — sub-pixel for typical wire sizes.
40774
+
40775
+ **Returns:** the point at that length. Degenerate zero-length shapes return their start for every `t`. Throws `WireConfigError` for non-finite inputs, fewer than two polyline points, or `t` outside `[0, 1]`.
40776
+
40777
+ ### `hitBezier()` / `hitPolyline()`
40778
+
40779
+ ```ts
40780
+ function hitBezier(curve: CubicBezier, point: Point, options?: HitOptions): HitResult | null;
40781
+ function hitPolyline(points: readonly Point[], point: Point, options?: HitOptions): HitResult | null;
40782
+ ```
40783
+
40784
+ Closest point on the shape to `point`, for click selection without invisible DOM hit targets. `hitPolyline` tests every segment analytically (exact); `hitBezier` finds the nearest of 64 samples, then refines with a ternary search on the true curve, so the reported `distance` is accurate while `t` carries the table's arc-length tolerance.
40785
+
40786
+ | Parameter | Type | Description |
40787
+ | ------------------ | ---------------------------------- | -------------------------------------------------- |
40788
+ | `curve` / `points` | `CubicBezier` / `readonly Point[]` | The shape to test |
40789
+ | `point` | `Point` | Query point |
40790
+ | `options` | `HitOptions` | `threshold` (default 4) maximum distance for a hit |
40791
+
40792
+ **Returns:** a `HitResult` (`t` length-normalized in `[0, 1]`, `distance` Euclidean) or `null` when the closest point is farther than `threshold`. For zoom-independent screen picking, divide a screen-pixel threshold by the camera zoom before calling. Same validation errors as the `pointOn*` helpers.
40793
+
40794
+ ---
40795
+
40796
+ ## Graph Functions
40797
+
40798
+ ### `topologicalOrder()`
40799
+
40800
+ ```ts
40801
+ function topologicalOrder(nodeIds: readonly string[], edges: readonly Edge[]): string[];
40802
+ ```
40803
+
40804
+ 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.
40805
+
40806
+ ### `findCyclicGroups()`
40807
+
40808
+ ```ts
40809
+ function findCyclicGroups(nodeIds: readonly string[], edges: readonly Edge[]): string[][];
40810
+ ```
40811
+
40812
+ 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()`.
40813
+
40814
+ ---
40815
+
40816
+ ## Errors
40817
+
40818
+ | Class | Thrown when |
40819
+ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
40820
+ | `WireError` | Base class; catch-all via `instanceof WireError` |
40821
+ | `WireGraphError` | Unknown edge endpoints, duplicate node ids, cyclic `topologicalOrder()` |
40822
+ | `WireConfigError` | Negative or non-finite `handleLength`, `padding`, `stub`, `bendPenalty`, `cornerRadius`, edit sizes, thresholds, or `t`; bad port offset |
40823
+
40824
+ ### Usage Guide
40825
+
40826
+ ## Basic Usage
40827
+
40828
+ Wire is headless: it turns port positions, node bounds, and edge lists into path data and orderings. You own the rendering.
40829
+
40830
+ ```ts
40831
+ import { bezierRoute, bezierToSvgPath, orthogonalRoute, polylineToSvgPath, topologicalOrder } from '@vielzeug/wire';
40832
+
40833
+ // A curved wire from a right-facing port to a left-facing port.
40834
+ const curve = bezierRoute({ side: 'right', x: 100, y: 40 }, { side: 'left', x: 320, y: 120 });
40835
+ pathElement.setAttribute('d', bezierToSvgPath(curve));
40836
+
40837
+ // A Manhattan wire that routes around the node boxes.
40838
+ const points = orthogonalRoute(
40839
+ { side: 'right', x: 100, y: 40 },
40840
+ { side: 'left', x: 320, y: 120 },
40841
+ { obstacles: nodeBounds },
40842
+ );
40843
+ if (points) pathElement.setAttribute('d', polylineToSvgPath(points));
40844
+ ```
40845
+
40846
+ 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, ...)`).
40847
+
40848
+ ## Port Sides
40849
+
40850
+ 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`":
40851
+
40852
+ ```ts
40853
+ import { portAnchor } from '@vielzeug/wire';
40854
+
40855
+ // Middle of the node's right edge, facing right.
40856
+ const out = portAnchor(nodeBounds, 'right'); // { side: 'right', x, y }
40857
+ // Quarter along the top edge.
40858
+ const top = portAnchor(nodeBounds, 'top', 0.25);
40859
+ ```
40860
+
40861
+ `bezierRoute()` extends each control point outward along its port's side, so wires leave and enter nodes perpendicular to the edge:
40862
+
40863
+ ```ts
40864
+ // Bottom port of A into top port of B (top-to-bottom flow).
40865
+ bezierRoute({ side: 'bottom', x: 60, y: 100 }, { side: 'top', x: 60, y: 220 });
40866
+ ```
40867
+
40868
+ A free endpoint that is not on a node — the cursor while dragging a wire, say — picks a side explicitly: `{ ...cursor, side: 'left' }`, or computes the facing side with `floatingSide(nodeBounds, cursor)`.
40869
+
40870
+ ## Routing Around Obstacles
40871
+
40872
+ `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:
40873
+
40874
+ 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:
40875
+
40876
+ ```ts
40877
+ const points = orthogonalRoute(outPort, inPort, {
40878
+ bendPenalty: 12, // cost of one extra bend, in the same units as distance
40879
+ obstacles: nodes.map((node) => node.bounds),
40880
+ padding: 8, // keep routes this far from obstacle edges
40881
+ });
40882
+ ```
40883
+
40884
+ Four contracts matter for editors:
40885
+
40886
+ - **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.
40887
+ - **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.
40888
+ - **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.
40889
+ - **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.
40890
+
40891
+ Routes may hug the padded boundary exactly; raise `padding` if you want more clearance.
40892
+
40893
+ ## Rounded Corners
40894
+
40895
+ `polylineToSvgPath()` accepts a `cornerRadius` that replaces each interior bend with a quadratic arc — orthogonal wires stop looking like pipe fittings with one option:
40896
+
40897
+ ```ts
40898
+ const points = orthogonalRoute(outPort, inPort, { obstacles: nodeBounds });
40899
+ if (points) pathElement.setAttribute('d', polylineToSvgPath(points, { cornerRadius: 8 }));
40900
+ ```
40901
+
40902
+ The radius is clamped per corner to half of its shortest adjacent run, so a bend between two short runs simply rounds as much as fits instead of self-overlapping. The router itself never rounds: `orthogonalRoute()` keeps returning raw waypoints, and rounding stays a rendering decision you can toggle per zoom level or theme.
40903
+
40904
+ ## Editing Geometry
40905
+
40906
+ Editors need to answer "what did the user click?" without invisible DOM hit targets. The edit helpers work on the geometry the routers already produce:
40907
+
40908
+ ```ts
40909
+ import { hitBezier, hitPolyline } from '@vielzeug/wire';
40910
+
40911
+ // World-space click, threshold scaled so the pick area is zoom-independent.
40912
+ const threshold = 8 / camera.zoom;
40913
+ const hit =
40914
+ edge.geometry.kind === 'bezier'
40915
+ ? hitBezier(edge.geometry.curve, worldPoint, { threshold })
40916
+ : hitPolyline(edge.geometry.points, worldPoint, { threshold });
40917
+ if (hit) selectEdge(edge.id, hit.t); // t is normalized by arc length
40918
+ ```
40919
+
40920
+ `hit.t` and the matching `pointOnBezier()` / `pointOnPolyline()` are parameterized by arc length, so `t = 0.5` is always the midpoint of the drawn wire — useful for labels and drag handles regardless of how lopsided the underlying bezier handles are.
40921
+
40922
+ For arrowheads, `arrowhead()` returns the three triangle points capping a line at its tip; pass the arrival direction (any non-zero vector — it is normalized):
40923
+
40924
+ ```ts
40925
+ import { arrowhead, pointOnBezier } from '@vielzeug/wire';
40926
+
40927
+ const tip = curve.to;
40928
+ const arriving = { x: tip.x - curve.c2.x, y: tip.y - curve.c2.y };
40929
+ const [apex, left, right] = arrowhead(tip, arriving, { length: 8, width: 5 });
40930
+ ```
40931
+
40932
+ Two more routing-polish pieces round out editors:
40933
+
40934
+ - **`floatingSide(rect, toward)`** returns the rect side facing a point — the dominant axis from the rect center — so an edge can track the cursor across node sides without storing a fixed port side.
40935
+ - **`selfLoop: true` on `bezierRoute()`** widens both handles to `1.5 ×` the port spacing when the endpoints share a side, so an edge from a node's `out` port back to its own `in` port bulges into a visible loop instead of collapsing onto the node edge.
40936
+
40937
+ ## Ordering the Graph
40938
+
40939
+ `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:
40940
+
40941
+ ```ts
40942
+ const order = topologicalOrder(
40943
+ ['render', 'layout', 'parse'],
40944
+ [
40945
+ { from: 'parse', to: 'layout' },
40946
+ { from: 'layout', to: 'render' },
40947
+ ],
40948
+ ); // ['parse', 'layout', 'render']
40949
+ ```
40950
+
40951
+ 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:
40952
+
40953
+ ```ts
40954
+ import { findCyclicGroups } from '@vielzeug/wire';
40955
+
40956
+ const groups = findCyclicGroups(nodeIds, edges);
40957
+ // [['a', 'b']] — a two-node loop; a self-loop appears as [['a']].
40958
+ ```
40959
+
40960
+ 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.
40961
+
40962
+ ## Best Practices
40963
+
40964
+ - 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.
40965
+ - Feed only the obstacles near the edge's corridor, not the whole document — cull with an atlas spatial index for large graphs.
40966
+ - Treat `topologicalOrder()` as the execution-order oracle for dataflow editors, and `findCyclicGroups()` as the validator that explains _why_ it threw.
40967
+ - Round-trip path strings through `polylineToSvgPath()` and `bezierToSvgPath()` rather than assembling `d` strings by hand; they keep precision stable for diffing and serialization.
40968
+
40969
+ ### Examples
40970
+
40971
+ ## Examples
40972
+
40973
+ - [Edges Around Nodes](./examples/edges-around-nodes.md)
40974
+
40975
+ ### REPL Examples
40976
+
40977
+ - edit - Arrowheads, arc-length t, hit testing (id: `wire-edit`)
40978
+ - orthogonalRoute - Edges around nodes (id: `wire-routing`)