@vielzeug/codex 26.11.24 → 26.11.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/data/snapshot.json +1 -0
- package/dist/catalog.d.ts +35 -39
- package/dist/catalog.js +112 -139
- package/dist/catalog.js.map +1 -1
- package/dist/cli.js +25 -16
- package/dist/cli.js.map +1 -1
- package/dist/http.js +1 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +5 -7
- package/dist/index.js +4 -6
- package/dist/index.js.map +1 -1
- package/dist/server.d.ts +9 -7
- package/dist/server.js +14 -6
- package/dist/server.js.map +1 -1
- package/dist/snapshot.d.ts +8 -22
- package/dist/snapshot.js +41 -176
- package/dist/snapshot.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/packages.js +49 -82
- package/dist/tools/packages.js.map +1 -1
- package/dist/tools/refine.d.ts +1 -2
- package/dist/tools/refine.js +90 -82
- package/dist/tools/refine.js.map +1 -1
- package/dist/tools/schema.d.ts +2 -1
- package/dist/tools/schema.js +9 -5
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/shared.d.ts +2 -2
- package/dist/types.d.ts +77 -64
- package/dist/types.js +6 -2
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/skills/vielzeug/SKILL.md +18 -20
- package/data/catalog.json +0 -2539
- package/data/llms-full.txt +0 -40978
- package/data/llms.txt +0 -60
- package/data/manifest.json +0 -4
- package/data/packages/archive.json +0 -87
- package/data/packages/arsenal.json +0 -270
- package/data/packages/assay.json +0 -52
- package/data/packages/atlas.json +0 -81
- package/data/packages/bard.json +0 -38
- package/data/packages/beacon.json +0 -51
- package/data/packages/clockwork.json +0 -69
- package/data/packages/codex.json +0 -37
- package/data/packages/coins.json +0 -99
- package/data/packages/conduit.json +0 -67
- package/data/packages/courier.json +0 -66
- package/data/packages/dnd.json +0 -60
- package/data/packages/familiar.json +0 -38
- package/data/packages/flux.json +0 -97
- package/data/packages/focus.json +0 -51
- package/data/packages/forge.json +0 -65
- package/data/packages/gesture.json +0 -65
- package/data/packages/herald.json +0 -80
- package/data/packages/illusionist.json +0 -132
- package/data/packages/ink.json +0 -41
- package/data/packages/keymap.json +0 -55
- package/data/packages/ledger.json +0 -60
- package/data/packages/lingua.json +0 -68
- package/data/packages/mesh.json +0 -52
- package/data/packages/necromancer.json +0 -55
- package/data/packages/orbit.json +0 -100
- package/data/packages/ore.json +0 -78
- package/data/packages/palette.json +0 -42
- package/data/packages/patchwork.json +0 -55
- package/data/packages/postmaster.json +0 -49
- package/data/packages/prism.json +0 -99
- package/data/packages/pulse.json +0 -71
- package/data/packages/refine.json +0 -36
- package/data/packages/ripple.json +0 -84
- package/data/packages/rune.json +0 -78
- package/data/packages/sandbox.json +0 -26
- package/data/packages/scout.json +0 -66
- package/data/packages/scribe.json +0 -57
- package/data/packages/scroll.json +0 -110
- package/data/packages/sentinel.json +0 -46
- package/data/packages/sigil.json +0 -52
- package/data/packages/sourcerer.json +0 -86
- package/data/packages/spell.json +0 -126
- package/data/packages/stage.json +0 -26
- package/data/packages/tabula.json +0 -39
- package/data/packages/tandem.json +0 -31
- package/data/packages/tavern.json +0 -34
- package/data/packages/tempo.json +0 -68
- package/data/packages/vault.json +0 -81
- package/data/packages/ward.json +0 -77
- package/data/packages/wayfinder.json +0 -126
- package/data/packages/wire.json +0 -51
- package/data/refine.json +0 -17277
- package/dist/consumer.d.ts +0 -17
- package/dist/consumer.js +0 -114
- package/dist/consumer.js.map +0 -1
- package/dist/port.d.ts +0 -2
- package/dist/port.js +0 -12
- package/dist/port.js.map +0 -1
package/data/packages/atlas.json
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "// Public root surface of @vielzeug/atlas. Every public export goes through this file.\n\nexport {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';\nexport { AtlasConfigError, AtlasError } from './errors.js';\nexport {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';\nexport { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';\nexport { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';\nexport {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';\nexport type { Matrix, Point, Rect, Size } from './shapes.js';\nexport {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';\nexport {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Atlas: Spatial Math for 2D Canvases'\ndescription: Camera transforms, matrix and rect math, polygon hit-testing, and a dynamic R-tree spatial index for infinite 2D canvases.\npackage: atlas\ncategory: utilities\nkeywords:\n [\n camera,\n viewport,\n zoom,\n pan,\n matrix,\n rect,\n aabb,\n hit-testing,\n r-tree,\n spatial-index,\n culling,\n marquee,\n geometry,\n canvas,\n ]\nexports: [createCamera, createSpatialIndex, multiply, invert, rectsIntersect, pointInPolygon, snapRect]\nrelated: [gesture, ink, wire]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"atlas\" />\n\n## Why Atlas?\n\nEvery infinite canvas re-implements the same three things badly: a camera that keeps the point under your cursor fixed while zooming, a hit-test that stops being O(n) once the scene grows, and selection and snapping math for moving rects. Atlas ships them as pure, headless primitives: a viewport-centred camera with anchor-preserving transforms and injectable animation scheduling, matrix/rect math, exact polygon narrow-phase, and a dynamic R-tree for O(log n) queries.\n\n```ts\n// Before\n// Hand-rolled transform stacks, linear scans on every pointermove, and\n// selection boxes that drift while zooming.\n\n// After\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\nconst camera = createCamera();\ncamera.zoomAt({ x: 400, y: 300 }, 1.2); // world point under (400,300) stays put\n\nconst index = createSpatialIndex();\nindex.set('shape-1', { height: 40, width: 60, x: 12, y: 8 });\nconst hits = index.queryRect(camera.visibleRect); // viewport culling, returns ids\n```\n\n| Feature | Atlas | Ad-hoc math | Full scene libraries |\n| ------------------------------------- | -------------------------------------------- | ----------- | -------------------- |\n| Bundle size | <PackageInfo package=\"atlas\" type=\"size\" /> | n/a | Typically 20–100 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a | Varies |\n| Anchor-preserving zoom/rotate | Built in | Drifts | Yes |\n| Dynamic R-tree hit-testing | Built in | O(n) scans | Yes |\n| Headless: no DOM, canvas, or renderer | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies | Usually coupled |\n\n<div class=\"decision-callout\">\n\n**Use Atlas when** you own the render loop and scene model but want correct, tested camera, geometry, and spatial-query math without writing it yourself.\n\n**Consider a full canvas engine when** you want a retained scene graph, built-in rendering, and event routing wholesale instead of headless primitives.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/atlas\n```\n\n```sh [npm]\nnpm install @vielzeug/atlas\n```\n\n```sh [yarn]\nyarn add @vielzeug/atlas\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\n// state.x/y is the world point at the viewport centre\nconst camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });\ncamera.resize({ height: 600, width: 800 });\ncamera.panBy(20, 0); // content follows the drag\ncamera.fitBounds({ height: 400, width: 600, x: -50, y: -50 }, { padding: 40 });\n\nconst index = createSpatialIndex();\nindex.set('a', { height: 10, width: 10, x: 0, y: 0 });\nindex.queryPoint({ x: 5, y: 5 }); // ['a']\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createCamera()`: viewport-centred state, pan, anchor-preserving zoom/rotate, `fitBounds()`, rotated `visibleRect`, and `animateTo()` with an injectable frame scheduler\n- `createSpatialIndex()`: dynamic R-tree (Guttman quadratic split) with `set`/`delete`/`get`/`queryRect`/`queryPoint` over ids\n- Matrix helpers: `multiply`, `invert`, `apply`, `translate`, `scale`, `rotate`, `around`, `scaleOf`, `toCssMatrix` in Canvas2D element order\n- Rect math: union, closed-interval intersection, containment, inflation, and bounds-from-points\n- Snapping: `snapRect()` alignment/grid/equal-gap guides with `kind`-tagged targets, plus pure `alignRects()`/`distributeRects()`\n- Narrow-phase geometry: `pointInPolygon`, `distanceToPolyline`, `pointNearPolygon` for exact stroke and polygon hit-testing\n- Frames: `frameMatrix()` local→world placement, `boundsOfFrame()` world AABBs, and `resizeRect()` editor resize math with min and aspect locks\n- `AtlasError` / `AtlasConfigError`: typed errors; the camera follows the Vielzeug disposal contract\n- Zero runtime dependencies, no DOM requirement: works in Node, Workers, and SSR\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Gesture](/gesture/): pinch and wheel handles feed `zoomAt()` and `panBy()` directly.\n- [Ink](/ink/): stroke geometry whose bounds and outlines Atlas hit-tests.\n- [Wire](/wire/): edge routing for node editors sharing the same world coordinates.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Atlas: API Reference'\ndescription: API reference for the Atlas camera, spatial index, matrix, rect, frame, and narrow-phase geometry helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ------------------------------------ | ---------------------------------------------------------- | --------- | ----------------------------------------------------------- |\n| `createCamera()` | Pan/zoom/rotate camera with anchor-preserving transforms | Sync | `x`/`y` is the world point at the viewport centre |\n| `createSpatialIndex()` | Dynamic R-tree over world-space rects | Sync | Broad-phase only: bounds overlap, not exact shape hits |\n| `multiply()` etc. | Canvas2D-order matrix composition | Sync | Element order is `[a,b,c,d,e,f]`, not row-major 3×3 |\n| `rectFromPoints()` | AABB of a point set | Sync | Returns `null` only for iterable input that may be empty |\n| `pointInPolygon()` | Even-odd ray-cast containment | Sync | Boundary points are implementation-defined; add tolerance |\n| `distanceToPolyline()` | Distance to the nearest segment | Sync | Returns `Infinity` for empty paths |\n| `snapRect()` | Alignment, grid, and equal-gap snapping with guides | Sync | Each axis resolves independently; alignment wins |\n| `alignRects()` | Align rects to a shared edge or center | Sync | Pure: returns new rects, input untouched |\n| `distributeRects()` | Equalize gaps along one axis | Sync | Needs 3+ rects; outermost rects stay fixed |\n| `frameMatrix()` | Local→world matrix for a positioned, rotated, scaled frame | Sync | `origin` is a world pivot; defaults to `{ x, y }` |\n| `boundsOfFrame()` | AABB of a rect under a frame matrix | Sync | Grows the bounds for rotation; not a tight oriented box |\n| `resizeRect()` | Resize a rect by dragging named edges | Sync | `aspect` is width/height; corner drags derive the free axis |\n| `AtlasError` | Base class for all atlas errors | Sync | Narrow with `instanceof AtlasError` |\n| `AtlasConfigError` | Invalid options and negative tolerances | Sync | Thrown at call time |\n| `Point` / `Rect` / `Size` / `Matrix` | Structural shapes shared across the canvas toolkit | Sync | All readonly; treat as values |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ---------------------- | ---------------------------------------------------------------------- |\n| `@vielzeug/atlas` | Camera, spatial index, matrix/rect/geometry helpers, types, and errors |\n| `@vielzeug/atlas/grid` | Square-tile math, recursive shadowcasting FOV, and fog-of-war state |\n\n---\n\n## Core Types\n\n```ts\ntype Point = Readonly<{ x: number; y: number }>;\ntype Size = Readonly<{ width: number; height: number }>;\ntype Rect = Readonly<{ x: number; y: number; width: number; height: number }>;\n/** Canvas2D/DOMMatrix element order: [a, b, c, d, e, f]. */\ntype Matrix = readonly [number, number, number, number, number, number];\n```\n\n---\n\n## `createCamera()`\n\n```ts\nfunction createCamera(options?: CameraOptions): Camera;\n```\n\nCreates a mutable camera. `state.x`/`state.y` name the world point at the **centre** of the viewport, so a saved state renders the same view on any screen size.\n\n| Parameter | Type | Description |\n| --------- | --------------- | ----------------------------------------------------------------------------------- |\n| `options` | `CameraOptions` | `initial` state, `viewport` size in CSS px, `minZoom`/`maxZoom` clamps, `scheduler` |\n\n**Returns:** `Camera` handle.\n\n**Example**\n\n```ts\nimport { createCamera } from '@vielzeug/atlas';\n\nconst camera = createCamera({\n initial: { zoom: 1.5 },\n maxZoom: 8,\n minZoom: 0.1,\n viewport: { height: 600, width: 800 },\n});\ncamera.zoomAt({ x: 400, y: 300 }, 1.2);\n```\n\nWithout `viewport` the camera starts at 0×0, where the centre is the origin; call `camera.resize()` once the real size is known (a `ResizeObserver` on the viewport element is the usual source).\n\nThrows `AtlasConfigError` when clamps violate `0 < minZoom <= maxZoom` or initial coordinates are non-finite.\n\n### Camera members\n\n| Member | Description |\n| ---------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `state` | Current `{ x, y, zoom, rotation }` (readonly snapshot) |\n| `viewport` | Current viewport `Size` in CSS px |\n| `matrix` / `inverse` | world → screen / screen → world matrices; `inverse` is always defined |\n| `toScreen(p)` / `toWorld(p)` | Point transforms |\n| `set(target)` | Jump to a partial state immediately, cancelling any animation |\n| `resize(size)` | Change the viewport size, keeping the world centre fixed |\n| `panBy(dx, dy)` | Screen-space pan; content follows the delta |\n| `zoomAt(screenPoint, factor)` | Multiplicative zoom holding the world point under `screenPoint` fixed |\n| `rotateAt(screenPoint, delta)` | Rotation (radians) holding the world point under `screenPoint` fixed |\n| `fitBounds(bounds, { padding? })` | Frame `bounds` in the current viewport at current rotation |\n| `visibleRect` | World AABB of the rotated viewport, for culling (getter) |\n| `animateTo(target, options?)` | Animate `{ x, y, zoom, rotation }`; replaces any running animation |\n| `stop()` | Cancel the running animation without completing it |\n| `subscribe(listener, options?)` | State-change listener; returns an unsubscribe function |\n| `dispose()` / `disposed` / `disposalSignal` / `[Symbol.dispose]` | Vielzeug disposal contract; disposal aborts animations |\n\nDirect manipulation (`set`, `resize`, `panBy`, `zoomAt`, `rotateAt`, `fitBounds`) cancels a running `animateTo` first, so user input is never overwritten by the next animation frame. After `dispose`, every mutating method is a no-op and `subscribe` returns a no-op unsubscribe.\n\n`AnimationOptions`: `duration` (ms, default 250), `easing` (default ease-in-out), `signal` (abort mid-flight; the animation stops where it is). Zoom interpolates in log space; rotation takes the shortest angular path and lands normalized to `(-π, π]`. A zoom-only animation keeps the viewport centre fixed.\n\n`FrameScheduler`: `{ requestFrame, cancelFrame, now }`. Defaults to `requestAnimationFrame`/`performance.now()`; inject a fake one in tests.\n\n---\n\n## `createSpatialIndex()`\n\n```ts\nfunction createSpatialIndex<K = string>(options?: SpatialIndexOptions): SpatialIndex<K>;\n```\n\nCreates a dynamic R-tree (Guttman, quadratic split) keyed by ids. The index stores only ids and rects — you keep your data in your own `Map` and look it up from returned ids — so stored values can never go stale.\n\n| Parameter | Type | Description |\n| --------- | --------------------- | -------------------------------------------- |\n| `options` | `SpatialIndexOptions` | `maxEntriesPerNode` (integer ≥ 4, default 8) |\n\n**Returns:** `SpatialIndex<K>` handle.\n\n**Example**\n\n```ts\nimport { createSpatialIndex } from '@vielzeug/atlas';\n\nconst shapes = new Map<string, Shape>();\nconst index = createSpatialIndex();\nindex.set('a', { height: 10, width: 10, x: 0, y: 0 });\nconst hits = index.queryRect(marquee); // string[] of ids\nconst shape = shapes.get(hits[0]);\n```\n\n### SpatialIndex members\n\n| Member | Description |\n| ----------------------------------- | ----------------------------------------------------------------------------------- |\n| `set(id, rect)` | Insert, or move an existing id; a no-op when the rect is unchanged |\n| `delete(id)` | `true` when removed, `false` when unknown |\n| `get(id)` | The current `Rect` for an id, or `undefined` |\n| `has(id)` | Membership test |\n| `queryRect(rect)` | Ids whose bounds overlap **or touch** `rect` (closed intervals) |\n| `queryPoint(point, { tolerance? })` | Ids within `tolerance` of `point` (default 0, inclusive); throws on negative values |\n| `clear()` / `size` / `bounds` | Reset, entry count, aggregate bounds (`null` when empty) |\n\nClosed-interval semantics mean zero-area rects (lines, points) are findable: a horizontal line entry is returned by any query rect that crosses it. The index owns no resources, so it has no disposal contract — drop the reference when done.\n\n---\n\n## Matrix Functions\n\nAll matrices use Canvas2D element order `[a, b, c, d, e, f]`; composition `multiply(a, b)` applies `a` first, then `b` (same order as chained `ctx.transform()` calls).\n\n| Function | Description |\n| ------------------------ | ------------------------------------------------- |\n| `IDENTITY` | Frozen identity matrix |\n| `multiply(a, b)` | Compose two matrices |\n| `apply(matrix, point)` | Transform a point |\n| `translate(tx, ty)` | Translation builder |\n| `scale(sx, sy?)` | Scale builder (`sy` defaults to `sx`) |\n| `rotate(radians)` | Rotation builder; positive is clockwise on screen |\n| `invert(matrix)` | Inverse; `null` for zero determinant |\n| `around(anchor, matrix)` | `translate(anchor) · matrix · translate(-anchor)` |\n| `scaleOf(matrix)` | Average axis scale (0 for degenerate matrices) |\n| `toCssMatrix(matrix)` | `matrix(...)` CSS value |\n\n---\n\n## Rect Functions\n\n| Function | Description |\n| ----------------------------------------------------------- | ------------------------------------------------------------------------------ |\n| `rectFromPoints(points)` | AABB of a point set; `null` for iterable input, non-null for a non-empty tuple |\n| `rectRight(rect)` / `rectBottom(rect)` / `rectCenter(rect)` | Edge and center accessors |\n| `unionRect(a, b)` | Smallest rect containing both |\n| `intersectRect(a, b)` | Overlap rect; `null` only when disjoint; touching yields a zero-area rect |\n| `rectsIntersect(a, b)` | Overlap-or-touch test (closed intervals) |\n| `containsRect(outer, inner)` / `containsPoint(rect, point)` | Inclusive containment tests |\n| `inflateRect(rect, amount)` | Grow every edge by `amount` |\n\n`rectFromPoints` has two overloads: pass a literal non-empty tuple (`rectFromPoints([a, b])`) for a guaranteed `Rect`, or any `Iterable<Point>` for `Rect | null`.\n\n---\n\n## Frame Functions\n\nA frame places a local shape in world space: a position, an optional clockwise rotation (radians), and an optional scale pivoting around a world `origin`.\n\n```ts\nfunction frameMatrix(options: FrameOptions): Matrix;\nfunction boundsOfFrame(rect: Rect, matrix: Matrix): Rect;\nfunction resizeRect(rect: Rect, edges: ResizeEdges, point: Point, options?: ResizeOptions): Rect;\n```\n\n| Function | Description |\n| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `frameMatrix({ x, y, rotation?, scale?, origin? })` | Local→world matrix: `around(origin, rotate · scale) · translate(x, y)`; `origin` defaults to `{ x, y }`, `scale` is a number or `{ x?, y? }` |\n| `boundsOfFrame(rect, matrix)` | Axis-aligned world bounds: the AABB of the four transformed corners |\n| `resizeRect(rect, edges, point, { min?, aspect? })` | Resized rect dragging the edge(s) named by `edges` (`'e'`, `'w'`, `'n'`, `'s'`, or a corner like `'nw'`) to `point`; opposite edge(s) stay fixed |\n\n`frameMatrix` composes the matrix helpers for the common positioned-shape case, so `apply(frameMatrix({ rotation, scale, x, y }), localPoint)` places a shape's local coordinates in the world. `boundsOfFrame` pairs with it for culling and selection: rotation grows the AABB, which is what a spatial index needs.\n\n`resizeRect` is the resize-handle math for editors. `min` (default 0) keeps the result from collapsing on either axis. `aspect` (width/height) locks the ratio: a corner drag derives the free axis from the axis that moved further, an edge drag grows the free dimension about its centre.\n\n```ts\nimport { boundsOfFrame, frameMatrix, resizeRect } from '@vielzeug/atlas';\n\nconst frame = frameMatrix({ rotation: Math.PI / 6, scale: 2, x: 100, y: 50 });\nboundsOfFrame({ height: 40, width: 100, x: 0, y: 0 }, frame); // world AABB\nresizeRect(selection, 'se', worldPointer, { min: 4 }); // drag the bottom-right corner\n```\n\nAll three throw `AtlasConfigError` on non-finite inputs; `resizeRect` also throws for unknown `edges`, a negative `min`, or a non-positive `aspect`.\n\n---\n\n## Geometry Functions\n\n| Function | Description |\n| --------------------------------------------- | --------------------------------------------------------------------------- |\n| `pointInPolygon(polygon, point)` | Even-odd ray-cast containment |\n| `distanceToPolyline(path, point)` | Distance to the nearest segment; `Infinity` for empty paths |\n| `pointNearPolygon(polygon, point, tolerance)` | Inside the polygon OR within `tolerance` of its outline; throws on negative |\n\n---\n\n## Snapping Functions\n\n| Function | Description |\n| ------------------------------ | ---------------------------------------------------------------------------------------------- |\n| `snapRect(rect, options)` | Snapped `{ delta, guides }` against candidate rects, grid lines, and equal gaps |\n| `alignRects(rects, edge)` | Copies aligned to a shared `left`/`horizontal-center`/`right`/`top`/`vertical-center`/`bottom` |\n| `distributeRects(rects, axis)` | Copies with equalized gaps along `'x'` or `'y'` |\n\n`snapRect` options: `candidates` (rects to snap to; the moving rect itself must not be included), `grid` (`{ x?, y? }` line spacing), `spacing` (enable equal-gap centering, default `false`), `threshold` (max snap distance; throws `AtlasConfigError` when negative). Each axis resolves independently to its nearest target within `threshold` (inclusive) among candidate anchors (left/center/right, top/center/bottom) and grid lines; the guide's `kind` reports which one engaged. When no target engaged on an axis, `spacing: true` centers the rect between its nearest neighbors when the two gaps can be made equal within `threshold`. A candidate counts as a neighbor only when it overlaps the moving rect on the perpendicular axis, and both sides need one.\n\nA `SnapGuide` is `{ axis, kind, position, from, to, marks? }`: `axis` is the axis the guide line is perpendicular to, `kind` is `'grid'`, `'object'`, or `'spacing'` (what the snap engaged, for dashed vs solid rendering), `position` is the world coordinate of the line, and `from`/`to` span the line along the other axis. Spacing guides sit at the position the rect actually occupies after both axes snapped, and carry `marks`: the centers of the two equal gaps, to draw as × markers. `alignRects` and `distributeRects` are pure; distribution keeps the outermost rects fixed and returns input copies unchanged for fewer than three rects.\n\n---\n\n## Grid Functions\n\nFrom the `@vielzeug/atlas/grid` subpath:\n\n| Function | Returns |\n| -------------------------------------- | ----------------------------------------------------------------------------------------------- |\n| `worldToTile(point, grid)` | `TileCoord` (`{ col, row }`) containing the point (floor division) |\n| `tileToRect(coord, grid)` | World `Rect` of the tile |\n| `tileCenter(coord, grid)` | World `Point` at the tile's centre |\n| `visibleTileRange(view, grid)` | `TileRange` (`minCol/maxCol/minRow/maxRow`) intersecting a world rect |\n| `iterateTileRange(range)` | Generator over every `TileCoord` in a range |\n| `tileKey(coord)` | Stable `\"col:row\"` string |\n| `computeFov(origin, radius, options?)` | `Set<string>` of visible `tileKey`s (8-octant recursive shadowcasting) |\n| `createFog()` | Three-state fog tracker over tile keys: `update`/`state`/`visible`, `exportState`/`importState` |\n\n`grid` is `{ tileSize }` (positive; `worldToTile`/`tileToRect`/`tileCenter`/`visibleTileRange` throw `AtlasConfigError` otherwise, as does a negative/non-integer FOV `radius`). `computeFov` options: `blocks(coord)` returns true when sight cannot pass through the tile; blocking tiles within range are themselves visible. The origin is always in the result. `TileCoord` is `{ col, row }`. `createFog()` stores `tileKey` strings, so a `computeFov` result feeds `fog.update()` directly: one call demotes the previously visible tiles to `seen` and marks the new keys `visible`. `fog.visible` is a `ReadonlySet<string>`.\n\n---\n\n## Errors\n\n| Class | Thrown when |\n| ------------------ | ------------------------------------------------------------------------------- |\n| `AtlasError` | Base class; catch-all via `instanceof AtlasError` |\n| `AtlasConfigError` | Invalid options/clamps, negative snap or query tolerances, and bad frame inputs |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Atlas: Usage Guide'\ndescription: Drive a camera, index shapes in an R-tree, and hit-test points, marquee rects, and polygons with Atlas.\n---\n\n[[toc]]\n\n## Basic Usage\n\nAtlas is headless: it never touches the DOM or a canvas. You feed it input events and scene rectangles, and it answers where things are.\n\n```ts\nimport { createCamera, createSpatialIndex } from '@vielzeug/atlas';\n\n// Camera: (x, y) is the world point shown at the viewport centre.\nconst camera = createCamera({ initial: { x: 0, y: 0, zoom: 1 } });\ncamera.resize({ height: viewport.clientHeight, width: viewport.clientWidth });\n\n// Screen → world for input handling.\nconst world = camera.toWorld({ x: event.offsetX, y: event.offsetY });\n\n// World → screen for positioning DOM overlays.\nconst screen = camera.toScreen(shape.position);\n```\n\n## Coordinate Spaces\n\nAtlas works in three spaces and never guesses between them:\n\n- **Client space**: `PointerEvent.clientX/Y`. Subtract the viewport's `getBoundingClientRect()` offset before handing coordinates to the camera.\n- **Screen space**: CSS pixels from the viewport element's top-left. `toWorld()` and `zoomAt()` take screen points. The camera learns this size through `resize()` — a `ResizeObserver` on the viewport element is the usual source.\n- **World space**: your scene coordinates. `camera.matrix` maps world → screen; `zoom` is screen pixels per world unit.\n\nPositive `rotation` is clockwise on screen (y grows downward) and is kept normalized to `(-π, π]`. `camera.matrix` uses Canvas2D element order `[a, b, c, d, e, f]`, so you can hand it straight to `ctx.setTransform()` (multiply by DPR first) or hand it to `toCssMatrix()` for DOM overlays. The getter is a cached composite recomputed only when the camera changes.\n\n## Zooming to the Cursor\n\n`zoomAt()` keeps the world point under a screen point fixed while the zoom changes — the standard infinite-canvas feel:\n\n```ts\nwheelElement.addEventListener('wheel', (event) => {\n const factor = Math.exp(-event.deltaY * 0.0015);\n camera.zoomAt({ x: event.offsetX, y: event.offsetY }, factor);\n});\n```\n\n`rotateAt()` does the same for rotation. Both clamp against `minZoom`/`maxZoom` and still hold the anchor exactly at the clamp.\n\n## Panning and Fitting\n\n`panBy(dx, dy)` takes a screen-space delta; content follows the drag. `fitBounds()` frames a world rect inside the current viewport with optional padding, preserving the current rotation:\n\n```ts\ncamera.panBy(event.movementX, event.movementY);\ncamera.fitBounds(selectionBounds, { padding: 48 });\n```\n\nBecause `state.x`/`state.y` is the world point at the viewport centre, a saved camera state re-frames the same view on any screen size, and a zoom-only `animateTo({ zoom })` keeps the view centred where the user is looking.\n\n## Animating the Camera\n\n`animateTo()` interpolates position linearly and zoom in log space (multiplicative zoom feels linear to the eye). Rotation takes the shortest angular path. Pass an injectable scheduler to drive animations from your render loop or tests:\n\n```ts\ncamera.animateTo(\n { x: 250, y: 100, zoom: 2 },\n {\n duration: 300,\n signal: controller.signal, // abort mid-flight; the animation stops where it is\n },\n);\n```\n\n## Indexing the Scene\n\n`createSpatialIndex()` is a dynamic R-tree keyed by ids. Index every shape by its world-space bounding box, then answer three questions fast: what is under this point, what does this marquee rect touch, and what is inside the viewport:\n\n```ts\nconst index = createSpatialIndex(); // keys default to string\n\nindex.set(shape.id, shape.bounds); // insert, and again after every move\nindex.delete(shape.id); // on delete\n\n// Viewport culling each frame.\nconst visibleIds = index.queryRect(camera.visibleRect);\n\n// Marquee selection — the index returns ids; your own Map holds the data.\nconst selected = index.queryRect(marquee).map((id) => shapes.get(id));\n\n// Hover: tolerance widens the point into a box for fat-finger targets.\nconst hovered = index.queryPoint(worldPoint, { tolerance: 4 / camera.state.zoom });\n```\n\nThe index stores only ids and rects, so it can never hand back a stale copy of your data — call `set()` with the new rect after each committed move. Queries use closed intervals: touching edges count, and zero-area rects (lines, points) are findable. The R-tree is broad-phase only: it answers \"bounding boxes overlap or touch\". For exact hits on polygonal shapes, follow up with the narrow-phase helpers below.\n\n## Exact Hit-Testing\n\n```ts\nimport { pointNearPolygon, pointInPolygon } from '@vielzeug/atlas';\n\npointInPolygon(polygon, worldPoint); // even-odd ray cast\npointNearPolygon(polygon, worldPoint, 2); // inside OR within 2 units of the outline\n```\n\nBuild the polygon from the shape's actual corners (rotate each point yourself with `apply()` if needed) and index its axis-aligned hull in the R-tree. `pointNearPolygon` is what a vector tool needs to hit-test a stroked (unfilled) shape: the outline band plus the interior both count.\n\n## Snapping and Alignment\n\nWhile a shape moves, one `snapRect()` call snaps it to nearby shapes, grid lines, and equal gaps, and returns the guides to draw on an overlay:\n\n```ts\nimport { snapRect } from '@vielzeug/atlas';\n\nconst snap = snapRect(dragRect, {\n candidates: otherSelectedOutRects,\n grid: { x: 50, y: 50 },\n spacing: true, // opt into equal-gap spacing between neighbors\n threshold: 8,\n});\nconst snapped = { ...dragRect, x: dragRect.x + snap.delta.x, y: dragRect.y + snap.delta.y };\n// snap.guides: [{ axis, kind, position, from, to, marks? }] in world coordinates — draw them through the camera.\n```\n\nEach axis resolves independently to its nearest target within `threshold` among candidate anchors (left/center/right, top/center/bottom) and grid lines; the guide's `kind` says which one engaged. With `spacing: true`, an axis that found no target at all falls back to img.ly-style equal-gap centering: the rect centers itself between its nearest neighbors when the two gaps can be made equal within `threshold`. A candidate only counts as a neighbor when it overlaps the moving rect on the perpendicular axis, and both sides need one, so a lone shape never spacing-snaps.\n\nEvery guide carries `kind: 'grid' | 'object' | 'spacing'` so you can style them apart (dashed for grid, solid for objects, × marks at `marks` for spacing). `axis` is the axis the line is perpendicular to: an `axis: 'x'` guide is a vertical line at `position`, running from `from` to `to`. Spacing guides sit at the position the rect actually occupies after both axes snapped, so the marker lines up with the shape. On drop, commit `snapped` to your model so undo history records the final position, not the raw pointer position.\n\nAfter a multi-select, align or distribute with the pure helpers and record one command:\n\n```ts\nimport { alignRects, distributeRects } from '@vielzeug/atlas';\n\nconst aligned = alignRects(selectedRects, 'horizontal-center'); // copies, same order\nconst spread = distributeRects(selectedRects, 'x'); // equal gaps, outermost fixed\n```\n\n## Matrix Helpers\n\nFor custom transforms, the matrix functions use Canvas2D order and compose left-to-right like `ctx.transform()`:\n\n```ts\nimport {\n apply,\n around,\n IDENTITY,\n invert,\n multiply,\n rotate,\n scale,\n scaleOf,\n toCssMatrix,\n translate,\n} from '@vielzeug/atlas';\n\nconst transform = multiply(multiply(scale(2), rotate(Math.PI / 4)), translate(10, 5));\napply(transform, { x: 1, y: 0 }); // transformed point\ninvert(transform); // null for degenerate matrices\naround({ x: 100, y: 100 }, scale(2)); // scale about a point, not the origin\nscaleOf(transform); // average axis scale\ntoCssMatrix(transform); // 'matrix(...)' for CSS transforms\n```\n\n## Frames and Resizing\n\nShapes on a board are placed with a position, an optional rotation, and an optional scale. `frameMatrix()` composes that into one local→world matrix, and `boundsOfFrame()` turns a local rect into the world AABB your spatial index and selection queries need:\n\n```ts\nimport { apply, boundsOfFrame, frameMatrix } from '@vielzeug/atlas';\n\nconst frame = frameMatrix({ rotation: Math.PI / 6, scale: 2, x: 100, y: 50 });\nconst world = apply(frame, localPoint); // local → world\nconst aabb = boundsOfFrame(localRect, frame); // world AABB, ready for index.set()\n```\n\n`origin` pivots rotation and scale around a world point; it defaults to `{ x, y }`, which makes rotation and scale pure post-transforms of the placement. `toCssMatrix(frame)` feeds the same transform straight to a DOM overlay.\n\nResize handles are the other half of editor math. `resizeRect()` takes the dragged handle's direction (`'e'`, `'nw'`, …), the pointer's world position, and keeps the opposite edge(s) fixed:\n\n```ts\nimport { resizeRect } from '@vielzeug/atlas';\n\n// Dragging the bottom-right handle; shapes never collapse below 4 units.\nconst next = resizeRect(selection, 'se', worldPointer, { min: 4 });\n// Shift-drag convention: lock the selection's current ratio.\nconst square = resizeRect(selection, 'se', worldPointer, {\n aspect: selection.width / selection.height,\n min: 4,\n});\n```\n\nOn a corner drag with `aspect` set, the axis the pointer moved further along drives the other, so the drag feels direct from either side. Commit the returned rect to your model on pointer-up, the same way you commit a snapped move.\n\n## Tile Grids\n\nTile and map editors live on a square grid. The `@vielzeug/atlas/grid` subpath converts between world coordinates and tile coordinates, and enumerates only the tiles a viewport can see:\n\n```ts\nimport { iterateTileRange, tileCenter, tileKey, tileToRect, visibleTileRange, worldToTile } from '@vielzeug/atlas/grid';\n\nconst grid = { tileSize: 32 };\n\nworldToTile({ x: 40, y: -1 }, grid); // { col: 1, row: -1 }\ntileToRect({ col: 1, row: -1 }, grid); // { x: 32, y: -32, width: 32, height: 32 }\ntileCenter({ col: 1, row: -1 }, grid); // { x: 48, y: -16 }\n\n// Render loop: iterate the tiles intersecting the camera's world rect.\nfor (const coord of iterateTileRange(visibleTileRange(camera.visibleRect, grid))) {\n drawTile(coord);\n}\n```\n\n`tileKey(coord)` yields the stable `\"col:row\"` string used by the FOV and fog APIs (and convenient as a `Map` key).\n\n## Field of View and Fog\n\n`computeFov()` runs recursive shadowcasting over the eight octants and returns the set of `tileKey` strings a viewer can see within a radius. Blocking tiles are visible but cast shadows behind themselves:\n\n```ts\nimport { computeFov, createFog } from '@vielzeug/atlas/grid';\n\nconst fov = computeFov({ col: 10, row: 8 }, 6, { blocks: (c) => walls.has(`${c.col}:${c.row}`) });\n\nconst fog = createFog();\nfog.update(fov); // demotes the previous frame's visible tiles to 'seen'\nfog.state(tileKey({ col: 10, row: 8 })); // 'visible' | 'seen' | 'unseen'\nsaveGame(fog.exportState()); // serializable { seen, visible } key lists\n```\n\n`computeFov()` is pure and costs O(radius²) worst case; walls prune the walk. `createFog()` owns the three-state bookkeeping (`unseen` → `visible` → `seen`) over `tileKey` strings and round-trips through `exportState()`/`importState()` for save files. One `update(visibleKeys)` call per frame replaces the whole visible set — demote-then-reveal ordering is handled for you — and `fog.visible` is a `ReadonlySet<string>` of the current keys.\n\n## Best Practices\n\n- Subtract the viewport rect once at the input boundary; never mix client and screen coordinates inside camera calls.\n- Call `camera.resize()` from a `ResizeObserver` on the viewport element; the camera cannot anchor zooms to the centre without knowing its size.\n- Call `index.set(id, rect)` after every committed move — stale bounds silently break marquee and culling queries.\n- Use `camera.visibleRect` (the world AABB of the rotated viewport) for culling; it is conservative by design, so no visible shape is ever dropped.\n- Snap against the pre-move rect each pointer move (not the last snapped rect) so the delta stays relative to the raw pointer and snapping never drifts cumulatively.\n- Dispose the camera when the editor unmounts; disposal aborts in-flight animations and turns every mutating method into a no-op. The spatial index owns no resources, so it needs no disposal.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Atlas: Examples'\ndescription: Practical examples and recipes for @vielzeug/atlas.\n---\n\n## Examples\n\n- [Pan, Zoom and Culling](./examples/pan-zoom-and-culling.md)\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [
|
|
10
|
-
{
|
|
11
|
-
"id": "atlas-camera",
|
|
12
|
-
"code": "import { createCamera, createSpatialIndex } from '@vielzeug/atlas'\n\n// A small scene of world-space rects, indexed by id for hit-testing.\nconst index = createSpatialIndex()\nconst colors = new Map()\nconst palette = ['#38bdf8', '#a78bfa', '#f472b6', '#34d399', '#fbbf24']\nfor (let i = 0; i < 40; i++) {\n const x = (i % 8) * 90 - 320\n const y = Math.floor(i / 8) * 70 - 140\n index.set('r' + i, { x, y, width: 60, height: 44 })\n colors.set('r' + i, palette[i % palette.length])\n}\n\n// Camera state is the world point at the viewport centre (the SVG is 480x300).\nconst camera = createCamera({ minZoom: 0.2, maxZoom: 8, viewport: { width: 480, height: 300 } })\ncamera.fitBounds({ x: -320, y: -140, width: 700, height: 420 }, { padding: 20 })\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '0 0 480 300')\nsvg.style.cssText = 'width:100%;max-width:560px;background:#0f172a;border-radius:12px;touch-action:none;cursor:grab'\ndocument.body.appendChild(svg)\n\nfunction render() {\n svg.replaceChildren()\n for (const id of index.queryRect(camera.visibleRect)) {\n const r = index.get(id)\n const p = camera.toScreen({ x: r.x, y: r.y })\n const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')\n rect.setAttribute('x', String(p.x))\n rect.setAttribute('y', String(p.y))\n rect.setAttribute('width', String(r.width * camera.state.zoom))\n rect.setAttribute('height', String(r.height * camera.state.zoom))\n rect.setAttribute('rx', '6')\n rect.setAttribute('fill', colors.get(id))\n svg.appendChild(rect)\n }\n}\nrender()\n\n// Wheel zoom anchored at the cursor.\nsvg.addEventListener('wheel', (event) => {\n event.preventDefault()\n const box = svg.getBoundingClientRect()\n const sx = (event.clientX - box.left) * (480 / box.width)\n const sy = (event.clientY - box.top) * (300 / box.height)\n camera.zoomAt({ x: sx, y: sy }, Math.exp(-event.deltaY * 0.0015))\n render()\n}, { passive: false })\n\n// Drag to pan; double-click fits the whole scene again.\nlet dragging = false\nsvg.addEventListener('pointerdown', (event) => {\n dragging = true\n svg.setPointerCapture(event.pointerId)\n svg.style.cursor = 'grabbing'\n})\nsvg.addEventListener('pointermove', (event) => {\n if (dragging) { camera.panBy(event.movementX, event.movementY); render() }\n})\nsvg.addEventListener('pointerup', () => { dragging = false; svg.style.cursor = 'grab' })\nsvg.addEventListener('dblclick', () => {\n camera.animateTo({ x: 0, y: 0, zoom: 1, rotation: 0 }, { duration: 400 })\n})\n\nconsole.log('visible rects:', index.queryRect(camera.visibleRect).length)",
|
|
13
|
-
"name": "createCamera - Pan, zoom and culling"
|
|
14
|
-
},
|
|
15
|
-
{
|
|
16
|
-
"id": "atlas-frames",
|
|
17
|
-
"code": "import { apply, boundsOfFrame, frameMatrix, resizeRect, toCssMatrix } from '@vielzeug/atlas'\n\n// One shape: a local rect placed by a frame matrix, resized by its handles.\nlet rect = { x: -90, y: -50, width: 180, height: 100 }\nconst rotation = Math.PI / 10\nconst frame = frameMatrix({ rotation, x: 0, y: 0 })\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '-240 -160 480 320')\nsvg.style.cssText = 'width:100%;max-width:560px;background:#0f172a;border-radius:12px;touch-action:none'\ndocument.body.appendChild(svg)\n\nconst ns = 'http://www.w3.org/2000/svg'\nfunction render() {\n svg.replaceChildren()\n const aabb = boundsOfFrame(rect, frame)\n const box = document.createElementNS(ns, 'rect')\n box.setAttribute('x', String(aabb.x)); box.setAttribute('y', String(aabb.y))\n box.setAttribute('width', String(aabb.width)); box.setAttribute('height', String(aabb.height))\n box.setAttribute('fill', 'none'); box.setAttribute('stroke', '#64748b'); box.setAttribute('stroke-dasharray', '4 4')\n svg.appendChild(box)\n const shape = document.createElementNS(ns, 'rect')\n shape.setAttribute('x', String(rect.x)); shape.setAttribute('y', String(rect.y))\n shape.setAttribute('width', String(rect.width)); shape.setAttribute('height', String(rect.height))\n shape.setAttribute('rx', '8'); shape.setAttribute('fill', '#38bdf8')\n shape.setAttribute('transform', toCssMatrix(frame))\n svg.appendChild(shape)\n // Handles sit on the rotated corners, and drag in world space.\n const corners = [\n { dir: 'nw', x: rect.x, y: rect.y },\n { dir: 'ne', x: rect.x + rect.width, y: rect.y },\n { dir: 'sw', x: rect.x, y: rect.y + rect.height },\n { dir: 'se', x: rect.x + rect.width, y: rect.y + rect.height },\n ]\n for (const c of corners) {\n const p = apply(frame, { x: c.x, y: c.y })\n const h = document.createElementNS(ns, 'rect')\n h.setAttribute('x', String(p.x - 5)); h.setAttribute('y', String(p.y - 5))\n h.setAttribute('width', '10'); h.setAttribute('height', '10'); h.setAttribute('rx', '2')\n h.setAttribute('fill', '#fbbf24'); h.style.cursor = 'grab'\n h.dataset.dir = c.dir\n svg.appendChild(h)\n }\n}\nrender()\n\n// Drag a handle: resizeRect keeps the opposite corner fixed; Shift locks the ratio.\nlet drag = null\nsvg.addEventListener('pointerdown', (event) => {\n const dir = event.target instanceof Element ? event.target.dataset.dir : undefined\n if (!dir) return\n drag = dir\n svg.setPointerCapture(event.pointerId)\n})\nsvg.addEventListener('pointermove', (event) => {\n if (!drag) return\n const box = svg.getBoundingClientRect()\n const point = {\n x: (event.clientX - box.left) * (480 / box.width) - 240,\n y: (event.clientY - box.top) * (320 / box.height) - 160,\n }\n const aspect = event.shiftKey && rect.height > 0 ? rect.width / rect.height : undefined\n rect = resizeRect(rect, drag, point, { aspect, min: 20 })\n render()\n})\nsvg.addEventListener('pointerup', () => { drag = null })\n\nconsole.log('aabb:', JSON.stringify(boundsOfFrame(rect, frame)))",
|
|
18
|
-
"name": "frameMatrix + resizeRect - Rotated frame with resize handles"
|
|
19
|
-
},
|
|
20
|
-
{
|
|
21
|
-
"id": "atlas-snap",
|
|
22
|
-
"code": "import { alignRects, distributeRects, snapRect, type Rect } from '@vielzeug/atlas'\n\n// Drag a rect with the pointer; it snaps to nearby rects and a 50px grid.\nconst candidates: Rect[] = [\n { x: -120, y: -80, width: 80, height: 60 },\n { x: 40, y: 20, width: 100, height: 40 },\n { x: -30, y: 110, width: 60, height: 60 },\n]\nlet moving: Rect = { x: 150, y: -40, width: 90, height: 50 }\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '-200 -150 480 340')\nsvg.style.cssText = 'width:100%;max-width:560px;background:#0f172a;border-radius:12px;touch-action:none'\ndocument.body.appendChild(svg)\n\nfunction render(guides) {\n svg.replaceChildren()\n const ns = 'http://www.w3.org/2000/svg'\n for (const g of guides) {\n const line = document.createElementNS(ns, 'line')\n if (g.axis === 'x') {\n line.setAttribute('x1', String(g.position)); line.setAttribute('x2', String(g.position))\n line.setAttribute('y1', String(g.from)); line.setAttribute('y2', String(g.to))\n } else {\n line.setAttribute('y1', String(g.position)); line.setAttribute('y2', String(g.position))\n line.setAttribute('x1', String(g.from)); line.setAttribute('x2', String(g.to))\n }\n line.setAttribute('stroke', '#f472b6'); line.setAttribute('stroke-width', '1.5')\n svg.appendChild(line)\n }\n for (const r of [...candidates, moving]) {\n const rect = document.createElementNS(ns, 'rect')\n rect.setAttribute('x', String(r.x)); rect.setAttribute('y', String(r.y))\n rect.setAttribute('width', String(r.width)); rect.setAttribute('height', String(r.height))\n rect.setAttribute('rx', '6')\n rect.setAttribute('fill', r === moving ? '#38bdf8' : '#334155')\n svg.appendChild(rect)\n }\n}\nrender([])\n\nsvg.addEventListener('pointermove', (event) => {\n if (event.buttons !== 1) return\n const box = svg.getBoundingClientRect()\n const px = (event.clientX - box.left) * (480 / box.width) - 200\n const py = (event.clientY - box.top) * (340 / box.height) - 150\n const target = { ...moving, x: px - moving.width / 2, y: py - moving.height / 2 }\n const snap = snapRect(target, { candidates, grid: { x: 50, y: 50 }, threshold: 8 })\n moving = { ...target, x: target.x + snap.delta.x, y: target.y + snap.delta.y }\n render(snap.guides)\n})\n\n// Press A to align all rects to the top edge, D to distribute horizontally.\nwindow.addEventListener('keydown', (event) => {\n if (event.key === 'a') candidates.splice(0, candidates.length, ...alignRects(candidates, 'top'))\n if (event.key === 'd') candidates.splice(0, candidates.length, ...distributeRects(candidates, 'x'))\n render([])\n})",
|
|
23
|
-
"name": "snapRect - Magnetic snapping and guides"
|
|
24
|
-
}
|
|
25
|
-
],
|
|
26
|
-
"typeSignatures": {
|
|
27
|
-
"AnimationOptions": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
28
|
-
"Camera": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
29
|
-
"CameraOptions": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
30
|
-
"CameraState": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
31
|
-
"createCamera": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
32
|
-
"FrameScheduler": "export {\n type AnimationOptions,\n type Camera,\n type CameraOptions,\n type CameraState,\n createCamera,\n type FrameScheduler,\n} from './camera.js';",
|
|
33
|
-
"AtlasConfigError": "export { AtlasConfigError, AtlasError } from './errors.js';",
|
|
34
|
-
"AtlasError": "export { AtlasConfigError, AtlasError } from './errors.js';",
|
|
35
|
-
"boundsOfFrame": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
36
|
-
"FrameOptions": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
37
|
-
"frameMatrix": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
38
|
-
"ResizeEdges": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
39
|
-
"ResizeOptions": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
40
|
-
"resizeRect": "export {\n boundsOfFrame,\n type FrameOptions,\n frameMatrix,\n type ResizeEdges,\n type ResizeOptions,\n resizeRect,\n} from './frame.js';",
|
|
41
|
-
"distanceToPolyline": "export { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';",
|
|
42
|
-
"pointInPolygon": "export { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';",
|
|
43
|
-
"pointNearPolygon": "export { distanceToPolyline, pointInPolygon, pointNearPolygon } from './geometry.js';",
|
|
44
|
-
"apply": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
45
|
-
"around": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
46
|
-
"IDENTITY": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
47
|
-
"invert": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
48
|
-
"multiply": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
49
|
-
"rotate": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
50
|
-
"scale": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
51
|
-
"scaleOf": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
52
|
-
"toCssMatrix": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
53
|
-
"translate": "export { apply, around, IDENTITY, invert, multiply, rotate, scale, scaleOf, toCssMatrix, translate } from './matrix.js';",
|
|
54
|
-
"containsPoint": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
55
|
-
"containsRect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
56
|
-
"inflateRect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
57
|
-
"intersectRect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
58
|
-
"rectBottom": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
59
|
-
"rectCenter": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
60
|
-
"rectFromPoints": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
61
|
-
"rectRight": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
62
|
-
"rectsIntersect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
63
|
-
"unionRect": "export {\n containsPoint,\n containsRect,\n inflateRect,\n intersectRect,\n rectBottom,\n rectCenter,\n rectFromPoints,\n rectRight,\n rectsIntersect,\n unionRect,\n} from './rect.js';",
|
|
64
|
-
"Matrix": "export type { Matrix, Point, Rect, Size } from './shapes.js';",
|
|
65
|
-
"Point": "export type { Matrix, Point, Rect, Size } from './shapes.js';",
|
|
66
|
-
"Rect": "export type { Matrix, Point, Rect, Size } from './shapes.js';",
|
|
67
|
-
"Size": "export type { Matrix, Point, Rect, Size } from './shapes.js';",
|
|
68
|
-
"AlignEdge": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
69
|
-
"alignRects": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
70
|
-
"distributeRects": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
71
|
-
"SnapGuide": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
72
|
-
"SnapGuideKind": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
73
|
-
"SnapOptions": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
74
|
-
"SnapResult": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
75
|
-
"snapRect": "export {\n type AlignEdge,\n alignRects,\n distributeRects,\n type SnapGuide,\n type SnapGuideKind,\n type SnapOptions,\n type SnapResult,\n snapRect,\n} from './snap.js';",
|
|
76
|
-
"createSpatialIndex": "export {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';",
|
|
77
|
-
"SpatialIndex": "export {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';",
|
|
78
|
-
"SpatialIndexOptions": "export {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';",
|
|
79
|
-
"SpatialQueryOptions": "export {\n createSpatialIndex,\n type SpatialIndex,\n type SpatialIndexOptions,\n type SpatialQueryOptions,\n} from './spatial-index.js';"
|
|
80
|
-
}
|
|
81
|
-
}
|
package/data/packages/bard.json
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "// Public root surface of @vielzeug/bard. Every public export goes through this file.\nexport { createBard } from './bard';\nexport { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';\nexport type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Bard'\ndescription: 'Lifecycle-owned Web Audio mixing: buses with ducking, buffered SFX and sprites, procedural synth, streamed tracks, and crossfading music decks'\npackage: bard\ncategory: utilities\nkeywords: [web-audio, audio, sfx, soundboard, crossfade, ducking, audio-sprites]\nrelated: [necromancer]\nexports: [createBard, BardError, BardLoadError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"bard\" />\n\n## Why Bard?\n\nThe Web Audio API gives you nodes and params but no lifecycle: nothing stops voices, removes gesture listeners, or closes the context when your feature unmounts. Bard wraps a lazily created `AudioContext` in one disposable engine with named buses, ducking, voice caps, and a crossfading music deck.\n\n```ts\n// Before: hand-rolled graph, listeners, and teardown you must remember\nconst ctx = new AudioContext();\nconst source = ctx.createBufferSource();\nsource.connect(ctx.destination);\n// ...who disconnects this on unmount?\n\n// After\nconst bard = createBard({ ducking: [{ source: 'voice', target: 'music', gain: 0.3 }] });\nawait bard.load({ confirm: '/confirm.wav' });\nbard.play('confirm');\nbard.dispose(); // stops voices, removes listeners, closes the context\n```\n\n| Feature | Native Web Audio | Bard | Howler.js |\n| ----------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | 0 B | <PackageInfo package=\"bard\" type=\"size\" /> | ~30 kB |\n| Root dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Lifecycle | Manual node teardown | `dispose()` + `Symbol.dispose` | Per-sound unload |\n| Mixing | Hand-built gain graph | Named buses, ducking rules, voice caps | Per-sound volume only |\n| Music transitions | Manual crossfade scheduling | `deck.transition()` with loop points, queue | Not built in |\n\n<div class=\"decision-callout\">\n\n**Use Bard when** an interactive app needs owned audio: UI SFX with voice caps, narration that ducks music, or game-state music transitions with crossfades and loop points.\n\n**Consider a plain `HTMLAudioElement` when** you need one background track with no mixing, sprites, or lifecycle requirements.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/bard\n```\n\n```sh [npm]\nnpm install @vielzeug/bard\n```\n\n```sh [yarn]\nyarn add @vielzeug/bard\n```\n\n:::\n\n## Quick Start\n\nCreate the engine once per app, load assets, and dispose it when the owning feature unmounts. Nothing touches `AudioContext` or the DOM until the first call that needs audio, so server rendering is safe.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard({\n ducking: [{ source: 'voice', target: 'music', gain: 0.3 }],\n});\n\nawait bard.load({\n music: { src: '/theme.mp3', stream: true },\n dice: { src: '/sfx.wav', sprites: { roll: [0, 1.2] } },\n});\n\nconst deck = bard.createDeck();\ndeck.transition('music', { loop: true });\nbard.play('dice:roll', { detune: [-60, 60] });\n\nbard.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createBard()`**: one disposable owner for the context, buses, voices, and decks.\n- **`bus()`**: named gain buses (`music`, `sfx`, `voice`) with click-free volume ramps.\n- **`ducking`**: declarative rules that ramp a target bus while a source bus has active voices.\n- **`play()`**: buffered playback with sprites, voice caps, oldest-first stealing, and detune/rate variance.\n- **`synth()`**: zero-asset oscillator and noise voices with ADSR and frequency sweeps.\n- **`createDeck()`**: two-slot crossfader with loop points, queue with shuffle, and opt-in Media Session.\n- **`tap()`**: observability events for state changes, steals, ducks, and track changes.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Necromancer](/necromancer/): pair visual transitions with deck music transitions from the same game-state change.\n- [Arsenal](/arsenal/): general-purpose utilities used across the monorepo.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Bard: API Reference'\ndescription: Public API of @vielzeug/bard.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ---------------------- | ------------------------------------------- | --------- | ------------------------------------------------------------------------ |\n| `createBard` | Creates the disposable audio engine | Sync | Context is still created lazily on first audio use |\n| `BardError` | Base error for invalid keys, buses, regions | — | Subclasses: `BardLoadError`, `BardDisposedError`, `BardUnsupportedError` |\n| `BardLoadError` | A manifest entry failed to fetch or decode | — | Original failure is in `cause` |\n| `BardDisposedError` | A method ran after `dispose()` | — | Thrown by every engine method except `dispose` |\n| `BardUnsupportedError` | No `AudioContext` in the runtime | — | `unlock()` rejects with it on servers without Web Audio |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | --------------------------------------- |\n| `@vielzeug/bard` | Complete public Bard API |\n| `@vielzeug/bard/testing` | Deterministic Web Audio fakes for tests |\n\n## Engine\n\n### createBard\n\n```ts\nfunction createBard(options?: BardOptions): Bard;\n```\n\nCreates the engine. Touches no browser global until the first method that needs audio.\n\n| Option | Type | Default | Notes |\n| --------------------- | ------------------------ | --------------------------- | --------------------------------------------------------------------------- |\n| `buses` | `readonly string[]` | `['music', 'sfx', 'voice']` | `'master'` is reserved and throws if declared |\n| `volume` | `number` | `1` | Master volume, linear 0..1 |\n| `ducking` | `readonly DuckingRule[]` | `[]` | See Ducking |\n| `maxVoices` | `number` | `32` | Engine-wide concurrent voice cap |\n| `autoUnlock` | `boolean` | `true` | Gesture listeners resume a suspended context |\n| `autoSuspendOnHidden` | `boolean` | `false` | Suspend on page hide, resume on show (only resumes its own suspends) |\n| `context` | `() => AudioContext` | lazy `new AudioContext()` | Injection seam for tests; injected contexts are never closed by `dispose()` |\n\nReturns the `Bard` engine.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard({ volume: 0.9 });\n```\n\n### Bard\n\n| Member | Signature | Notes |\n| ----------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |\n| `state` | `'idle' \\| 'suspended' \\| 'running' \\| 'interrupted' \\| 'closed'` | `'idle'` until first lazy context creation; `'interrupted'` occurs on iOS calls |\n| `context` | `AudioContext \\| null` | Native context for advanced graph work |\n| `unlock()` | `() => Promise<void>` | Creates and resumes the context |\n| `load(manifest, options?)` | `(AssetManifest, { signal? }) => Promise<void>` | Deduplicates concurrent fetches per URL |\n| `unload(keys?)` | `(string \\| readonly string[]) => void` | Stops active voices for the dropped keys |\n| `has(key)` | `(string) => boolean` | Resolves `'key:sprite'` to its parent asset |\n| `play(key, options?)` | `(string, PlayOptions?) => SoundHandle` | Throws `BardError` for unknown keys and streamed assets |\n| `synth(options)` | `(SynthOptions) => SoundHandle` | Procedural voice, self-cleaning |\n| `bus(name)` | `(string) => BusController` | `'master'` is valid; unknown names throw |\n| `createDeck(options?)` | `(DeckOptions?) => MusicDeck` | Multiple decks share the engine |\n| `suspend()` / `resume()` | `() => Promise<void>` | Engine-wide pause for the whole context |\n| `tap(handler, options?)` | `(BardEvent) => void` → unsubscribe | Handler errors are swallowed; auto-detaches on `signal` |\n| `dispose()` | `() => void` | Stops voices and decks, aborts loads, removes listeners, closes an owned context; idempotent |\n| `disposed` / `disposalSignal` | `boolean` / `AbortSignal` | Standard disposal contract |\n\n---\n\n## Playback\n\n### SoundHandle\n\nReturned by `play()` and `synth()`.\n\n| Member | Signature | Notes |\n| --------------------------------------------- | -------------------------------- | ------------------------------------------- |\n| `stop(options?)` | `(FadeOptions?) => void` | Fades (default 15 ms micro-fade) then stops |\n| `setVolume(volume, options?)` | `(number, FadeOptions?) => void` | Ramped, never clicks |\n| `setPan(pan)` | `(-1..1) => void` | Every voice has a panner |\n| `finished` | `Promise<void>` | Resolves on natural end, stop, or dispose |\n| `dispose()` / `disposed` / `[Symbol.dispose]` | | Immediate stop and node release |\n\n### PlayOptions\n\n| Option | Type | Default | Notes |\n| ----------------------- | ---------------------- | ------------- | --------------------------------------- |\n| `bus` | `string` | `'sfx'` | Destination bus |\n| `volume` | `number` | `1` | Linear 0..1 |\n| `pan` | `number` | `0` | -1..1; voices always route via a panner |\n| `loop` | `boolean` | `false` | Loops the buffer or sprite region |\n| `loopStart` / `loopEnd` | `number` | — | Absolute buffer seconds |\n| `offset` | `number` | `0` | Start offset in seconds |\n| `detune` | `number \\| [min, max]` | — | Cents; ranges sampled per voice |\n| `rate` | `number \\| [min, max]` | — | Playback rate; shifts pitch on buffers |\n| `maxVoices` | `number` | — | Per-key cap; oldest copy is stolen |\n| `fadeIn` | `number` | — | Seconds from 0 to `volume` |\n| `random` | `() => number` | `Math.random` | Deterministic sampling in tests |\n\n### SynthOptions\n\n| Option | Type | Default | Notes |\n| ----------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------ | --------------------------------------------------------------- |\n| `type` | `'sine' \\| 'square' \\| 'sawtooth' \\| 'triangle' \\| 'noise'` | `'sine'` | `'noise'` uses a cached white-noise buffer |\n| `freq` | `number \\| [from, to]` | `440` | Tuple sweeps exponentially; maps to filter cutoff for `'noise'` |\n| `duration` | `number` | `0.3` | Total seconds including release; must be positive |\n| `envelope` | `SynthEnvelope` | `{ attack: 0.005, decay: 0.05, sustain: 0.6, release: 0.1 }` | ADSR; `sustain` is a level |\n| `filter` | `SynthFilter` | — | Biquad stage before the envelope |\n| `bus` / `volume` / `pan` / `detune` | as in `PlayOptions` | | |\n\n---\n\n## Mixing\n\n### DuckingRule\n\n```ts\ninterface DuckingRule {\n readonly source: string;\n readonly target: string;\n readonly gain: number; // duck level, linear 0..1\n readonly attack?: number; // seconds, default 0.2\n readonly release?: number; // seconds, default 0.8\n}\n```\n\nWhile the `source` bus has active voices, `target` ramps to `gain`; when they end it ramps back to 1. Multiple rules on one target take the lowest active gain.\n\n### BusController\n\n| Member | Notes |\n| ----------------------------------- | -------------------------------------- |\n| `name` | Bus name |\n| `volume` / `setVolume(v, options?)` | User volume stage, ramped |\n| `muted` / `mute()` / `unmute()` | Ramped mute |\n| `duckLevel` | Current duck multiplier (1 = unducked) |\n\n---\n\n## Music Deck\n\n### MusicDeck\n\n| Member | Signature | Notes |\n| --------------------------------------------- | -------------------------------------------- | ---------------------------------------------------- |\n| `current` | `string \\| null` | Active track key |\n| `playing` | `boolean` | `false` while paused or stopped |\n| `transition(key, options?)` | `(string, TransitionOptions?) => void` | Crossfades; transitioning to the live key is a no-op |\n| `queue(keys, options?)` | `(readonly string[], QueueOptions?) => void` | Replaces the queue and starts its first track |\n| `next()` / `previous()` | `() => void` | No-op without a queue |\n| `pause()` / `play()` | `() => void` | `play()` resumes from the paused offset |\n| `stop(options?)` | `(FadeOptions?) => void` | Stops and clears queue and slot |\n| `dispose()` / `disposed` / `[Symbol.dispose]` | | Releases a Media Session claim |\n\n`TransitionOptions`: `fade`, `loop`, `loopStart`, `loopEnd`, `offset`.\n`QueueOptions`: `shuffle`, `crossfade`, `repeat`, `random`.\n\n### DeckOptions\n\n| Option | Type | Default | Notes |\n| -------------- | --------- | --------- | ------------------------------------------------------ |\n| `bus` | `string` | `'music'` | Destination bus |\n| `mediaSession` | `boolean` | `false` | Claims `navigator.mediaSession`; a second claim throws |\n| `fade` | `number` | `2` | Default crossfade seconds |\n\n---\n\n## Assets\n\n### AssetManifest\n\n```ts\ntype AssetManifest = Readonly<Record<string, string | AssetDefinition>>;\n\ninterface AssetDefinition {\n readonly src: string;\n readonly sprites?: Readonly<Record<string, readonly [start: number, duration: number]>>;\n readonly stream?: boolean; // deck-only playback via an owned <audio> element\n readonly meta?: AssetMeta; // Media Session metadata\n}\n```\n\nA bare string is shorthand for `{ src }`. Sprite regions are `[startSeconds, durationSeconds]` and play as `'key:sprite'`; out-of-bounds regions throw `BardError`.\n\n---\n\n## Observability\n\n### BardEvent\n\n| Event | Payload | Fires |\n| ------------ | ---------------------- | ---------------------------------------- |\n| `state` | `state` | Context lifecycle changes |\n| `load` | `key` | A manifest entry finished loading |\n| `load-error` | `key`, `error` | A load failed |\n| `steal` | `key` | A voice was stolen past a cap |\n| `duck` | `bus`, `level`, `ramp` | A bus duck level changed |\n| `track` | `key \\| null` | The deck changed tracks |\n| `dispose` | — | Emitted once at the start of `dispose()` |\n\n---\n\n## Testing\n\n`@vielzeug/bard/testing` exports `FakeAudioContext` (manual clock via `advance(seconds)`, recorded `FakeAudioParam` automation), `FakeMediaElement`, `FakeMediaSession`, and `flush()`. Inject the fake with `createBard({ context: () => fake })`.\n\n---\n\n## Errors\n\n| Error | Trigger | Notes |\n| ------------------- | ---------------------------------------------------------------- | --------------------------------------------------------- |\n| `BardError` | Unknown key/bus/sprite, reserved bus name, streamed-asset misuse | Base class |\n| `BardLoadError` | Fetch or `decodeAudioData` failure | `cause` carries the original error or `{ status }` |\n| `BardDisposedError` | Engine use after `dispose()` | Also `BardUnsupportedError` when no `AudioContext` exists |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Bard: Usage Guide'\ndescription: Play sounds, mix buses with ducking, generate synth SFX, and crossfade music with @vielzeug/bard.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate one engine per app, load a manifest, and play through a bus. Dispose the engine when its owning feature unmounts.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard();\nawait bard.load({ click: '/click.wav', boom: '/boom.wav' });\n\nconst handle = bard.play('boom', { volume: 0.8, pan: -0.3 });\nawait handle.finished;\nbard.dispose();\n```\n\n`play()` returns a `SoundHandle` immediately; audio starts once the browser allows it. `finished` resolves when the voice ends, is stopped, or is disposed.\n\n## Unlocking Audio\n\nBrowsers start the `AudioContext` suspended until a user gesture. Bard attaches capture-phase listeners for `pointerup`, `touchend`, `keydown`, and `click` and resumes the context inside the first one. All listeners are removed once the context is running.\n\n```ts\nconst bard = createBard(); // listeners attach on first audio use\nawait bard.unlock(); // or resume programmatically inside your own handler\n```\n\n`autoUnlock: false` skips the gesture listeners entirely; call `resume()` from your own gesture handler instead.\n\n## Buses and Volume\n\nVoices route to a named bus: `voice -> [pan] -> bus -> master -> destination`. The defaults are `music`, `sfx`, and `voice`; override with `buses`. Volume changes always ramp, so they never click.\n\n```ts\nconst music = bard.bus('music');\nmusic.setVolume(0.6, { fade: 0.5 });\nmusic.mute();\nmusic.unmute();\n```\n\n`bard.bus('master')` controls the output stage for every bus.\n\n## Ducking\n\nA ducking rule ramps a target bus down while the source bus has active voices, and back up when they end. Narration over music is the canonical case.\n\n```ts\nconst bard = createBard({\n ducking: [{ source: 'voice', target: 'music', gain: 0.3, attack: 0.2, release: 0.8 }],\n});\n\nawait bard.load({ announce: '/announce.wav' });\nconst voice = bard.play('announce', { bus: 'voice' });\n// music is now at 30% until the announcement ends\nawait voice.finished; // music ramps back to 100%\n```\n\nDucking uses its own gain stage per bus, so it never fights user volume automation.\n\n## Sound Sprites\n\nBundle many short SFX into one file and address regions with `key:sprite`. The region is `[startSeconds, durationSeconds]`.\n\n```ts\nawait bard.load({\n ui: { src: '/ui.wav', sprites: { open: [0, 0.4], close: [0.5, 0.4] } },\n});\n\nbard.play('ui:open');\nbard.play('ui:close', { bus: 'sfx' });\n```\n\n## Voice Caps and Variance\n\n`maxVoices` caps concurrent copies of one key; the oldest copy is stolen with a micro-fade. The engine-wide cap is `maxVoices` in `createBard` (default 32). Ranges for `detune` and `rate` keep repeated hits from sounding identical.\n\n```ts\nfor (let i = 0; i < 10; i += 1) {\n bard.play('ui:open', { maxVoices: 3, detune: [-100, 100], rate: [0.95, 1.05] });\n}\n```\n\nNote: `rate` shifts pitch on buffer sources. Pitch-preserving playback belongs on a streamed `HTMLAudioElement`.\n\n## Procedural Synth\n\n`synth()` builds an oscillator or noise burst with an ADSR envelope and optional filter, and disconnects itself when done. No assets required.\n\n```ts\n// countdown tick\nbard.synth({ type: 'square', freq: 880, duration: 0.08 });\n\n// descending error buzz with a lowpass\nbard.synth({\n type: 'sawtooth',\n freq: [220, 55],\n duration: 0.6,\n filter: { type: 'lowpass', frequency: [2400, 400] },\n});\n```\n\n## Music Deck\n\nA deck crossfades between two slots. Transition to game states, loop the body of a track after its intro, or queue continuous playback.\n\n```ts\nconst deck = bard.createDeck({ fade: 2.5 });\n\n// intro plays once, then the region loops seamlessly\ndeck.transition('bossTheme', { loop: true, loopStart: 12.5 });\n\n// later: crossfade to the victory track\ndeck.transition('victory', { fade: 4 });\n\n// continuous ambient playback with deterministic shuffle\ndeck.queue(['forest', 'cave', 'village'], { shuffle: true, crossfade: 6, repeat: true });\ndeck.next();\n```\n\n`pause()` then `play()` resumes from the paused position. A manual `transition()` takes over from the queue.\n\n## Streaming Long Tracks\n\nMark an asset `stream: true` to play it through an owned `<audio>` element instead of decoding it into an `AudioBuffer`. Mobile devices never spike RAM on ten-minute ambient tracks. Streamed assets are deck-only; `play()` on them throws.\n\n```ts\nawait bard.load({\n ambient: { src: 'https://cdn.example.com/forest.mp3', stream: true },\n});\nbard.createDeck().transition('ambient', { loop: true });\n```\n\nThe element requests CORS (`crossOrigin: 'anonymous'`); a CDN without CORS headers plays silent through Web Audio. Streamed loops cover the whole file: `loopStart`/`loopEnd` throw.\n\n## Media Session\n\n`mediaSession: true` claims `navigator.mediaSession` for one deck: metadata from the asset's `meta`, hardware play/pause/next/previous. A second claim throws instead of stealing controls; disposing the deck releases the claim.\n\n```ts\nawait bard.load({\n theme: { src: '/theme.mp3', meta: { title: 'Hunt Theme', artist: 'Bard' } },\n});\nconst deck = bard.createDeck({ mediaSession: true });\ndeck.transition('theme');\n```\n\n## Testing\n\n`@vielzeug/bard/testing` ships deterministic fakes: a context with a manual clock, recorded param automation, and fake media elements. Bard's own suite uses them.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\nimport { FakeAudioContext } from '@vielzeug/bard/testing';\n\nconst ctx = new FakeAudioContext();\nconst bard = createBard({ context: () => ctx });\nawait bard.load({ ping: '/ping.wav' });\nbard.play('ping');\nctx.advance(2); // clock moves, sources past their stop time fire 'ended'\n```\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useState } from 'react';\nimport { createBard, type Bard } from '@vielzeug/bard';\n\nexport function useBard() {\n const [bard, setBard] = useState<Bard | null>(null);\n useEffect(() => {\n const engine = createBard();\n setBard(engine);\n return () => engine.dispose();\n }, []);\n return bard;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, shallowRef } from 'vue';\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = shallowRef<ReturnType<typeof createBard> | null>(null);\nonMounted(() => (bard.value = createBard()));\nonUnmounted(() => bard.value?.dispose());\n</script>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { createBard } from '@vielzeug/bard';\n import { onDestroy } from 'svelte';\n\n const bard = createBard();\n onDestroy(() => bard.dispose());\n</script>\n```\n\n:::\n\nCreate the engine in a mount hook, not at module scope: only mount lifecycle proves a browser runtime exists.\n\n## Best Practices\n\n- Create one engine per app and pass it down; contexts are a limited hardware resource.\n- Dispose the engine with its owning feature; `using` works via `Symbol.dispose`.\n- Keep streamed assets for tracks longer than a few minutes; buffers are better for SFX.\n- Give narration its own `voice` bus and duck `music` from it, rather than fading tracks by hand.\n- Inject `random` in tests so detune, rate, and shuffle are deterministic.\n- Watch `tap()` events (`steal`, `duck`, `load-error`) in development to catch mixing problems early.\n- Call `unlock()` from your own first-gesture UI when you want audio live before the next interaction.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Bard Examples'\ndescription: Practical sound, ducking, and music-transition recipes for @vielzeug/bard.\n---\n\n## Examples\n\n- [Game-State Music Transitions](./examples/game-state-music-transitions.md)\n- [Duck Music Under Narration](./examples/duck-music-under-narration.md)\n- [UI SFX Without Assets](./examples/ui-sfx-without-assets.md)\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [],
|
|
10
|
-
"typeSignatures": {
|
|
11
|
-
"createBard": "export { createBard } from './bard';",
|
|
12
|
-
"BardDisposedError": "export { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';",
|
|
13
|
-
"BardError": "export { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';",
|
|
14
|
-
"BardLoadError": "export { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';",
|
|
15
|
-
"BardUnsupportedError": "export { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';",
|
|
16
|
-
"AssetDefinition": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
17
|
-
"AssetManifest": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
18
|
-
"AssetMeta": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
19
|
-
"Bard": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
20
|
-
"BardEvent": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
21
|
-
"BardOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
22
|
-
"BardState": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
23
|
-
"BusController": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
24
|
-
"DeckOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
25
|
-
"DuckingRule": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
26
|
-
"FadeOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
27
|
-
"MediaImage": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
28
|
-
"MusicDeck": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
29
|
-
"PlayOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
30
|
-
"QueueOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
31
|
-
"SoundHandle": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
32
|
-
"SynthEnvelope": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
33
|
-
"SynthFilter": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
34
|
-
"SynthOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
35
|
-
"SynthWaveform": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
|
|
36
|
-
"TransitionOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';"
|
|
37
|
-
}
|
|
38
|
-
}
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "// Public root surface of @vielzeug/beacon. Every public export goes through this file.\nexport { createCoachmark } from './coachmark';\nexport { BeaconConfigError, BeaconDisposedError, BeaconError } from './errors';\nexport { resolveTarget } from './target';\nexport { createTour } from './tour';\nexport type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Beacon: Product tours and coachmarks'\ndescription: 'Guided onboarding and contextual product tours for web applications'\npackage: beacon\ncategory: ui-interaction\nkeywords: [onboarding, product-tour, coachmark, walkthrough, step-by-step, spotlight, headless]\nrelated: [refine, orbit, ripple, vault]\nexports: [createTour, createCoachmark, resolveTarget]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"beacon\" />\n\n## Why Beacon?\n\nProduct tours rot fast: hand-wired step sequences hard-code positioning, persistence, and target waiting into application code, and break the first time the UI moves. Beacon is the headless half of a tour — it owns step order, target waiting, resumable progress, and events — while your markup (or `@vielzeug/refine`'s `ore-tour` components) decides what a step looks like.\n\n```ts\n// Before: step logic tangled with rendering and storage\nlet step = Number(localStorage.getItem('tour-step') ?? 0);\nfunction showStep() {\n const el = document.querySelector(steps[step].selector);\n card.style.top = `${el.getBoundingClientRect().bottom + 8}px`; // breaks on scroll\n card.innerHTML = steps[step].html;\n}\n\n// After: the engine owns order, persistence, and the anchor rect\nimport { createTour } from '@vielzeug/beacon';\n\nconst tour = createTour({ id: 'welcome', steps, storage });\ntour.current.subscribe(() => renderCard(tour.current.value)); // rect is the live anchor\ntour.start();\n```\n\n| Feature | Beacon | Shepherd.js | Intro.js |\n| ---------------------------- | --------------------------------------------------- | -------------------------------------------- | ----------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"beacon\" type=\"size\" /> | ~50 kB | ~25 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> (none) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Headless (you own the UI) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Resumable persisted progress | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n| Versioned re-offers | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Coachmarks (single hints) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Beacon when** tours must survive UI changes: steps anchor to your real DOM, progress persists and resumes, and the card markup is yours (or refine's ready-made `ore-tour`).\n\n**Consider Shepherd or Intro.js when** you want a fully-rendered, opinionated tour widget you never style yourself and can accept their DOM and CSS.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/beacon\n```\n\n```sh [npm]\nnpm install @vielzeug/beacon\n```\n\n```sh [yarn]\nyarn add @vielzeug/beacon\n```\n\n:::\n\n## Quick Start\n\nDefine the tour as data, run it, and render the current step wherever you like. The handle is disposable, so component teardown cleans everything up.\n\n```ts\nimport { createTour, type BeaconTourConfig } from '@vielzeug/beacon';\n\nconst config = {\n id: 'getting-started',\n steps: [\n { id: 'welcome', title: 'Welcome', description: 'A two-minute look around.' },\n { id: 'nav', target: '[data-tour=\"nav\"]', title: 'Navigation', placement: 'bottom-start' },\n ],\n} satisfies BeaconTourConfig;\n\nconst tour = createTour(config);\n\n// Render from the live snapshot: rect is the anchor, null centers the card.\nconst unsubscribe = tour.current.subscribe(() => {\n const { presentation, rect, step } = tour.current.value;\n console.log({ presentation, rect, step }); // drive your card from this\n});\n\ntour.start();\n\n// On teardown:\nunsubscribe();\ntour.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createTour()` runs a sequential, resumable walkthrough over your own DOM.\n- `createCoachmark()` shows a single contextual hint once per user per version.\n- `current` is a live `Readable<BeaconCurrentStep>` snapshot: step, index, placement, presentation, and resolved anchor rect, kept fresh on scroll, resize, and layout changes.\n- `target` accepts a selector, `Element`, rect, or lazy resolver, and beacon waits for lazily-mounted targets before showing the step.\n- `storage` persists progress through any `BeaconStorage` bridge (localStorage, IndexedDB via `@vielzeug/vault`, a server API).\n- `version` re-offers a finished tour when the product changes underneath it.\n- `tap()` subscribes to lifecycle events (`step:start`, `tour:complete`, `target-missing`, ...) with `AbortSignal` support.\n- `resolveTarget()` turns any target into a viewport rect compatible with `@vielzeug/orbit` positioners.\n- `ore-tour`'s `bind()` in `@vielzeug/refine` renders a handle and routes its actions with zero glue code.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Refine](/refine/): ships `ore-tour` and `ore-spotlight`, the ready-made dialog/popover/bottom-sheet presentation layer for a beacon handle.\n- [Orbit](/orbit/): compute exact popover coordinates from `current.rect` when you build a custom presentation.\n- [Vault](/vault/): durable storage backends that plug into `BeaconStorage` with a six-line bridge.\n- [Ripple](/ripple/): the `Readable` signals every beacon handle exposes come from here.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Beacon: API Reference'\ndescription: Public API of @vielzeug/beacon.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------- | ----------------------------------------------------------- | --------------------------------- | ------------------------------------------------------------------------- |\n| `createTour(config)` | Runs a sequential, resumable walkthrough over the app's DOM | Sync (storage reads may be async) | `start()` is a no-op when the stored record says the tour is completed |\n| `createCoachmark(config)` | Shows a single contextual hint anchored to one target | Sync (storage reads may be async) | `show()` is a no-op after `dismiss()` until `reset()` or a `version` bump |\n| `resolveTarget(target)` | Resolves any target to a viewport-space rect or `null` | Sync | Call it per position update; a scrolled target's rect changes |\n| `BeaconError` | Base class for all beacon-originated errors | — | Catch this to catch any beacon error |\n| `BeaconConfigError` | Invalid tour/coachmark configuration | Thrown at creation | Empty `steps` or duplicate step ids fail at `createTour()` |\n| `BeaconDisposedError` | Handle used after `dispose()` | Thrown on call | `dispose()` is idempotent; later method calls throw |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | -------------------------- |\n| `@vielzeug/beacon` | Complete public Beacon API |\n\n---\n\n## Core Functions\n\n### createTour\n\n```ts\nfunction createTour(config: BeaconTourConfig): BeaconTourHandle;\n```\n\nReturns a live handle for one guided tour. Throws `BeaconConfigError` when `id` is empty, `steps` is empty, or step ids are duplicated.\n\nParameters: see [`BeaconTourConfig`](#beacontourconfig).\n\n**Returns:** a [`BeaconTourHandle`](#beacontourhandle) that is also `Disposable`.\n\n**Example:**\n\n```ts\nimport { createTour } from '@vielzeug/beacon';\n\nconst tour = createTour({\n id: 'release-tour',\n steps: [{ id: 'intro', title: 'What changed' }],\n autoStart: true,\n});\n\ntour.status.subscribe(() => console.log(tour.status.value));\n```\n\nHandle methods:\n\n| Member | Behavior |\n| ---------------------------------- | ------------------------------------------------------------------------------------------------- |\n| `start()` | Begin or resume the tour. No-op when completed; throws after dispose. |\n| `next()` | Advance; past the last step, finishes the tour. |\n| `back()` | Return to the previous step. No-op on the first step. |\n| `goto(step)` | Jump to a step by index or id. Unknown values warn and no-op. |\n| `pause()` | Stop showing, keep progress so `start()` resumes it. |\n| `skip()` | End from a \"Skip\" control. Persisted as dismissed, reported with reason `'skip'`. |\n| `finish()` | Mark finished and stop showing. |\n| `dismiss()` | End by closing (Escape, backdrop). Persisted as dismissed. |\n| `reset()` | Discard persisted progress; the tour is eligible again. |\n| `tap(handler, options?)` | Observe [`BeaconTourEvent`](#beacontourentype)s; returns an unsubscribe, honors `options.signal`. |\n| `dispose()` / `[Symbol.dispose]()` | Release all listeners and observers. Idempotent. |\n| Handle properties: |\n\n| Member | Type | Notes |\n| ---------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `current` | `Readable<BeaconCurrentStep>` | The snapshot to render; `step` is `null` while closed. Beacon re-publishes the rect on scroll, resize, and target layout changes while a step is active. |\n| `status` | `Readable<BeaconStatus>` | Lifecycle, persisted on every change. |\n| `eligible` | `Readable<boolean>` | Whether the tour should be offered to this user. |\n| `steps` | `readonly BeaconStep[]` | The configured steps, in order. |\n| `id` | `string` | The configured id (also the storage key suffix). |\n| `disposed` | `boolean` | Whether `dispose()` has run. |\n| `disposalSignal` | `AbortSignal` | Aborted on dispose; pass it to your own listeners. |\n\n---\n\n### createCoachmark\n\n```ts\nfunction createCoachmark(config: BeaconCoachmarkConfig): BeaconCoachmarkHandle;\n```\n\nReturns a handle for one contextual hint. Throws `BeaconConfigError` when `id` is empty.\n\nParameters: see [`BeaconCoachmarkConfig`](#beaconcoachmarkconfig).\n\n**Returns:** a [`BeaconCoachmarkHandle`](#beaconcoachmarkhandle) that is also `Disposable`.\n\n**Example:**\n\n```ts\nimport { createCoachmark } from '@vielzeug/beacon';\n\nconst hint = createCoachmark({\n id: 'share-hint',\n target: '[data-tour=\"share\"]',\n title: 'Share this board',\n});\n\nhint.show(); // waits for the target to mount if it is not on screen yet\n```\n\nHandle members:\n\n| Member | Behavior |\n| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `show()` | Show the hint. No-op once dismissed without a newer version. |\n| `hide()` | Hide without recording it as seen; it can show again. |\n| `dismiss()` | Hide and record as seen permanently (until `reset()`/`version`). |\n| `reset()` | Discard the persisted record; the hint is eligible again. |\n| `tap(handler, options?)` | Observe `coachmark:show`, `coachmark:dismiss`, and common events. |\n| `current` | `Readable<BeaconCurrentStep>` — the hint as a single-step snapshot: `step` is the hint while visible, `null` while hidden. The rect stays live on scroll, resize, and target layout changes. |\n| `eligible` | `Readable<boolean>` — never seen, or superseded by a newer version. |\n\n---\n\n### resolveTarget\n\n```ts\nfunction resolveTarget(target: BeaconTarget): BeaconRect | null;\n```\n\nResolves a target to a viewport-space rect, or `null` when it is not available yet. Strings resolve through `document.querySelector`; functions are called and their result normalized.\n\n| Parameter | Type | Description |\n| --------- | -------------- | -------------------------------------------- |\n| `target` | `BeaconTarget` | Selector, `Element`, rect, or lazy resolver. |\n\n**Returns:** `BeaconRect | null` — shape-compatible with `getBoundingClientRect()` and `@vielzeug/orbit`'s `Rect`.\n\n**Example:**\n\n```ts\nimport { resolveTarget } from '@vielzeug/beacon';\n\nconst rect = resolveTarget('[data-tour=\"share\"]');\n// Anchor an orbit positioner from a virtual reference:\nconst reference = { getBoundingClientRect: () => resolveTarget('[data-tour=\"share\"]') ?? ZERO_RECT };\n```\n\n---\n\n## Types\n\n### BeaconTourConfig\n\n| Option | Type | Default | Description |\n| ----------------- | -------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------- |\n| `id` | `string` | required | Unique identity; used as the storage key. |\n| `steps` | `readonly BeaconStep[]` | required | Every step, in order. At least one. |\n| `autoScroll` | `boolean` | `true` | Scroll each anchored step's target into view when it activates. |\n| `autoStart` | `boolean` | `false` | Start on the next microtask when eligible. |\n| `placement` | `BeaconPlacement` | `'auto'` | Default placement handed to the presentation layer. |\n| `presentation` | `BeaconPresentation` | `'auto'` | Default presentation handed to the presentation layer. |\n| `scrollOffset` | `number \\| (() => number)` | `0` | Pixels kept clear at the viewport top for a sticky header, read at scroll time. |\n| `storage` | `BeaconStorage` | memory-only | Progress persistence. |\n| `targetTimeoutMs` | `number` | `Infinity` | How long to wait for a step's target before skipping that step. `0` publishes immediately with a `null` rect. |\n| `version` | `number` | `1` | Bump to re-show a finished tour. |\n\n### BeaconCoachmarkConfig\n\n| Option | Type | Default | Description |\n| -------------- | -------------------- | ----------- | ------------------------------------------ |\n| `id` | `string` | required | Unique identity; used as the storage key. |\n| `target` | `BeaconTarget` | required | Where the hint points. |\n| `autoShow` | `boolean` | `true` | Show automatically when not yet seen. |\n| `data` | `unknown` | — | Free-form data for the presentation layer. |\n| `description` | `string` | — | Supporting copy. |\n| `placement` | `BeaconPlacement` | `'auto'` | Preferred side. |\n| `presentation` | `BeaconPresentation` | `'auto'` | Preferred presentation. |\n| `storage` | `BeaconStorage` | memory-only | Seen-record persistence. |\n| `title` | `string` | — | Headline copy. |\n| `version` | `number` | `1` | Bump to re-show a seen coachmark. |\n\n### BeaconStep\n\n```ts\ninterface BeaconStep {\n readonly data?: unknown;\n readonly description?: string;\n readonly id: string;\n readonly placement?: BeaconPlacement;\n readonly presentation?: BeaconPresentation;\n readonly target?: BeaconTarget;\n readonly title?: string;\n}\n```\n\nOne stop in a tour. `id` is stable and persisted — renaming it resets progress for that step. Omit `target` for a centered intro/outro step. `placement`/`presentation` override the tour-level defaults.\n\n### BeaconTarget\n\n```ts\ntype BeaconTarget = BeaconTargetResolver | BeaconRect | Element | string;\n```\n\nWhat a step points at. Selectors and elements anchor to real DOM; rects (or resolvers returning one) anchor to element-less geometry such as a canvas region.\n\n### BeaconTargetResolver\n\n```ts\ntype BeaconTargetResolver = () => Element | BeaconRect | null;\n```\n\nResolves a target lazily; `null` means \"not available yet\".\n\n### BeaconRect\n\n```ts\ninterface BeaconRect {\n readonly height: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n}\n```\n\nA viewport-space rectangle in CSS pixels. Matches `@vielzeug/orbit`'s `Rect` shape.\n\n### BeaconPlacement\n\n```ts\ntype BeaconPlacement =\n | 'auto'\n | 'bottom'\n | 'bottom-end'\n | 'bottom-start'\n | 'left'\n | 'left-end'\n | 'left-start'\n | 'right'\n | 'right-end'\n | 'right-start'\n | 'top'\n | 'top-end'\n | 'top-start';\n```\n\nPreferred side for an anchored presentation; `'auto'` asks the positioning layer to choose.\n\n### BeaconPresentation\n\n```ts\ntype BeaconPresentation = 'auto' | 'bottom-sheet' | 'modal' | 'popover';\n```\n\nHow a step should be presented. `'auto'` lets the presentation layer pick by available space.\n\n### BeaconStatus\n\n```ts\ntype BeaconStatus = 'active' | 'completed' | 'dismissed' | 'idle' | 'paused';\n```\n\nTour lifecycle, persisted across visits. `'idle'` means never started.\n\n### BeaconProgress\n\n```ts\ninterface BeaconProgress {\n readonly status: BeaconStatus;\n readonly stepIndex: number;\n readonly version: number;\n}\n```\n\nThe persisted record for one tour or coachmark. `stepIndex` is `-1` before the first step. Records are validated on read; invalid records fall back to a fresh tour.\n\n### BeaconStorage\n\n```ts\ninterface BeaconStorage {\n get(key: string): Promise<BeaconProgress | null | undefined> | BeaconProgress | null | undefined;\n remove(key: string): Promise<unknown> | unknown;\n set(key: string, value: BeaconProgress): Promise<unknown> | unknown;\n}\n```\n\nMinimal storage contract; sync or async. Values are JSON. Keys arrive namespaced (`@vielzeug/beacon:<id>`). A `@vielzeug/vault` store plugs in with:\n\n```ts\nconst storage: BeaconStorage = {\n get: (key) => store.get('progress', key),\n remove: (key) => store.delete('progress', key),\n set: (key, value) => store.put('progress', { id: key, ...value }),\n};\n```\n\n### BeaconCurrentStep\n\n```ts\ninterface BeaconCurrentStep {\n readonly placement: BeaconPlacement;\n readonly presentation: BeaconPresentation;\n readonly rect: BeaconRect | null;\n readonly step: BeaconStep | null;\n readonly stepIndex: number;\n readonly totalSteps: number;\n}\n```\n\nThe snapshot a presentation layer renders from. `step` is `null` before start and after the tour ends; `rect` is `null` for centered steps and unresolved targets. While a step is active, Beacon keeps `rect` fresh on scroll, resize, and target layout changes — no app-side refresh call is needed.\n\n### BeaconTourEvent\n\n```ts\ntype BeaconTourEvent =\n | { readonly index: number; readonly step: BeaconStep; readonly type: 'step:start' }\n | { readonly index: number; readonly step: BeaconStep; readonly type: 'step:complete' }\n | { readonly reason: 'finish' | 'skip'; readonly type: 'tour:complete' }\n | { readonly type: 'tour:dismiss' }\n | { readonly status: BeaconStatus; readonly type: 'status-change' }\n | { readonly message: string; readonly type: 'target-missing' }\n | { readonly index: number; readonly message: string; readonly step: BeaconStep; readonly type: 'target-waiting' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\nNotable moments a tour reports through `tap()`. `target-missing` means a step was skipped because its target did not appear in time; `target-waiting` fires when a step begins waiting for its target to mount; `warning` carries storage or handler failures.\n\n### BeaconCoachmarkEvent\n\n```ts\ntype BeaconCoachmarkEvent =\n | { readonly type: 'coachmark:show' }\n | { readonly type: 'coachmark:dismiss' }\n | { readonly type: 'target-waiting' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\nNotable moments a coachmark reports through `tap()`.\n\n### BeaconTourHandle / BeaconCoachmarkHandle\n\nThe objects returned by `createTour()` and `createCoachmark()`, documented in [Core Functions](#core-functions). Both expose `disposalSignal`, `disposed`, `tap()`, `dispose()`, and `[Symbol.dispose]()`.\n\n## Errors\n\n| Error | Triggered by | Notes |\n| --------------------- | ----------------------------------------------------- | ------------------------------------------------------------------ |\n| `BeaconError` | Base for all beacon errors | `name` is the subclass name; `cause` supported via `ErrorOptions`. |\n| `BeaconConfigError` | Empty `id`, empty `steps`, missing/duplicate step ids | Thrown synchronously from `createTour()`/`createCoachmark()`. |\n| `BeaconDisposedError` | Calling handle methods after `dispose()` | `dispose()` itself never throws. |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Beacon: Usage Guide'\ndescription: How to use @vielzeug/beacon.\n---\n\n[[toc]]\n\n## Basic Usage\n\nA tour is a config object plus a handle you drive from your own UI. The handle never renders anything: it publishes a `current` snapshot, and your card (or refine's `ore-tour`) renders it.\n\n```ts\nimport { createTour } from '@vielzeug/beacon';\n\nconst tour = createTour({\n id: 'product-tour',\n steps: [\n { id: 'welcome', title: 'Welcome', description: 'See what changed in this release.' },\n { id: 'nav', target: '[data-tour=\"nav\"]', title: 'Find everything', placement: 'bottom-start' },\n { id: 'share', target: '[data-tour=\"share\"]', title: 'Share the board', placement: 'bottom-end' },\n ],\n autoStart: true,\n});\n\n// Readable<T> from @vielzeug/ripple: the listener takes no arguments;\n// read .value inside it.\nconst unsubscribe = tour.current.subscribe(() => {\n const current = tour.current.value;\n if (!current.step) {\n hideCard();\n return;\n }\n renderCard({\n anchor: current.rect, // viewport rect of the target, null for centered steps\n index: current.stepIndex,\n placement: current.placement,\n presentation: current.presentation,\n title: current.step.title,\n total: current.totalSteps,\n });\n});\n\n// Wire your card's controls back to the handle.\ncardEl.addEventListener('next', () => tour.next());\ncardEl.addEventListener('back', () => tour.back());\ncardEl.addEventListener('skip', () => tour.skip());\n\n// On teardown:\nunsubscribe();\ntour.dispose();\n```\n\n`start()` is a no-op when the stored record says this user already completed the tour, so calling it on every page load is safe.\n\n## Steps and Targets\n\nA step without a `target` centers (intro/outro copy). A step with one anchors, and beacon waits for the target to exist before publishing the step — a tour can walk through lazily-mounted routes without any coordination code.\n\n```ts\nconst tour = createTour({\n id: 'deep-tour',\n steps: [\n // Selector: resolved with document.querySelector on activation.\n { id: 'sidebar', target: '[data-tour=\"sidebar\"]', title: 'Your libraries' },\n // Element: a ref your framework already holds.\n { id: 'editor', target: editorEl, title: 'The editor' },\n // Rect: geometry with no element, such as a canvas region.\n { id: 'chart', target: { height: 120, width: 240, x: 400, y: 300 }, title: 'This trend' },\n // Resolver: computed on every activation, and on scroll/resize while the step is active.\n {\n id: 'selection',\n target: () => window.getSelection()?.getRangeAt(0).getBoundingClientRect() ?? null,\n title: 'Your selection',\n },\n ],\n // Give up waiting after 4s and skip the step instead of hanging the tour.\n targetTimeoutMs: 4000,\n});\n```\n\nWith the default `targetTimeoutMs: Infinity`, a step whose target never mounts simply waits: the tour resumes the moment the user navigates to it. Set `0` to publish immediately with a `null` rect instead of waiting.\n\n## Persisting Progress\n\nWithout `storage`, progress lives in memory for the handle's lifetime only. Any object matching `BeaconStorage` makes it durable — values are JSON, keys are namespaced under `@vielzeug/beacon:`.\n\n```ts\nimport type { BeaconStorage } from '@vielzeug/beacon';\n\nconst storage: BeaconStorage = {\n get: (key) => JSON.parse(localStorage.getItem(key) ?? 'null'),\n remove: (key) => localStorage.removeItem(key),\n set: (key, value) => localStorage.setItem(key, JSON.stringify(value)),\n};\n\nconst tour = createTour({ id: 'product-tour', steps, storage });\n```\n\nAsync storage works too: `get` may return a promise, and the tour boots as soon as it resolves. A `set` that rejects is reported through `tap()` as a `warning` event, never thrown.\n\nRecords are validated on read, so a hand-edited or stale record falls back to a fresh tour instead of crashing.\n\n### Re-offering a finished tour\n\nBump `version` when the product changes and every user who finished the old tour becomes eligible again — users mid-tour on the old version keep their progress.\n\n```ts\nconst tour = createTour({\n id: 'product-tour',\n steps: newSteps,\n version: 2, // stored records at version 1 no longer block the tour\n});\n```\n\n`reset()` clears the persisted record for the current user, which is what a \"Replay tour\" or \"Reset onboarding\" control should call before `start()`.\n\n## Driving a Refine Presentation\n\n`@vielzeug/refine` ships `ore-tour` (a dialog with step footer, progress, and focus handling) and `ore-spotlight` (a decorative cutout that dims everything but the target). A beacon handle satisfies `ore-tour`'s `TourController` shape, so one call wires both directions:\n\n```ts\nimport type { OreTourElement } from '@vielzeug/refine/tour';\n\nconst card = document.querySelector<OreTourElement>('#tour-card');\n\nconst tour = createTour({ id: 'product-tour', presentation: 'auto', steps });\n\n// bind() renders `current` into the card's props and routes the card's\n// next/back/skip/finish/dismiss actions back into the handle.\nconst unbind = card.bind(tour);\n\ntour.start();\n\n// On teardown:\nunbind();\ntour.dispose();\n```\n\n`presentation: 'auto'` maps to a popover on wide viewports and a bottom sheet on narrow ones; ore-tour makes that switch itself and freezes the choice while the card is open, so a mid-step resize never rebuilds the card. Beacon keeps `current.rect` fresh on scroll, resize, and layout changes, so the anchored card follows the layout with no app-side listeners.\n\nApps that render their own markup read `current` directly instead (see [Basic Usage](#basic-usage)).\n\n## Coachmarks\n\nA coachmark is one hint anchored to one target, shown the first time the target appears and dismissed permanently after. Use it for the \"explain this button once\" moment a tour would be too heavy for — or as the follow-up a tour hands off to.\n\n```ts\nimport { createCoachmark } from '@vielzeug/beacon';\n\nconst share = createCoachmark({\n id: 'share-hint',\n target: '[data-tour=\"share\"]',\n title: 'Share this board',\n description: 'Send a link that opens straight into this view.',\n storage,\n});\n\n// Render from `current` — the same single-step snapshot a tour publishes.\nshare.current.subscribe(() => console.log(share.current.value.step !== null, share.current.value.rect));\n\n// The target may never appear on this page; show() waits for it.\nshare.show();\n\n// \"Got it\" button:\nshare.dismiss(); // records it as seen; never shows again for this version\n```\n\n`hide()` closes the hint without recording it, so it can appear again later; `dismiss()` is permanent until `reset()` or a `version` bump.\n\n## Events and Analytics\n\n`tap()` observes everything the engine considers notable. It returns an unsubscribe function and accepts an `AbortSignal`, so one controller can tear down every subscription.\n\n```ts\nconst controller = new AbortController();\n\ntour.tap(\n (event) => {\n switch (event.type) {\n case 'step:start':\n analytics.track('tour_step', { id: tour.id, step: event.step.id });\n break;\n case 'tour:complete':\n analytics.track('tour_complete', { id: tour.id, reason: event.reason });\n break;\n case 'target-missing':\n // A step's target never mounted: your selector drifted from the DOM.\n console.warn(event.message);\n break;\n case 'warning':\n console.warn(event.message, event.error);\n break;\n }\n },\n { signal: controller.signal },\n);\n```\n\n`target-missing` is the event to alert on: it means a step was skipped because its target did not appear within `targetTimeoutMs`, which is exactly how stale tours announce themselves.\n\n## Testing\n\nBeacon runs without a rendering layer, so plain DOM tests are enough. The default in-memory storage keeps each handle's progress isolated, and `jsdom`'s `getBoundingClientRect()` returns zero-sized rects, which is fine for step-order assertions.\n\n```ts\nimport { createTour } from '@vielzeug/beacon';\nimport { expect, test } from 'vitest';\n\ntest('walks steps in order and completes', () => {\n const tour = createTour({\n id: 'test-tour',\n steps: [{ id: 'a' }, { id: 'b' }],\n targetTimeoutMs: 0, // publish immediately even without targets\n });\n\n tour.start();\n expect(tour.current.value.step?.id).toBe('a');\n\n tour.next();\n expect(tour.current.value.step?.id).toBe('b');\n\n tour.next(); // past the last step finishes\n expect(tour.status.value).toBe('completed');\n});\n```\n\nFor persistence assertions, pass a `Map`-backed `BeaconStorage` and a second handle with the same `id` to check it resumes where the first stopped.\n\n## Framework Integration\n\nBeacon is framework-neutral: bridge the `Readable` snapshot with whatever primitive your framework already has.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useState } from 'react';\nimport { createTour } from '@vielzeug/beacon';\n\nfunction useTourState(tour: ReturnType<typeof createTour>) {\n const [current, setCurrent] = useState(tour.current.value);\n useEffect(() => tour.current.subscribe(() => setCurrent(tour.current.value)), [tour]);\n return current;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onScopeDispose, shallowRef } from 'vue';\nimport { createTour } from '@vielzeug/beacon';\n\nconst current = shallowRef(tour.current.value);\nconst unsubscribe = tour.current.subscribe(() => (current.value = tour.current.value));\nonScopeDispose(unsubscribe);\n</script>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onDestroy } from 'svelte';\n import { readable } from 'svelte/store';\n\n const current = readable(tour.current.value, (set) => {\n set(tour.current.value);\n return tour.current.subscribe(() => set(tour.current.value));\n });\n onDestroy(() => tour.dispose());\n</script>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n- **Refine**: `ore-tour` and `ore-spotlight` are the intended presentation layer; see [Driving a Refine Presentation](#driving-a-refine-presentation).\n- **Orbit**: `current.rect` matches orbit's `Rect` shape, so a custom card positions with `computePosition({ getBoundingClientRect: () => current.rect ?? ZERO_RECT }, floatingEl, middleware)`.\n- **Vault**: any vault store becomes a `BeaconStorage` with a six-line bridge (see the `BeaconStorage` docs in [API Reference](./api.md)).\n- **Ripple**: every handle exposes ripple `Readable`s; `createRipple().isBatchingObservable` semantics apply when you subscribe from effects.\n\n## Best Practices\n\n- Give every tour and coachmark a stable `id` — it is the storage key; treat renames as data migrations.\n- Keep tour configs in their own modules as plain data checked with `satisfies BeaconTourConfig`, so steps stay reviewable data, not component code.\n- Prefer `data-tour=\"...\"` attributes as target selectors: they survive class renames and read as intent.\n- Set a finite `targetTimeoutMs` in production and alert on `target-missing` to catch stale selectors.\n- Call `reset()` before `start()` for replay controls; never delete storage keys by hand.\n- Bump `version` when a tour's meaning changes, not when its copy is typo-fixed.\n- Dispose handles on teardown; `tap()` subscriptions with a shared `AbortSignal` clean up in one call.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Beacon: Examples'\ndescription: Practical examples and recipes for @vielzeug/beacon.\n---\n\n## Examples\n\n- [Guided Tour](./examples/guided-tour.md)\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [
|
|
10
|
-
{
|
|
11
|
-
"id": "coachmark",
|
|
12
|
-
"code": "import { createCoachmark } from '@vielzeug/beacon'\n\nconst button = document.createElement('button')\nbutton.textContent = 'Share'\nbutton.dataset.tour = 'share'\ndocument.body.appendChild(button)\n\nconst hint = createCoachmark({\n autoShow: false,\n description: 'Send a link that opens straight into this view.',\n id: 'share-hint',\n target: '[data-tour=\"share\"]',\n title: 'Share this board',\n})\n\nhint.tap((event) => console.log('event:', event.type))\n\n// current is the single-step snapshot: step is the hint while visible, null while hidden.\nhint.current.subscribe(() => console.log('visible:', hint.current.value.step !== null))\n\nhint.show()\nconsole.log('rect anchored to button:', JSON.stringify(hint.current.value.rect))\n\n// hide() can come back; dismiss() records it as seen.\nhint.hide()\nhint.show()\nhint.dismiss()\n\n// Once dismissed, show() is a no-op until reset() or a version bump.\nhint.show()\nconsole.log('eligible after dismiss:', hint.eligible.value)\n\nhint.reset()\nconsole.log('eligible after reset:', hint.eligible.value)",
|
|
13
|
-
"name": "Coachmark - Show Once, Dismiss, Reset"
|
|
14
|
-
},
|
|
15
|
-
{
|
|
16
|
-
"id": "persist-progress",
|
|
17
|
-
"code": "import { createTour } from '@vielzeug/beacon'\n\n// Any key-value object is a BeaconStorage; keys arrive namespaced.\nconst db = new Map()\nconst storage = {\n get: (key) => (db.has(key) ? JSON.parse(db.get(key)) : null),\n remove: (key) => db.delete(key),\n set: (key, value) => db.set(key, JSON.stringify(value)),\n}\n\nconst steps = [\n { id: 'a', title: 'First' },\n { id: 'b', title: 'Second' },\n { id: 'c', title: 'Third' },\n]\n\nconst first = createTour({ id: 'resume-demo', steps, storage, targetTimeoutMs: 0 })\nfirst.start()\nfirst.next()\nconsole.log('First session stopped at step index:', first.current.value.stepIndex)\nfirst.pause() // keeps progress so the next handle resumes\n\n// A brand-new handle (next page load) resumes from the stored record.\nconst second = createTour({ id: 'resume-demo', steps, storage, targetTimeoutMs: 0 })\nconsole.log('Resumed status:', second.status.value)\nsecond.start()\nconsole.log('Resumed at step:', second.current.value.step.title)\n\nsecond.finish()\nconsole.log('After finish:', second.status.value)\n\n// start() is a no-op for completed tours:\nsecond.start()\nconsole.log('Still:', second.status.value)\n\n// reset() makes it eligible again (what a \"Replay tour\" button calls):\nsecond.reset()\nsecond.start()\nconsole.log('After reset + start, step:', second.current.value.step.title)",
|
|
18
|
-
"name": "Persist Progress - Resume, Finish, Replay"
|
|
19
|
-
},
|
|
20
|
-
{
|
|
21
|
-
"id": "tour-basics",
|
|
22
|
-
"code": "import { createTour } from '@vielzeug/beacon'\n\n// A tiny stage so the tour has something real to anchor to.\nconst stage = document.createElement('div')\nstage.innerHTML = '<button data-tour=\"nav\" style=\"margin:24px\">Navigation</button><button data-tour=\"share\" style=\"margin:24px\">Share</button>'\ndocument.body.appendChild(stage)\n\nconst tour = createTour({\n autoScroll: false, // jsdom has no real scrolling\n id: 'repl-tour',\n steps: [\n { id: 'welcome', title: 'Welcome' },\n { id: 'nav', target: '[data-tour=\"nav\"]', title: 'Navigation' },\n { id: 'share', target: '[data-tour=\"share\"]', title: 'Share' },\n ],\n targetTimeoutMs: 0,\n})\n\n// Readable<T>: the listener takes no arguments, read .value inside.\ntour.current.subscribe(() => {\n const current = tour.current.value\n if (!current.step) return\n console.log('Step ' + (current.stepIndex + 1) + ' of ' + current.totalSteps + ': ' + current.step.title)\n console.log(' anchor rect:', current.rect === null ? 'null (centered)' : JSON.stringify(current.rect))\n})\n\ntour.tap((event) => {\n if (event.type === 'tour:complete') console.log('Tour complete, reason:', event.reason)\n})\n\ntour.start()\ntour.next()\ntour.next()\ntour.next() // past the last step finishes the tour\n\nconsole.log('status:', tour.status.value)",
|
|
23
|
-
"name": "Tour Basics - Steps, Rects, Completion"
|
|
24
|
-
}
|
|
25
|
-
],
|
|
26
|
-
"typeSignatures": {
|
|
27
|
-
"createCoachmark": "export { createCoachmark } from './coachmark';",
|
|
28
|
-
"BeaconConfigError": "export { BeaconConfigError, BeaconDisposedError, BeaconError } from './errors';",
|
|
29
|
-
"BeaconDisposedError": "export { BeaconConfigError, BeaconDisposedError, BeaconError } from './errors';",
|
|
30
|
-
"BeaconError": "export { BeaconConfigError, BeaconDisposedError, BeaconError } from './errors';",
|
|
31
|
-
"resolveTarget": "export { resolveTarget } from './target';",
|
|
32
|
-
"createTour": "export { createTour } from './tour';",
|
|
33
|
-
"BeaconBaseEvent": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
34
|
-
"BeaconCoachmarkConfig": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
35
|
-
"BeaconCoachmarkEvent": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
36
|
-
"BeaconCoachmarkHandle": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
37
|
-
"BeaconCurrentStep": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
38
|
-
"BeaconPlacement": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
39
|
-
"BeaconPresentation": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
40
|
-
"BeaconProgress": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
41
|
-
"BeaconRect": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
42
|
-
"BeaconStatus": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
43
|
-
"BeaconStep": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
44
|
-
"BeaconStorage": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
45
|
-
"BeaconTarget": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
46
|
-
"BeaconTargetResolver": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
47
|
-
"BeaconTourConfig": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
48
|
-
"BeaconTourEvent": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
|
|
49
|
-
"BeaconTourHandle": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';"
|
|
50
|
-
}
|
|
51
|
-
}
|