@vielzeug/codex 26.11.22 → 26.11.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +283 -51
- package/data/llms-full.txt +2626 -15
- package/data/llms.txt +7 -2
- package/data/manifest.json +1 -1
- package/data/packages/atlas.json +81 -0
- package/data/packages/beacon.json +1 -1
- package/data/packages/codex.json +1 -1
- package/data/packages/gesture.json +27 -5
- package/data/packages/ink.json +41 -0
- package/data/packages/palette.json +42 -0
- package/data/packages/prism.json +1 -1
- package/data/packages/stage.json +26 -0
- package/data/packages/wire.json +51 -0
- package/data/refine.json +224 -209
- package/package.json +2 -2
- package/skills/vielzeug/SKILL.md +7 -2
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
|
-
"apiSource": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';\nexport { GestureConfigError, GestureError } from './errors.js';\nexport {\n createLongPress,\n type LongPress,\n type LongPressDetail,\n type LongPressOptions,\n} from './long-press.js';\nexport {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';\n",
|
|
2
|
+
"apiSource": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';\nexport { GestureConfigError, GestureError } from './errors.js';\nexport {\n createLongPress,\n type LongPress,\n type LongPressDetail,\n type LongPressOptions,\n} from './long-press.js';\nexport {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';\nexport {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';\nexport {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Gesture: Pointer movement primitives'\ndescription: Framework-neutral
|
|
5
|
-
"api": "---\ntitle: 'Gesture: API Reference'\ndescription: API reference for two-dimensional drag and one-axis pan recognition.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------ | --------------------------------------------------- | -------------- | ------------------------------------------------------- |\n| `createDragGesture()` | Track unrestricted two-dimensional pointer movement | Sync | Does not provide DOM movement or drop semantics |\n| `createPanGesture()` | Track pointer movement projected onto one axis | Sync | Cross-axis intent ends a pending interaction |\n| `createLongPress()` | Recognize a primary pointer held in place | Sync | The click that follows a fired hold is swallowed |\n| `DragGesture` / `PanGesture` / `LongPress` | Control recognition lifecycle | Sync | `dispose()` does not invoke `onEnd` |\n| `DragGestureOptions` | Configure free-drag recognition | Sync | `activationDistance` uses Euclidean distance |\n| `PanGestureOptions` | Configure axis-locked recognition | Sync | Completion thresholds belong in `onEnd` |\n| `LongPressOptions` | Configure hold recognition | Sync | `durationMs` and `slopPx` are validated at construction |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------- | ----------------------------------------------------------------------------------------- |\n| `@vielzeug/gesture` | Drag and pan factories, handles, callback details, options, axes, points, and end reasons |\n\n## Core Functions\n\n### `createDragGesture()`\n\n```ts\nfunction createDragGesture(target: Element, options?: DragGestureOptions): DragGesture;\n```\n\nTracks one primary pointer without restricting movement to an axis.\n\n| Parameter | Type | Description |\n| --------- | -------------------- | --------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `DragGestureOptions` | Activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `DragGesture` handle.\n\n**Example**\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst drag = createDragGesture(element, {\n onMove: ({ delta }) => {\n element.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n element.style.translate = '';\n },\n});\n```\n\n---\n\n### `createPanGesture()`\n\n```ts\nfunction createPanGesture(target: Element, options?: PanGestureOptions): PanGesture;\n```\n\nTracks one primary pointer after movement establishes intent on the configured axis.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | --------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `PanGestureOptions` | Axis, activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `PanGesture` handle.\n\n**Example**\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 48) dismiss();\n },\n});\n```\n\nBoth handles expose the same members:\n\n| Member | Type | Contract |\n| -------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------- |\n| `active` | `boolean` | `true` after activation and before release or cancellation |\n| `cancel()` | `() => boolean` | Clears pending recognition or ends active recognition with `reason: 'cancel'`; returns whether a session existed |\n| `disposalSignal` | `AbortSignal` | Aborts when the handle is disposed |\n| `dispose()` | `() => void` | Aborts `disposalSignal`, clears recognition, releases capture, and detaches listeners; idempotent |\n| `disposed` | `boolean` | `true` after disposal |\n| `[Symbol.dispose]()` | `() => void` | Calls `dispose()` |\n\n---\n\n### `createLongPress()`\n\n```ts\nfunction createLongPress(target: Element, options?: LongPressOptions): LongPress;\n```\n\nRecognizes a primary pointer held in place: `onLongPress` fires with the originating pointerdown once the hold outlasts `durationMs`.\n\n| Parameter | Type | Description |\n| --------- | ------------------ | ---------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission, document tracking, and click swallowing |\n| `options` | `LongPressOptions` | Hold time, slop distance, admission, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `LongPress` handle with the same members as the other gestures; `active` is `true` while a hold is pending.\n\n**Example**\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(list, {\n shouldStart: (event) => event.pointerType !== 'mouse',\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest('.tile');\n openDetail(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx`, a second touch, window blur, or a hidden document cancels a pending hold. The dynamic `disabled` predicate is checked again before the timer fires. The pointer-generated click following a fired hold is swallowed through a capture-phase listener on `target`; keyboard clicks (`detail: 0`) remain available. Bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers.\n\n## Types\n\n### Drag types\n\n```ts\ntype DragEndReason = 'cancel' | 'release';\n\ntype DragPoint = Readonly<{\n x: number;\n y: number;\n}>;\n\ntype DragGestureDetail = Readonly<{\n current: DragPoint;\n delta: DragPoint;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: DragPoint;\n target: Element;\n velocity: DragPoint;\n}>;\n\ntype DragGestureEndDetail = DragGestureDetail &\n Readonly<{\n reason: DragEndReason;\n }>;\n\ntype DragGestureOptions = Readonly<{\n activationDistance?: number;\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: DragGestureEndDetail) => void;\n onMove?: (detail: DragGestureDetail) => void;\n onStart?: (detail: DragGestureDetail) => void;\n pointerCapture?: boolean;\n shouldActivate?: (detail: DragGestureDetail) => boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\n`start`, `current`, and `delta` use viewport `clientX` and `clientY` coordinates. Activation uses `Math.hypot(delta.x, delta.y)`.\n\n### Pan types\n\n```ts\ntype PanAxis = 'x' | 'y';\ntype PanEndReason = 'cancel' | 'release';\n\ntype PanGestureDetail = Readonly<{\n axis: PanAxis;\n current: number;\n distance: number;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: number;\n target: Element;\n velocity: number;\n}>;\n\ntype PanGestureEndDetail = PanGestureDetail &\n Readonly<{\n reason: PanEndReason;\n }>;\n\ntype PanGestureOptions = Readonly<{\n activationDistance?: number;\n axis?: PanAxis | (() => PanAxis);\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: PanGestureEndDetail) => void;\n onMove?: (detail: PanGestureDetail) => void;\n onStart?: (detail: PanGestureDetail) => void;\n pointerCapture?: boolean;\n shouldActivate?: (detail: PanGestureDetail) => boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\nPan details project `start`, `current`, and `distance` onto `axis`. The default axis is `'x'`.\n\nVelocity is signed CSS pixels per second over the trailing 90 ms. Samples include pointerdown, movement (including activation), and release. A window with fewer than two distinct sample times reports zero velocity; a pause longer than the window removes earlier movement.\n\n### Long-press types\n\n```ts\ntype LongPressDetail = Readonly<{\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n target: Element;\n}>;\n\ntype LongPressOptions = Readonly<{\n durationMs?: number;\n disabled?: boolean | (() => boolean | undefined);\n onLongPress?: (detail: LongPressDetail) => void;\n shouldStart?: (event: PointerEvent) => boolean;\n slopPx?: number;\n signal?: AbortSignal;\n}>;\n```\n\n`durationMs` defaults to `500` and `slopPx` to `8`. `event` is the pointerdown that started the hold, so `event.target` is the pressed element.\n\n### Handle types\n\n```ts\ntype DragGesture = {\n readonly active: boolean;\n [Symbol.dispose](): void;\n cancel(): boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n};\n\ntype PanGesture = DragGesture;\n```\n\n### Shared option behavior\n\n| Option | Default | Contract |\n| -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |\n| `activationDistance` | `6` | Non-negative finite CSS pixels; drag uses Euclidean distance, pan waits for dominant-axis intent |\n| `axis` | `'x'` | Pan only; fixed value or getter sampled when each interaction starts |\n| `disabled` | `false` | Fixed value or getter; blocks starts and cancels active recognition on the next matching pointer event |\n| `pointerCapture` | `true` | Best-effort capture after activation; document tracking continues when capture is disabled or fails |\n| `shouldStart` | N/A | Admission predicate evaluated for the primary pointer before tracking starts |\n| `shouldActivate` | N/A | Drag/pan predicate evaluated once after distance/axis recognition and before capture or callbacks; false rejects the session |\n| `signal` | N/A | Disposes the handle when the external owner aborts |\n| `onStart` | N/A | Runs once on the activating movement |\n| `onMove` | N/A | Runs on the activating movement and each later matching movement |\n| `onEnd` | N/A | Runs once for active release or cancellation; pending interactions end without callbacks |\n\nOptions and callback details are readonly. Fixed callbacks and capture policy are snapshotted at construction. Function-valued `axis` and `disabled` options remain dynamic.\n\nGesture tracks accepted movement with capture-phase listeners on the target's current owner document. Window blur, hidden-document transition, `pointercancel`, pointer capture loss on the gesture target, and a second touch anywhere in that document cancel recognition. A `lostpointercapture` event bubbling from a descendant does not cancel the target's gesture. Exact diagonal ties remain pending until one axis dominates; cross-axis dominance rejects the pending pan. Gesture does not arbitrate ownership between recognizers on the same axis.\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| -------------------- | --------------------------------------------- | --------------------------------------------------- |\n| `GestureError` | Base class for every gesture-originated error | `instanceof GestureError` catches any gesture error |\n| `GestureConfigError` | Invalid option value | Extends `GestureError` |\n\n- Invalid `activationDistance` values throw `GestureConfigError` during construction.\n- Invalid fixed `axis` values throw `GestureConfigError` during construction.\n- Invalid values returned by a dynamic `axis` getter throw `GestureConfigError` when a pointer interaction starts.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Gesture: Usage Guide'\ndescription: Track unrestricted pointer dragging and axis-locked pans with application-owned rendering and completion.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate one handle for the element that owns the interaction. This example creates its surface, applies the required touch policy, and disposes the handle when the page unloads.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst row = document.body.appendChild(document.createElement('div'));\nrow.textContent = 'Swipe to archive';\nrow.style.touchAction = 'pan-y';\n\nconst pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) {\n pan.dispose();\n row.remove();\n }\n },\n});\n\nwindow.addEventListener('pagehide', () => pan.dispose(), { once: true });\n```\n\n## Track Two-Dimensional Dragging\n\nUse `createDragGesture()` when movement must remain unrestricted in both dimensions:\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst card = document.querySelector<HTMLElement>('[data-draggable]');\nif (!card) throw new Error('Missing [data-draggable] element');\n\nconst drag = createDragGesture(card, {\n activationDistance: 6,\n onMove: ({ delta }) => {\n card.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n card.style.translate = '';\n },\n});\n\nwindow.addEventListener('pagehide', () => drag.dispose(), { once: true });\n```\n\n`start`, `current`, and `delta` are readonly `{ x, y }` points. Set `touch-action: none` when the surface owns movement in both dimensions. Drag recognition does not provide previews, drop targets, DOM movement, or `DataTransfer`; use Dnd for those semantics.\n\n## Recognize Long Presses\n\nUse `createLongPress()` for hold interactions: the touch counterpart of a keyboard preview key. `onLongPress` receives the originating pointerdown once the hold outlasts `durationMs`:\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(grid, {\n durationMs: 500,\n shouldStart: (event) => event.pointerType !== 'mouse' && (event.target as HTMLElement).closest('.tile') !== null,\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest<HTMLElement>('.tile');\n openPreview(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx` cancels back to a normal press, so scrolling never triggers the hold. The click that follows a fired hold is swallowed through a capture-phase listener on `target`: bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers, and gate `shouldStart` to the elements the hold belongs to.\n\n## Completion Rules\n\nGesture reports movement and terminal state but does not decide what constitutes a swipe. Apply thresholds and allowed directions in `onEnd`.\n\n```ts\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && distance <= -80) {\n openNext();\n } else {\n resetPanel();\n }\n },\n});\n```\n\n## Direction Recognition\n\nThe gesture remains pending during small movement and exact diagonal ties. It activates only after movement strictly favors the configured axis. Cross-axis movement ends the pending interaction without invoking callbacks.\n\nThe default `activationDistance` is 6 pixels. Tune direction-recognition slop for touch density or component-specific needs:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n activationDistance: 12,\n onMove,\n onEnd,\n});\n```\n\nSet `activationDistance: 0` when the first pointer move with non-zero displacement should activate immediately. Zero-motion events remain pending.\n\nUse the corresponding `touch-action` value so the browser retains native scrolling on the other axis.\n\n```css\n.swipe-row {\n touch-action: pan-y pinch-zoom;\n}\n```\n\n```ts\nconst pan = createPanGesture(row, { axis: 'x', onMove });\n```\n\nUse `shouldStart` to exclude controls at pointerdown. Use `shouldActivate` for direction or boundary checks that require movement; rejection happens before capture or callbacks.\n\n```ts\nconst pan = createPanGesture(panel, {\n axis: 'y',\n shouldActivate: ({ distance }) => distance > 0 && scroller.scrollTop <= 0,\n onMove: renderPull,\n onEnd: settlePull,\n});\n```\n\nGesture cancels pending and active touch recognition when a second finger touches the owner document. Reset presentation on `reason: 'cancel'`; never commit an action from cancellation. Native scroll and pinch behavior still depends on the surface's CSS and event handling. Once native scrolling owns a touch sequence, start a fresh swipe at the boundary rather than attempting a mid-scroll handoff.\n\n## Pointer Capture\n\nPointer capture is enabled by default. After axis intent is accepted, Gesture attempts to capture the pointer while continuing to track movement through document-level listeners. Capture failure (for example after target detachment or pointer termination) falls back to document tracking without stranding the session.\n\nDisable capture when nested or newly revealed controls must retain native pointer-up and click targeting:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n pointerCapture: false,\n onMove: renderReveal,\n onEnd: settleReveal,\n});\n```\n\nDocument-level tracking still keeps the pan active outside the target. Disabling capture changes event targeting, not gesture tracking.\n\n## Interactive Descendants\n\nUse `shouldStart` when buttons, links, or form controls inside the surface must not start a pan.\n\n```ts\nconst pan = createPanGesture(notification, {\n axis: 'x',\n pointerCapture: false,\n shouldStart: (event) =>\n !event.composedPath().some((node) => node instanceof Element && node.matches('button, a, input, select, textarea')),\n onMove,\n onEnd,\n});\n```\n\n`shouldStart` protects controls under the initial pointer. `pointerCapture: false` additionally protects controls that appear beneath the pointer during a reveal interaction.\n\n## Disabled State\n\nA boolean disables the recognizer permanently. A getter supports state that changes while the handle is alive.\n\n```ts\nconst pan = createPanGesture(row, {\n disabled: () => isLocked,\n onEnd: ({ reason }) => {\n if (reason === 'cancel') resetRow();\n },\n});\n```\n\nWhen the getter becomes `true`, the next pointer event cancels an active pan. Window blur or a hidden owner document also cancels active tracking so a lost release cannot block later gestures.\n\nGesture snapshots fixed callbacks and capture policy at construction. Use the `axis` and `disabled` functions for behavior that must remain dynamic instead of mutating the options object.\n\n## Lifecycle\n\nDispose the target-bound handle when its owning UI scope unmounts.\n\n```ts\nconst element = document.querySelector<HTMLElement>('[data-pan]');\nif (!element) throw new Error('Missing [data-pan] element');\n\nconst owner = new AbortController();\nconst request = new AbortController();\nconst pan = createPanGesture(element, {\n axis: 'x',\n signal: owner.signal,\n});\n\nconst childSignal = AbortSignal.any([pan.disposalSignal, request.signal]);\nwindow.addEventListener('pagehide', () => owner.abort(), { once: true });\n```\n\nPass `{ signal }` to dispose with an existing owner signal. `disposalSignal` always aborts when Gesture finishes teardown, so child work can compose with the handle regardless of how disposal starts.\n\nUse `cancel()` to stop a pending or active interaction without disposing the handle. An active interaction emits `onEnd` with `reason: 'cancel'`. Call `cancel()` before `dispose()` when a connected surface needs its `onEnd` reset path; disposal itself does not invoke callbacks.\n\n## Framework Integration\n\nCreate the handle after the target element exists and dispose it on unmount.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\nimport { createPanGesture } from '@vielzeug/gesture';\n\nfunction SwipeRow({ onDismiss }: { onDismiss: () => void }) {\n const rowRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const row = rowRef.current;\n if (!row) return;\n\n const pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) onDismiss();\n },\n });\n\n return () => pan.dispose();\n }, [onDismiss]);\n\n return <div ref={rowRef}>Swipe me</div>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, ref } from 'vue';\nimport { createPanGesture, type PanGesture } from '@vielzeug/gesture';\n\nconst emit = defineEmits<{ dismiss: [] }>();\nconst rowEl = ref<HTMLDivElement | null>(null);\nlet pan: PanGesture | undefined;\n\nonMounted(() => {\n const row = rowEl.value;\n if (!row) return;\n\n pan = createPanGesture(row, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) emit('dismiss');\n },\n });\n});\n\nonUnmounted(() => pan?.dispose());\n</script>\n\n<template>\n <div ref=\"rowEl\">Swipe me</div>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createPanGesture } from '@vielzeug/gesture';\n\n let { ondismiss = () => {} }: { ondismiss: () => void } = $props();\n let rowEl: HTMLDivElement;\n\n onMount(() => {\n const pan = createPanGesture(rowEl, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) ondismiss();\n },\n });\n\n return () => pan.dispose();\n });\n</script>\n\n<div bind:this={rowEl}>Swipe me</div>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### Gesture + Refine\n\nRefine uses Gesture internally for carousel, drawer, toast, and list-item pointer interactions. Custom surfaces can use the same pan lifecycle while keeping visual state local.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onMove: ({ distance }) => {\n panel.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n panel.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 80) revealActions();\n },\n});\n```\n\n### Gesture + Dnd\n\nGesture owns pointer recognition: unrestricted two-dimensional drag and one-axis pan. Dnd builds touch sorting on `createDragGesture()`, then owns `DataTransfer`, previews, hit-testing, file drop zones, keyboard sorting, DOM reordering, and connected-list transactions. Use Dnd when an item is picked up and dropped; use Gesture directly when application code owns rendering and completion.\n\n## Best Practices\n\n- **Set** `touch-action` for the axis the browser should continue scrolling.\n- **Use** `shouldStart` to exclude nested interactive controls.\n- **Disable** pointer capture when nested or newly revealed controls must keep native release targeting.\n- **Apply** completion thresholds and direction rules in `onEnd`; use `activationDistance` only for recognition slop.\n- **Treat** `reason: 'cancel'` as a reset path, never a commit path. Pointer capture loss on the gesture target cancels; capture loss bubbling from a descendant does not.\n- **Keep** `onMove` rendering lightweight.\n- **Dispose** the handle when its target leaves the UI.\n",
|
|
4
|
+
"index": "---\ntitle: 'Gesture: Pointer movement primitives'\ndescription: Framework-neutral pointer drag, pan, pinch, and wheel recognition with lifecycle-owned handles.\npackage: gesture\ncategory: input\nkeywords: [pointer, pan, swipe, gesture, touch, drag, long press, pinch, zoom, wheel]\nexports:\n [createDragGesture, createPanGesture, createLongPress, createPinchGesture, createWheelGesture, GestureConfigError]\nrelated: [refine, dnd, keymap]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"gesture\" />\n\n## Why Gesture?\n\nPointer-driven interfaces need reliable one-pointer movement tracking without coupling recognition to rendering, drag-and-drop semantics, or product-specific completion policy.\n\n```ts\n// Before\nelement.addEventListener('pointermove', (event) => {\n // Coordinate tracking, pointer identity, direction locking, and cleanup\n});\n\n// After\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onMove: ({ distance }) => console.log('distance', distance),\n onEnd: ({ reason }) => console.log('ended', reason),\n});\n```\n\n| Feature | Gesture | Ad-hoc pointer handling |\n| ----------------------------- | --------------------------------------------- | ----------------------- |\n| Bundle size | <PackageInfo package=\"gesture\" type=\"size\" /> | n/a |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a |\n| Two-dimensional drag tracking | Built in | Manual |\n| Axis intent recognition | Built in | Manual |\n| Pointer ownership | Tracked across the document | Manual |\n| Lifecycle cleanup | `dispose()` + `disposalSignal` | Manual |\n\n<div class=\"decision-callout\">\n\n**Use Gesture when** UI surfaces need consistent free drag or axis-locked pan tracking while retaining their own rendering and completion rules.\n\n**Consider direct pointer handling when** the interaction is isolated and does not need reusable lifecycle or direction-lock behavior.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/gesture\n```\n\n```sh [npm]\nnpm install @vielzeug/gesture\n```\n\n```sh [yarn]\nyarn add @vielzeug/gesture\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst element = document.querySelector<HTMLElement>('[data-swipe]');\nif (!element) throw new Error('Missing [data-swipe] element');\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onMove: ({ distance }) => {\n element.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n element.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 48) {\n pan.dispose();\n element.remove();\n }\n },\n});\n\nwindow.addEventListener('pagehide', () => pan.dispose(), { once: true });\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createDragGesture()`: unrestricted two-dimensional pointer movement tracking\n- `createPanGesture()`: one-axis pointer movement with direction intent recognition\n- `createLongPress()`: hold recognition with slop cancellation and click swallowing\n- `createPinchGesture()`: two-pointer scale and rotation with per-frame deltas\n- `createWheelGesture()`: wheel and trackpad input with pixel-normalized deltas\n- Direction locking: activates only when movement favors the configured axis\n- Configurable pointer capture: own the pointer by default or preserve native targeting\n- Configurable `activationDistance`: tune slop for touch density and component needs\n- Consumer-owned policy: completion thresholds, snapping, and outcomes stay in application code\n- Stable completion: one `onEnd` callback for release and cancellation\n- Lifecycle ownership: `dispose()`, `disposed`, `disposalSignal`, optional owner `signal`, and `[Symbol.dispose]()`\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/): components that use pan recognition for carousel, drawer, toast, and list interactions.\n- [Dnd](/dnd/): builds touch sorting on `createDragGesture()` and adds files, previews, drop targets, keyboard reordering, and connected-list transactions.\n- [Keymap](/keymap/): keyboard interaction primitives for complementary input paths.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Gesture: API Reference'\ndescription: API reference for drag, pan, long-press, pinch, and wheel recognition.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------ | --------------------------------------------------- | -------------- | -------------------------------------------------------- |\n| `createDragGesture()` | Track unrestricted two-dimensional pointer movement | Sync | Does not provide DOM movement or drop semantics |\n| `createPanGesture()` | Track pointer movement projected onto one axis | Sync | Cross-axis intent ends a pending interaction |\n| `createLongPress()` | Recognize a primary pointer held in place | Sync | The click that follows a fired hold is swallowed |\n| `createPinchGesture()` | Track two-pointer scale and rotation | Sync | Ends when either pointer lifts |\n| `createWheelGesture()` | Track wheel input with pixel-normalized deltas | Sync | Never prevents scrolling unless `preventDefault` opts in |\n| `normalizeWheel()` | Convert wheel deltas to CSS pixels for any mode | Sync | Page-mode scaling uses the target's client box |\n| `DragGesture` / `PanGesture` / `LongPress` | Control recognition lifecycle | Sync | `dispose()` does not invoke `onEnd` |\n| `DragGestureOptions` | Configure free-drag recognition | Sync | `activationDistance` uses Euclidean distance |\n| `PanGestureOptions` | Configure axis-locked recognition | Sync | Completion thresholds belong in `onEnd` |\n| `LongPressOptions` | Configure hold recognition | Sync | `durationMs` and `slopPx` are validated at construction |\n| `PinchGestureOptions` | Configure pinch/rotate recognition | Sync | `activationDistance` is a span change, not pointer move |\n| `WheelOptions` | Configure wheel recognition | Sync | `preventDefault` accepts a per-event predicate |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------- | -------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/gesture` | Drag, pan, long-press, pinch, and wheel factories, handles, callback details, options, points, and end reasons |\n\n## Core Functions\n\n### `createDragGesture()`\n\n```ts\nfunction createDragGesture(target: Element, options?: DragGestureOptions): DragGesture;\n```\n\nTracks one primary pointer without restricting movement to an axis.\n\n| Parameter | Type | Description |\n| --------- | -------------------- | --------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `DragGestureOptions` | Activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `DragGesture` handle.\n\n**Example**\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst drag = createDragGesture(element, {\n onMove: ({ delta }) => {\n element.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n element.style.translate = '';\n },\n});\n```\n\n---\n\n### `createPanGesture()`\n\n```ts\nfunction createPanGesture(target: Element, options?: PanGestureOptions): PanGesture;\n```\n\nTracks one primary pointer after movement establishes intent on the configured axis.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | --------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `PanGestureOptions` | Axis, activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `PanGesture` handle.\n\n**Example**\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 48) dismiss();\n },\n});\n```\n\nBoth handles expose the same members:\n\n| Member | Type | Contract |\n| -------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------- |\n| `active` | `boolean` | `true` after activation and before release or cancellation |\n| `cancel()` | `() => boolean` | Clears pending recognition or ends active recognition with `reason: 'cancel'`; returns whether a session existed |\n| `disposalSignal` | `AbortSignal` | Aborts when the handle is disposed |\n| `dispose()` | `() => void` | Aborts `disposalSignal`, clears recognition, releases capture, and detaches listeners; idempotent |\n| `disposed` | `boolean` | `true` after disposal |\n| `[Symbol.dispose]()` | `() => void` | Calls `dispose()` |\n\n---\n\n### `createLongPress()`\n\n```ts\nfunction createLongPress(target: Element, options?: LongPressOptions): LongPress;\n```\n\nRecognizes a primary pointer held in place: `onLongPress` fires with the originating pointerdown once the hold outlasts `durationMs`.\n\n| Parameter | Type | Description |\n| --------- | ------------------ | ---------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission, document tracking, and click swallowing |\n| `options` | `LongPressOptions` | Hold time, slop distance, admission, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `LongPress` handle with the same members as the other gestures; `active` is `true` while a hold is pending.\n\n**Example**\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(list, {\n shouldStart: (event) => event.pointerType !== 'mouse',\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest('.tile');\n openDetail(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx`, a second touch, window blur, or a hidden document cancels a pending hold. The dynamic `disabled` predicate is checked again before the timer fires. The pointer-generated click following a fired hold is swallowed through a capture-phase listener on `target`; keyboard clicks (`detail: 0`) remain available. Bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers.\n\n---\n\n### `createPinchGesture()`\n\n```ts\nfunction createPinchGesture(target: Element, options?: PinchGestureOptions): PinchGesture;\n```\n\nTracks two pointers and reports scale and rotation relative to the positions where they went down.\n\n| Parameter | Type | Description |\n| --------- | --------------------- | --------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `PinchGestureOptions` | Activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `PinchGesture` handle with the same members as the other gestures.\n\n**Example**\n\n```ts\nimport { createPinchGesture } from '@vielzeug/gesture';\n\nconst pinch = createPinchGesture(stage, {\n onMove: ({ deltaScale, deltaRotation, deltaCentroid }) => {\n camera.zoomBy(1 + deltaScale);\n camera.rotateBy(deltaRotation);\n camera.panBy(deltaCentroid.x, deltaCentroid.y);\n },\n});\n```\n\nThe gesture activates once the span between the pointers changes by `activationDistance` pixels. It ends when either pointer lifts (`reason: 'release'`) or the session is cancelled; the remaining pointer never continues the gesture. A third pointer down is ignored.\n\n---\n\n### `createWheelGesture()`\n\n```ts\nfunction createWheelGesture(target: Element, options?: WheelOptions): WheelGesture;\n```\n\nReports wheel events with deltas normalized to CSS pixels. The handle is disposal-only: it has `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]()`, but no `active` or `cancel()` because wheel events are stateless.\n\n| Parameter | Type | Description |\n| --------- | -------------- | ------------------------------------------------------------ |\n| `target` | `Element` | Element the `wheel` listener is attached to |\n| `options` | `WheelOptions` | Prevention, admission, callback, and lifecycle configuration |\n\n**Returns:** A disposal-only `WheelGesture` handle.\n\n**Example**\n\n```ts\nimport { createWheelGesture } from '@vielzeug/gesture';\n\nconst wheel = createWheelGesture(stage, {\n preventDefault: true,\n onWheel: ({ deltaX, deltaY, pinch }) => {\n if (pinch) camera.zoomBy(Math.exp(-deltaY * 0.01));\n else camera.panBy(-deltaX, -deltaY);\n },\n});\n```\n\n`pinch` is `true` when `ctrlKey` is set, which is how browsers report trackpad pinch-zoom. Prevention defaults to `false`; the listener is non-passive so `preventDefault` works when opted in.\n\n---\n\n### `normalizeWheel()`\n\n```ts\nfunction normalizeWheel(event: WheelEvent, target: Element): { deltaX: number; deltaY: number };\n```\n\nConverts a wheel event's deltas to CSS pixels for any `deltaMode`: pixel mode passes through, line mode multiplies by 16, and page mode multiplies by the larger of the target's client width and height (falling back to the window box). Exported for consumers that already own their wheel listener.\n\n## Types\n\n### Drag types\n\n```ts\ntype DragEndReason = 'cancel' | 'release';\n\ntype DragPoint = Readonly<{\n x: number;\n y: number;\n}>;\n\ntype DragGestureDetail = Readonly<{\n current: DragPoint;\n delta: DragPoint;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: DragPoint;\n target: Element;\n velocity: DragPoint;\n}>;\n\ntype DragGestureEndDetail = DragGestureDetail &\n Readonly<{\n reason: DragEndReason;\n }>;\n\ntype DragGestureOptions = Readonly<{\n activationDistance?: number;\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: DragGestureEndDetail) => void;\n onMove?: (detail: DragGestureDetail) => void;\n onStart?: (detail: DragGestureDetail) => void;\n pointerCapture?: boolean;\n shouldActivate?: (detail: DragGestureDetail) => boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\n`start`, `current`, and `delta` use viewport `clientX` and `clientY` coordinates. Activation uses `Math.hypot(delta.x, delta.y)`.\n\n### Pan types\n\n```ts\ntype PanAxis = 'x' | 'y';\ntype PanEndReason = 'cancel' | 'release';\n\ntype PanGestureDetail = Readonly<{\n axis: PanAxis;\n current: number;\n distance: number;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: number;\n target: Element;\n velocity: number;\n}>;\n\ntype PanGestureEndDetail = PanGestureDetail &\n Readonly<{\n reason: PanEndReason;\n }>;\n\ntype PanGestureOptions = Readonly<{\n activationDistance?: number;\n axis?: PanAxis | (() => PanAxis);\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: PanGestureEndDetail) => void;\n onMove?: (detail: PanGestureDetail) => void;\n onStart?: (detail: PanGestureDetail) => void;\n pointerCapture?: boolean;\n shouldActivate?: (detail: PanGestureDetail) => boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\nPan details project `start`, `current`, and `distance` onto `axis`. The default axis is `'x'`.\n\nVelocity is signed CSS pixels per second over the trailing 90 ms. Samples include pointerdown, movement (including activation), and release. A window with fewer than two distinct sample times reports zero velocity; a pause longer than the window removes earlier movement.\n\n### Long-press types\n\n```ts\ntype LongPressDetail = Readonly<{\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n target: Element;\n}>;\n\ntype LongPressOptions = Readonly<{\n durationMs?: number;\n disabled?: boolean | (() => boolean | undefined);\n onLongPress?: (detail: LongPressDetail) => void;\n shouldStart?: (event: PointerEvent) => boolean;\n slopPx?: number;\n signal?: AbortSignal;\n}>;\n```\n\n`durationMs` defaults to `500` and `slopPx` to `8`. `event` is the pointerdown that started the hold, so `event.target` is the pressed element.\n\n### Pinch types\n\n```ts\ntype PinchEndReason = 'cancel' | 'release';\n\ntype PinchPoint = Readonly<{\n x: number;\n y: number;\n}>;\n\ntype PinchGestureDetail = Readonly<{\n centroid: PinchPoint;\n deltaCentroid: PinchPoint;\n deltaRotation: number;\n deltaScale: number;\n event: PointerEvent;\n rotation: number;\n scale: number;\n startCentroid: PinchPoint;\n target: Element;\n}>;\n\ntype PinchGestureEndDetail = PinchGestureDetail &\n Readonly<{\n reason: PinchEndReason;\n }>;\n\ntype PinchGestureOptions = Readonly<{\n activationDistance?: number;\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: PinchGestureEndDetail) => void;\n onMove?: (detail: PinchGestureDetail) => void;\n onStart?: (detail: PinchGestureDetail) => void;\n pointerCapture?: boolean;\n signal?: AbortSignal;\n}>;\n```\n\n`scale` is the current pointer span divided by the span when the pointers went down; `rotation` is the pointer-line angle since pointerdown in radians, positive clockwise, wrapped to `(-π, π]`. `deltaScale`, `deltaRotation`, and `deltaCentroid` are the change since the previous event (the start event's baseline for the first callback), which is what incremental transforms consume. Centroid coordinates are viewport `clientX`/`clientY` space. `activationDistance` is a span change in pixels and defaults to `6`. Pinch has no `shouldStart`; the first two pointers down after creation are tracked and later pointers are ignored.\n\n### Wheel types\n\n```ts\ntype WheelDetail = Readonly<{\n deltaX: number;\n deltaY: number;\n event: WheelEvent;\n pinch: boolean;\n target: Element;\n}>;\n\ntype WheelOptions = Readonly<{\n disabled?: boolean | (() => boolean | undefined);\n onWheel?: (detail: WheelDetail) => void;\n preventDefault?: boolean | ((event: WheelEvent) => boolean);\n signal?: AbortSignal;\n}>;\n\ntype WheelGesture = Readonly<{\n [Symbol.dispose]: () => void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n}>;\n```\n\n`deltaX`/`deltaY` are normalized to CSS pixels (see `normalizeWheel()`); positive moves content right/down. `pinch` mirrors `ctrlKey`.\n\n### Handle types\n\n```ts\ntype DragGesture = {\n readonly active: boolean;\n [Symbol.dispose](): void;\n cancel(): boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n};\n\ntype PanGesture = DragGesture;\n\ntype PinchGesture = DragGesture;\n```\n\n### Shared option behavior\n\n| Option | Default | Contract |\n| -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |\n| `activationDistance` | `6` | Non-negative finite CSS pixels; drag uses Euclidean distance, pan waits for dominant-axis intent |\n| `axis` | `'x'` | Pan only; fixed value or getter sampled when each interaction starts |\n| `disabled` | `false` | Fixed value or getter; blocks starts and cancels active recognition on the next matching pointer event |\n| `pointerCapture` | `true` | Best-effort capture after activation; document tracking continues when capture is disabled or fails |\n| `shouldStart` | N/A | Admission predicate evaluated for the primary pointer before tracking starts |\n| `shouldActivate` | N/A | Drag/pan predicate evaluated once after distance/axis recognition and before capture or callbacks; false rejects the session |\n| `signal` | N/A | Disposes the handle when the external owner aborts |\n| `onStart` | N/A | Runs once on the activating movement |\n| `onMove` | N/A | Runs on the activating movement and each later matching movement |\n| `onEnd` | N/A | Runs once for active release or cancellation; pending interactions end without callbacks |\n\nOptions and callback details are readonly. Fixed callbacks and capture policy are snapshotted at construction. Function-valued `axis` and `disabled` options remain dynamic.\n\nGesture tracks accepted movement with capture-phase listeners on the target's current owner document. Window blur, hidden-document transition, `pointercancel`, pointer capture loss on the gesture target, and a second touch anywhere in that document cancel recognition. A `lostpointercapture` event bubbling from a descendant does not cancel the target's gesture. Exact diagonal ties remain pending until one axis dominates; cross-axis dominance rejects the pending pan. Gesture does not arbitrate ownership between recognizers on the same axis.\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| -------------------- | --------------------------------------------- | --------------------------------------------------- |\n| `GestureError` | Base class for every gesture-originated error | `instanceof GestureError` catches any gesture error |\n| `GestureConfigError` | Invalid option value | Extends `GestureError` |\n\n- Invalid `activationDistance` values throw `GestureConfigError` during construction.\n- Invalid fixed `axis` values throw `GestureConfigError` during construction.\n- Invalid values returned by a dynamic `axis` getter throw `GestureConfigError` when a pointer interaction starts.\n",
|
|
6
|
+
"usage": "---\ntitle: 'Gesture: Usage Guide'\ndescription: Track unrestricted pointer dragging and axis-locked pans with application-owned rendering and completion.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate one handle for the element that owns the interaction. This example creates its surface, applies the required touch policy, and disposes the handle when the page unloads.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst row = document.body.appendChild(document.createElement('div'));\nrow.textContent = 'Swipe to archive';\nrow.style.touchAction = 'pan-y';\n\nconst pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) {\n pan.dispose();\n row.remove();\n }\n },\n});\n\nwindow.addEventListener('pagehide', () => pan.dispose(), { once: true });\n```\n\n## Track Two-Dimensional Dragging\n\nUse `createDragGesture()` when movement must remain unrestricted in both dimensions:\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst card = document.querySelector<HTMLElement>('[data-draggable]');\nif (!card) throw new Error('Missing [data-draggable] element');\n\nconst drag = createDragGesture(card, {\n activationDistance: 6,\n onMove: ({ delta }) => {\n card.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n card.style.translate = '';\n },\n});\n\nwindow.addEventListener('pagehide', () => drag.dispose(), { once: true });\n```\n\n`start`, `current`, and `delta` are readonly `{ x, y }` points. Set `touch-action: none` when the surface owns movement in both dimensions. Drag recognition does not provide previews, drop targets, DOM movement, or `DataTransfer`; use Dnd for those semantics.\n\n## Recognize Long Presses\n\nUse `createLongPress()` for hold interactions: the touch counterpart of a keyboard preview key. `onLongPress` receives the originating pointerdown once the hold outlasts `durationMs`:\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(grid, {\n durationMs: 500,\n shouldStart: (event) => event.pointerType !== 'mouse' && (event.target as HTMLElement).closest('.tile') !== null,\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest<HTMLElement>('.tile');\n openPreview(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx` cancels back to a normal press, so scrolling never triggers the hold. The click that follows a fired hold is swallowed through a capture-phase listener on `target`: bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers, and gate `shouldStart` to the elements the hold belongs to.\n\n## Recognize Pinch and Rotate\n\nUse `createPinchGesture()` for two-pointer scale and rotation. `scale` and `rotation` are relative to the positions where the two pointers went down, so a transform applied from `onStart` onward composes against the gesture's own baseline:\n\n```ts\nimport { createPinchGesture } from '@vielzeug/gesture';\n\nconst stage = document.querySelector<HTMLElement>('[data-stage]');\nif (!stage) throw new Error('Missing [data-stage] element');\n\nconst card = stage.querySelector<HTMLElement>('[data-card]');\nif (!card) throw new Error('Missing [data-card] element');\n\nlet x = 0;\nlet y = 0;\ncreatePinchGesture(stage, {\n onMove: ({ scale, rotation, deltaCentroid }) => {\n x += deltaCentroid.x;\n y += deltaCentroid.y;\n card.style.transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotation}rad)`;\n },\n});\n```\n\nThe gesture activates once the pointer span changes by `activationDistance` pixels (default 6), which keeps two-finger taps from jittering the canvas. `deltaScale`, `deltaRotation`, and `deltaCentroid` carry the movement since the previous event, which is what incremental camera transforms consume. The session ends when either pointer lifts; the remaining pointer never continues the gesture. Set `touch-action: none` on the target.\n\nCentroid coordinates are client-space, like every other pointer coordinate in this package. When the target is offset from the viewport origin, convert to target-local coordinates with `getBoundingClientRect()` before applying them to content.\n\nPair pinch with a single-pointer drag or pan by cancelling the single-pointer gesture from pinch's `onStart`; the drag handle's `cancel()` ends its active session without firing `onEnd`, so dragging and pinching never fight over the same surface.\n\n## Recognize Wheel and Trackpad Zoom\n\nUse `createWheelGesture()` for scroll-wheel and trackpad input. Deltas are normalized to CSS pixels regardless of the browser's `deltaMode` (pixels, lines, or pages), and `pinch` marks the ctrl-key wheel events macOS sends for trackpad pinch-zoom:\n\n```ts\nimport { createWheelGesture } from '@vielzeug/gesture';\n\nconst wheel = createWheelGesture(stage, {\n preventDefault: (event) => event.ctrlKey || stage.contains(event.target as Node),\n onWheel: ({ deltaX, deltaY, pinch }) => {\n if (pinch) {\n camera.zoomBy(Math.exp(-deltaY * 0.01));\n } else {\n camera.panBy(-deltaX, -deltaY);\n }\n },\n});\n```\n\nThe recognizer never prevents silently: `preventDefault` defaults to `false`, and the listener is registered non-passive so prevention works when you opt in. `normalizeWheel()` is exported for code that already listens for wheel events and only needs the normalization.\n\n## Completion Rules\n\nGesture reports movement and terminal state but does not decide what constitutes a swipe. Apply thresholds and allowed directions in `onEnd`.\n\n```ts\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && distance <= -80) {\n openNext();\n } else {\n resetPanel();\n }\n },\n});\n```\n\n## Direction Recognition\n\nThe gesture remains pending during small movement and exact diagonal ties. It activates only after movement strictly favors the configured axis. Cross-axis movement ends the pending interaction without invoking callbacks.\n\nThe default `activationDistance` is 6 pixels. Tune direction-recognition slop for touch density or component-specific needs:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n activationDistance: 12,\n onMove,\n onEnd,\n});\n```\n\nSet `activationDistance: 0` when the first pointer move with non-zero displacement should activate immediately. Zero-motion events remain pending.\n\nUse the corresponding `touch-action` value so the browser retains native scrolling on the other axis.\n\n```css\n.swipe-row {\n touch-action: pan-y pinch-zoom;\n}\n```\n\n```ts\nconst pan = createPanGesture(row, { axis: 'x', onMove });\n```\n\nUse `shouldStart` to exclude controls at pointerdown. Use `shouldActivate` for direction or boundary checks that require movement; rejection happens before capture or callbacks.\n\n```ts\nconst pan = createPanGesture(panel, {\n axis: 'y',\n shouldActivate: ({ distance }) => distance > 0 && scroller.scrollTop <= 0,\n onMove: renderPull,\n onEnd: settlePull,\n});\n```\n\nGesture cancels pending and active touch recognition when a second finger touches the owner document. Reset presentation on `reason: 'cancel'`; never commit an action from cancellation. Native scroll and pinch behavior still depends on the surface's CSS and event handling. Once native scrolling owns a touch sequence, start a fresh swipe at the boundary rather than attempting a mid-scroll handoff.\n\n## Pointer Capture\n\nPointer capture is enabled by default. After axis intent is accepted, Gesture attempts to capture the pointer while continuing to track movement through document-level listeners. Capture failure (for example after target detachment or pointer termination) falls back to document tracking without stranding the session.\n\nDisable capture when nested or newly revealed controls must retain native pointer-up and click targeting:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n pointerCapture: false,\n onMove: renderReveal,\n onEnd: settleReveal,\n});\n```\n\nDocument-level tracking still keeps the pan active outside the target. Disabling capture changes event targeting, not gesture tracking.\n\n## Interactive Descendants\n\nUse `shouldStart` when buttons, links, or form controls inside the surface must not start a pan.\n\n```ts\nconst pan = createPanGesture(notification, {\n axis: 'x',\n pointerCapture: false,\n shouldStart: (event) =>\n !event.composedPath().some((node) => node instanceof Element && node.matches('button, a, input, select, textarea')),\n onMove,\n onEnd,\n});\n```\n\n`shouldStart` protects controls under the initial pointer. `pointerCapture: false` additionally protects controls that appear beneath the pointer during a reveal interaction.\n\n## Disabled State\n\nA boolean disables the recognizer permanently. A getter supports state that changes while the handle is alive.\n\n```ts\nconst pan = createPanGesture(row, {\n disabled: () => isLocked,\n onEnd: ({ reason }) => {\n if (reason === 'cancel') resetRow();\n },\n});\n```\n\nWhen the getter becomes `true`, the next pointer event cancels an active pan. Window blur or a hidden owner document also cancels active tracking so a lost release cannot block later gestures.\n\nGesture snapshots fixed callbacks and capture policy at construction. Use the `axis` and `disabled` functions for behavior that must remain dynamic instead of mutating the options object.\n\n## Lifecycle\n\nDispose the target-bound handle when its owning UI scope unmounts.\n\n```ts\nconst element = document.querySelector<HTMLElement>('[data-pan]');\nif (!element) throw new Error('Missing [data-pan] element');\n\nconst owner = new AbortController();\nconst request = new AbortController();\nconst pan = createPanGesture(element, {\n axis: 'x',\n signal: owner.signal,\n});\n\nconst childSignal = AbortSignal.any([pan.disposalSignal, request.signal]);\nwindow.addEventListener('pagehide', () => owner.abort(), { once: true });\n```\n\nPass `{ signal }` to dispose with an existing owner signal. `disposalSignal` always aborts when Gesture finishes teardown, so child work can compose with the handle regardless of how disposal starts.\n\nUse `cancel()` to stop a pending or active interaction without disposing the handle. An active interaction emits `onEnd` with `reason: 'cancel'`. Call `cancel()` before `dispose()` when a connected surface needs its `onEnd` reset path; disposal itself does not invoke callbacks.\n\n## Framework Integration\n\nCreate the handle after the target element exists and dispose it on unmount.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\nimport { createPanGesture } from '@vielzeug/gesture';\n\nfunction SwipeRow({ onDismiss }: { onDismiss: () => void }) {\n const rowRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const row = rowRef.current;\n if (!row) return;\n\n const pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) onDismiss();\n },\n });\n\n return () => pan.dispose();\n }, [onDismiss]);\n\n return <div ref={rowRef}>Swipe me</div>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, ref } from 'vue';\nimport { createPanGesture, type PanGesture } from '@vielzeug/gesture';\n\nconst emit = defineEmits<{ dismiss: [] }>();\nconst rowEl = ref<HTMLDivElement | null>(null);\nlet pan: PanGesture | undefined;\n\nonMounted(() => {\n const row = rowEl.value;\n if (!row) return;\n\n pan = createPanGesture(row, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) emit('dismiss');\n },\n });\n});\n\nonUnmounted(() => pan?.dispose());\n</script>\n\n<template>\n <div ref=\"rowEl\">Swipe me</div>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createPanGesture } from '@vielzeug/gesture';\n\n let { ondismiss = () => {} }: { ondismiss: () => void } = $props();\n let rowEl: HTMLDivElement;\n\n onMount(() => {\n const pan = createPanGesture(rowEl, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) ondismiss();\n },\n });\n\n return () => pan.dispose();\n });\n</script>\n\n<div bind:this={rowEl}>Swipe me</div>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### Gesture + Refine\n\nRefine uses Gesture internally for carousel, drawer, toast, and list-item pointer interactions. Custom surfaces can use the same pan lifecycle while keeping visual state local.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onMove: ({ distance }) => {\n panel.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n panel.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 80) revealActions();\n },\n});\n```\n\n### Gesture + Dnd\n\nGesture owns pointer recognition: unrestricted two-dimensional drag and one-axis pan. Dnd builds touch sorting on `createDragGesture()`, then owns `DataTransfer`, previews, hit-testing, file drop zones, keyboard sorting, DOM reordering, and connected-list transactions. Use Dnd when an item is picked up and dropped; use Gesture directly when application code owns rendering and completion.\n\n## Best Practices\n\n- **Set** `touch-action` for the axis the browser should continue scrolling.\n- **Use** `shouldStart` to exclude nested interactive controls.\n- **Disable** pointer capture when nested or newly revealed controls must keep native release targeting.\n- **Apply** completion thresholds and direction rules in `onEnd`; use `activationDistance` only for recognition slop.\n- **Treat** `reason: 'cancel'` as a reset path, never a commit path. Pointer capture loss on the gesture target cancels; capture loss bubbling from a descendant does not.\n- **Keep** `onMove` rendering lightweight.\n- **Dispose** the handle when its target leaves the UI.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Gesture: Examples'\ndescription: Worked examples for @vielzeug/gesture.\n---\n\n## Examples\n\n- [Carousel Pan Navigation](./examples/carousel-swipe-navigation.md)\n- [Swipe-to-Dismiss Notifications](./examples/swipe-dismiss-notifications.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
@@ -16,6 +16,16 @@
|
|
|
16
16
|
"id": "pan-basic",
|
|
17
17
|
"code": "import { createPanGesture } from '@vielzeug/gesture'\n\nconst surface = document.createElement('div')\nsurface.textContent = 'Drag horizontally'\nsurface.style.cssText = 'width:240px;padding:32px;text-align:center;background:#e0e7ff;border-radius:12px;touch-action:pan-y;user-select:none;'\ndocument.body.appendChild(surface)\n\nconst output = document.createElement('pre')\ndocument.body.appendChild(output)\n\nconst pan = createPanGesture(surface, {\n axis: 'x',\n onMove: ({ distance }) => {\n surface.style.transform = `translateX(${distance}px)`\n output.textContent = `distance: ${Math.round(distance)}px`\n },\n onEnd: ({ distance, reason }) => {\n surface.style.transform = ''\n output.textContent = reason === 'release' && Math.abs(distance) >= 48\n ? `swipe: ${distance < 0 ? 'left' : 'right'}`\n : `ended: ${reason}`\n },\n})\n\nconsole.log('Pan gesture ready:', pan.disposed === false)",
|
|
18
18
|
"name": "createPanGesture - Basic"
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"id": "pinch-basic",
|
|
22
|
+
"code": "import { createPinchGesture } from '@vielzeug/gesture'\n\nconst stage = document.createElement('div')\nstage.style.cssText = 'width:100%;height:280px;display:grid;place-items:center;background:#f1f5f9;border-radius:12px;touch-action:none;user-select:none;'\nconst card = document.createElement('div')\ncard.textContent = 'Pinch me'\ncard.style.cssText = 'padding:24px 32px;background:#6366f1;color:white;border-radius:12px;font-weight:600;'\nstage.appendChild(card)\ndocument.body.appendChild(stage)\n\nconst output = document.createElement('pre')\ndocument.body.appendChild(output)\n\nlet x = 0\nlet y = 0\ncreatePinchGesture(stage, {\n onMove: ({ scale, rotation, deltaCentroid }) => {\n x += deltaCentroid.x\n y += deltaCentroid.y\n card.style.transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotation}rad)`\n output.textContent = `scale: ${scale.toFixed(2)} rotation: ${(rotation * 57.3).toFixed(0)}°`\n },\n onEnd: ({ reason }) => {\n output.textContent = `ended: ${reason}`\n },\n})\n\nconsole.log('Pinch gesture ready')",
|
|
23
|
+
"name": "createPinchGesture - Basic"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"id": "wheel-basic",
|
|
27
|
+
"code": "import { createWheelGesture } from '@vielzeug/gesture'\n\nconst viewport = document.createElement('div')\nviewport.style.cssText = 'width:100%;height:220px;overflow:hidden;background:#f1f5f9;border-radius:12px;touch-action:none;'\nconst content = document.createElement('div')\ncontent.style.cssText = 'width:200%;height:400%;display:grid;place-items:center;font-weight:600;color:#475569;'\ncontent.textContent = 'Scroll inside'\nviewport.appendChild(content)\ndocument.body.appendChild(viewport)\n\nconst output = document.createElement('pre')\ndocument.body.appendChild(output)\n\nlet x = 0\nlet y = 0\ncreateWheelGesture(viewport, {\n preventDefault: true,\n onWheel: ({ deltaX, deltaY, pinch }) => {\n if (pinch) {\n output.textContent = `pinch-zoom wheel: ${deltaY.toFixed(1)}px`\n return\n }\n x = Math.max(-400, Math.min(0, x - deltaX))\n y = Math.max(-800, Math.min(0, y - deltaY))\n content.style.transform = `translate(${x}px, ${y}px)`\n output.textContent = `offset: ${Math.round(x)}px, ${Math.round(y)}px`\n },\n})\n\nconsole.log('Wheel gesture ready')",
|
|
28
|
+
"name": "createWheelGesture - Basic"
|
|
19
29
|
}
|
|
20
30
|
],
|
|
21
31
|
"typeSignatures": {
|
|
@@ -38,6 +48,18 @@
|
|
|
38
48
|
"PanGesture": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
39
49
|
"PanGestureDetail": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
40
50
|
"PanGestureEndDetail": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
41
|
-
"PanGestureOptions": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';"
|
|
51
|
+
"PanGestureOptions": "export {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';",
|
|
52
|
+
"createPinchGesture": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
53
|
+
"PinchEndReason": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
54
|
+
"PinchGesture": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
55
|
+
"PinchGestureDetail": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
56
|
+
"PinchGestureEndDetail": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
57
|
+
"PinchGestureOptions": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
58
|
+
"PinchPoint": "export {\n createPinchGesture,\n type PinchEndReason,\n type PinchGesture,\n type PinchGestureDetail,\n type PinchGestureEndDetail,\n type PinchGestureOptions,\n type PinchPoint,\n} from './pinch-gesture.js';",
|
|
59
|
+
"createWheelGesture": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';",
|
|
60
|
+
"normalizeWheel": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';",
|
|
61
|
+
"WheelDetail": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';",
|
|
62
|
+
"WheelGesture": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';",
|
|
63
|
+
"WheelOptions": "export {\n createWheelGesture,\n normalizeWheel,\n type WheelDetail,\n type WheelGesture,\n type WheelOptions,\n} from './wheel-gesture.js';"
|
|
42
64
|
}
|
|
43
65
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiSource": "/**\n * @vielzeug/ink: freehand stroke smoothing, width profiling, and SVG path output.\n *\n * Pure, deterministic geometry functions. No DOM, no timers, no long-lived handles.\n */\nexport { InkConfigError, InkError } from './errors.js';\nexport { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';\nexport { simplifyStroke } from './simplify.js';\nexport { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';\nexport { type StabilizeStrokeOptions, stabilizeStroke } from './stabilize.js';\nexport { type PolylineToSvgPathOptions, polylineToSvgPath } from './svg.js';\nexport type { Point, StrokePoint } from './types.js';\nexport { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';\n",
|
|
3
|
+
"docs": {
|
|
4
|
+
"index": "---\ntitle: 'Ink: Freehand Stroke Geometry'\ndescription: Deterministic causal stroke stabilization, Catmull-Rom smoothing, speed and pressure width profiling, outline polygons, RDP simplification, and SVG path output.\npackage: ink\ncategory: data\nkeywords:\n [\n freehand,\n stroke,\n smoothing,\n catmull-rom,\n streamline,\n simplify,\n ramer-douglas-peucker,\n svg,\n path,\n variable-width,\n pressure,\n drawing,\n canvas,\n ]\nexports: [stabilizeStroke, smoothStroke, strokeWidths, strokeOutline, simplifyStroke, polylineToSvgPath]\nrelated: [gesture, prism]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"ink\" />\n\n## Why Ink?\n\nRaw pointer samples are jagged, and a good ink line needs stabilization, speed- and pressure-derived widths, a closed outline polygon, and a compact SVG path on top of them. Ink computes all four as pure, deterministic functions: identical samples always produce identical geometry, so strokes are replayable, testable, and server-renderable.\n\n```ts\n// Before\n// Hand-rolled filter math, per-point width heuristics, and manual path assembly\n// in every drawing surface, each with its own jitter and nondeterminism.\n\n// After\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';\n\nconst stabilized = stabilizeStroke(samples);\nconst d = polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 4 })), {\n close: true,\n});\n```\n\n| Feature | Ink | Ad-hoc smoothing | Sketch libraries |\n| ------------------------------ | -------------------------------------------- | ---------------- | -------------------- |\n| Bundle size | <PackageInfo package=\"ink\" type=\"size\" /> | n/a | Typically 10–50 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a | Varies |\n| Deterministic pure functions | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Rarely | Often randomized |\n| Variable-width outline polygon | Built in | Manual | Rare |\n| Runs without a DOM | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies | Usually browser-only |\n\n<div class=\"decision-callout\">\n\n**Use Ink when** a drawing or annotation surface needs reusable stroke geometry: stabilization, smoothing, width profiling, outlines, decimation, or SVG serialization without owning the math.\n\n**Consider direct polyline rendering when** the input is already clean (vector tools with their own smoothing) and a plain segment path is visually sufficient.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/ink\n```\n\n```sh [npm]\nnpm install @vielzeug/ink\n```\n\n```sh [yarn]\nyarn add @vielzeug/ink\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink';\n\n// Raw samples from a pointer stream (see @vielzeug/gesture for capture),\n// timestamped with PointerEvent.timeStamp.\nconst samples = [\n { time: 0, x: 0, y: 0 },\n { time: 16, x: 12, y: 3 },\n { time: 32, x: 25, y: -2 },\n { time: 48, x: 40, y: 1 },\n];\n\nconst stabilized = stabilizeStroke(samples); // causal jitter removal\nconst widths = strokeWidths(stabilized, { width: 6 }); // speed-derived widths\nconst ring = strokeOutline(stabilized, widths); // closed variable-width polygon\nconst d = polylineToSvgPath(ring, { close: true }); // SVG `d` string\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `stabilizeStroke()`: causal Streamline-style averaging for live drawing; the stroke ends exactly where the pen lifted\n- `smoothStroke()`: deterministic Catmull-Rom resampling after capture\n- `strokeWidths()`: real-speed-derived widths (`distance / Δtime`) with pressure modulation and clamped scaling\n- `strokeOutline()`: closed variable-width polygon offset along local normals with capped ends; constant width with a single number\n- `simplifyStroke()`: iterative Ramer-Douglas-Peucker decimation preserving endpoints\n- `polylineToSvgPath()`: SVG `d` strings for open strokes and closed outline rings, with configurable precision\n- `InkError` / `InkConfigError`: typed configuration errors thrown at call time\n- Determinism: identical input always yields identical output; no randomness, no clocks\n- Zero runtime dependencies and no DOM requirement: works in Node, Workers, and SSR\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Gesture](/gesture/): captures the pointer samples Ink consumes; pan handles produce the raw point streams.\n- [Prism](/prism/): SVG rendering primitives; Ink's `d` strings drop straight into its path elements.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Ink: API Reference'\ndescription: 'API reference for @vielzeug/ink: causal stabilization, Catmull-Rom smoothing, speed-based widths, outline polygons, simplification, and SVG path output.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------------- | -------------------------------------------------------- | --------- | ----------------------------------------------------------------- |\n| `stabilizeStroke()` | Causal jitter removal while drawing | Sync | One output point per input; last point snaps to the pen-up spot |\n| `smoothStroke()` | Catmull-Rom resampling after capture | Sync | Adds points: `steps` samples per input segment |\n| `strokeWidths()` | Per-point widths from real speed (`time`) and pressure | Sync | Velocity is off for the whole stroke if any point lacks `time` |\n| `strokeOutline()` | Closed variable-width polygon around a stroke | Sync | Array `widths` must match point count; a number is constant |\n| `simplifyStroke()` | Ramer-Douglas-Peucker decimation | Sync | Returns input references, not copies |\n| `polylineToSvgPath()` | SVG `d` string for polylines and closed outline rings | Sync | Requires at least one point; pass `close: true` for rings |\n| `InkError` | Base class for all ink errors | Sync | Narrow with `instanceof InkError` |\n| `InkConfigError` | Invalid options or point counts | Sync | Thrown at call time, not construction |\n| `Point` / `StrokePoint` | Structural point shapes shared across the canvas toolkit | Sync | `pressure` and `time` are optional; `time` unlocks width velocity |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------- | ---------------------------------------------------------------------------------------------------- |\n| `@vielzeug/ink` | Stabilization, smoothing, width profiling, outline, simplification, SVG serialization, types, errors |\n\n---\n\n## Core Functions\n\n### `stabilizeStroke()`\n\n```ts\nfunction stabilizeStroke(points: readonly StrokePoint[], options?: StabilizeStrokeOptions): StrokePoint[];\n```\n\nRemoves hand jitter _while the stroke is being drawn_: a causal exponential average toward each incoming sample with a jitter dead zone, so straight lines stay crisp. It never looks ahead.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | ----------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Input samples |\n| `options` | `StabilizeStrokeOptions` | `strength` in `[0, 1]`; `0` is the raw input, default `0.5` |\n\n**Returns:** New `StrokePoint[]` with exactly the input's length. The last point is the last input point exactly — the stroke ends where the pen lifted. Inside the dead zone the position repeats but the incoming sample's `pressure` and `time` carry through.\n\n**Example**\n\n```ts\nimport { stabilizeStroke } from '@vielzeug/ink';\n\nconst live = stabilizeStroke(samples, { strength: 0.6 });\n```\n\nThrows `InkConfigError` for a `strength` outside `[0, 1]`.\n\n---\n\n### `smoothStroke()`\n\n```ts\nfunction smoothStroke(points: readonly StrokePoint[], options?: SmoothStrokeOptions): StrokePoint[];\n```\n\nResamples a stroke through a uniform Catmull-Rom spline: `steps` samples per input segment, with the first and last input points preserved exactly. `pressure` and `time` are interpolated linearly, so widths computed from the output match widths computed from the input. For jitter removal while drawing, use `stabilizeStroke()` instead — this function adds points and looks ahead.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | ------------------------------------------------------------------------------ |\n| `points` | `readonly StrokePoint[]` | Input samples; fewer than three are returned as copies |\n| `options` | `SmoothStrokeOptions` | `tension` in `[0, 1]` (default `1`), `steps` integer `[2, 1000]` (default `8`) |\n\n**Returns:** New `StrokePoint[]` with `steps` samples per input segment plus the exact final point.\n\n**Example**\n\n```ts\nimport { smoothStroke } from '@vielzeug/ink';\n\nconst resampled = smoothStroke(samples, { tension: 1, steps: 8 });\n```\n\nThrows `InkConfigError` for a `tension` outside `[0, 1]` or a `steps` value outside `[2, 1000]` or non-integer.\n\n---\n\n### `strokeWidths()`\n\n```ts\nfunction strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[];\n```\n\nReturns one width per point from real pen speed and optional pressure. Speed is `distance / Δtime` between consecutive points, which stays correct after any stabilization, smoothing, or simplification. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale. When any point lacks `time` — or a Δtime is zero — velocity modulation is disabled for the whole stroke (width becomes `width × pressure`) instead of guessing speed from sample spacing.\n\n| Parameter | Type | Description |\n| --------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |\n| `options` | `StrokeWidthOptions` | `width` (required, > 0), `thinning` in `[0, 1]` (default `0.5`), `referenceSpeed` in px/ms (default `0.5`), `taper`, `simulatePressure` |\n\n**Returns:** `number[]` with the same length as `points`. The first point uses the forward segment; degenerate (zero-length) segments keep the previous scale so stationary samples do not spike.\n\nPressure multiplies the result through a curve where `0.5` (the neutral value a mouse reports) maps to exactly `1`: the range is `[0.5, 1.25]`, so a neutral-pressure stroke is as wide as one without pressure data.\n\n`taper` fades the width in over `taper.start` and out over `taper.end` units of arc length (same units as `width`): a smoothstep ramp from a `0.15` floor at the tip to full width at the taper length, multiplied on top of the speed/pressure profile. `simulatePressure` (default `false`) synthesizes pressure for points that have none on a timed stroke: the width multiplier ramps from `0.5` at each tip to neutral across the first and last 15% of arc length, so mouse strokes thin at the ends. Points that carry real `pressure` always use it, and untimed strokes ignore the option.\n\n**Example**\n\n```ts\nimport { strokeWidths } from '@vielzeug/ink';\n\nconst widths = strokeWidths(samples, { width: 6, thinning: 0.5 });\nconst tapered = strokeWidths(samples, { width: 6, taper: { start: 30, end: 30 }, simulatePressure: true });\n```\n\nThrows `InkConfigError` for a non-positive `width` or `referenceSpeed`, a `thinning` outside `[0, 1]`, a negative or non-finite `taper` length, or an empty `points` array.\n\n---\n\n### `strokeOutline()`\n\n```ts\nfunction strokeOutline(\n points: readonly StrokePoint[],\n widths: number | readonly number[],\n options?: StrokeOutlineOptions,\n): Point[];\n```\n\nReturns a closed polygon approximating the variable-width stroke: start cap, left offsets forward, end cap, right offsets backward, with no repeated final vertex. Pass a constant `widths` number for a uniform stroke.\n\n| Parameter | Type | Description |\n| --------- | ----------------------------- | --------------------------------------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples (at least one) |\n| `widths` | `number \\| readonly number[]` | Constant width, or per-point widths from `strokeWidths()` |\n| `options` | `StrokeOutlineOptions` | `cap` (default `'round'`), `join` (default `'round'`), `miterLimit` (default `4`) |\n\n`cap` selects the end treatment: `'round'` half-circle caps, `'butt'` no cap points, `'square'` a half-width tangent extension at each end. `join` handles turns sharper than 90°, where naive offsetting makes the inner side cross itself: `'round'` keeps the plain offset samples (current default output), `'bevel'` replaces each sharp joint with the two adjacent segment-offset points, dropping the crossing spike, and `'miter'` extends to the offset-line intersection while the miter length stays within `miterLimit` × half width, falling back to bevel beyond it.\n\n**Returns:** `Point[]` ring, deterministic for deterministic input.\n\n**Example**\n\n```ts\nimport { strokeOutline } from '@vielzeug/ink';\n\nconst ring = strokeOutline(samples, widths);\nconst uniform = strokeOutline(samples, 4);\nconst marker = strokeOutline(samples, 4, { cap: 'square', join: 'miter', miterLimit: 6 });\n```\n\nThrows `InkConfigError` when an array `widths` length differs from `points` length or any width is not a positive finite number, when `cap` or `join` is not a known variant, or when `miterLimit` is not a positive finite number.\n\n---\n\n### `simplifyStroke()`\n\n```ts\nfunction simplifyStroke(points: readonly StrokePoint[], tolerance: number): StrokePoint[];\n```\n\nReturns a Ramer-Douglas-Peucker decimated subsequence of the input; first and last points are always kept.\n\n| Parameter | Type | Description |\n| ----------- | ------------------------ | -------------------------------------------------- |\n| `points` | `readonly StrokePoint[]` | Stroke samples |\n| `tolerance` | `number` | Maximum perpendicular deviation to discard, `>= 0` |\n\n**Returns:** `StrokePoint[]` containing the same object references as the input (metadata such as `pressure` and `time` survives).\n\n**Example**\n\n```ts\nimport { simplifyStroke } from '@vielzeug/ink';\n\nconst decimated = simplifyStroke(samples, 0.5);\n```\n\nThrows `InkConfigError` for a negative or non-finite `tolerance`.\n\n---\n\n### `polylineToSvgPath()`\n\n```ts\nfunction polylineToSvgPath(points: readonly Point[], options?: PolylineToSvgPathOptions): string;\n```\n\nReturns an SVG path `d` string: `M x y` plus one `L x y` per remaining point. Works for open strokes and for the closed ring from `strokeOutline()` — pass `close: true` for rings.\n\n| Parameter | Type | Description |\n| --------- | -------------------------- | --------------------------------------------------------------------------- |\n| `points` | `readonly Point[]` | Stroke samples or ring vertices (at least one) |\n| `options` | `PolylineToSvgPathOptions` | `close` appends `Z`; `precision` rounds coordinates (`0`–`12`, default `2`) |\n\n**Returns:** `string` suitable for a `<path d=\"...\">` attribute.\n\n**Example**\n\n```ts\nimport { polylineToSvgPath } from '@vielzeug/ink';\n\nconst d = polylineToSvgPath(samples, { precision: 1 }); // \"M 0 0 L 12 3 L 25 -2\"\nconst outline = polylineToSvgPath(ring, { close: true }); // \"M ... L ... Z\"\n```\n\nThrows `InkConfigError` when `points` is empty or `precision` is out of range.\n\n## Types\n\n```ts\ntype Point = Readonly<{ x: number; y: number }>;\n```\n\nA two-dimensional point. Structural so canvas-toolkit packages can share it without importing each other.\n\n```ts\ntype StrokePoint = Readonly<{\n x: number;\n y: number;\n pressure?: number; // normalized [0, 1]; 0.5 is neutral\n time?: number; // milliseconds, e.g. PointerEvent.timeStamp; enables width velocity\n}>;\n```\n\nA sampled stroke point. `time` values only need to share a clock; any monotonic source works.\n\n```ts\ninterface StabilizeStrokeOptions {\n strength?: number; // [0, 1], default 0.5\n}\n```\n\n```ts\ninterface SmoothStrokeOptions {\n tension?: number; // [0, 1], default 1\n steps?: number; // [2, 1000] integer, default 8\n}\n```\n\n```ts\ninterface StrokeWidthOptions {\n width: number; // required, > 0\n thinning?: number; // [0, 1], default 0.5\n referenceSpeed?: number; // > 0, default 0.5 (px per ms)\n taper?: StrokeTaperOptions; // arc-length end fade, default none\n simulatePressure?: boolean; // default false; timed strokes only\n}\n```\n\n```ts\ninterface StrokeTaperOptions {\n start?: number; // fade-in length along arc length, >= 0, default 0\n end?: number; // fade-out length along arc length, >= 0, default 0\n}\n```\n\n```ts\ntype StrokeCap = 'round' | 'butt' | 'square';\n```\n\n```ts\ntype StrokeJoin = 'round' | 'bevel' | 'miter';\n```\n\n```ts\ninterface StrokeOutlineOptions {\n cap?: StrokeCap; // default 'round'\n join?: StrokeJoin; // default 'round'\n miterLimit?: number; // > 0, default 4 (miter length / half width)\n}\n```\n\n```ts\ninterface PolylineToSvgPathOptions {\n close?: boolean; // default false\n precision?: number; // [0, 12] integer, default 2\n}\n```\n\n## Errors\n\n| Error | Trigger |\n| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |\n| `InkError` | Base class; catch all ink errors with `instanceof InkError` |\n| `InkConfigError` | Invalid options (strength, tension, steps, width, thinning, precision, tolerance, cap, join, miterLimit, taper, …) or point-count mismatches |\n",
|
|
6
|
+
"usage": "---\ntitle: 'Ink: Usage Guide'\ndescription: 'How to smooth freehand strokes with @vielzeug/ink: stabilization, smoothing, speed-based widths, outline polygons, and SVG paths.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nCapture samples from any pointer source — with a timestamp — then run them through the pipeline: stabilize while drawing, simplify, width, outline, serialize. Every function is pure, so you can call them in any order and re-run them freely.\n\n```ts\nimport {\n polylineToSvgPath,\n simplifyStroke,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n} from '@vielzeug/ink';\n\n// Capture: PointerEvent.timeStamp is the timestamp ink wants.\nconst samples: StrokePoint[] = [];\nelement.addEventListener('pointermove', (event) => {\n samples.push({ pressure: event.pressure, time: event.timeStamp, x: event.offsetX, y: event.offsetY });\n});\n\nconst stabilized = stabilizeStroke(samples);\nconst widths = strokeWidths(stabilized, { width: 6 });\nconst d = polylineToSvgPath(strokeOutline(stabilized, widths), { close: true });\n\n// Render with any SVG-capable surface.\nconst path = document.createElementNS('http://www.w3.org/2000/svg', 'path');\npath.setAttribute('d', d);\n```\n\n## Stabilize While Drawing\n\n`stabilizeStroke()` removes hand jitter causally — it never looks ahead — so you can run it on every pointer move while the stroke is being drawn. It emits exactly one point per input sample, keeping per-sample metadata aligned, and its last point is always the last input point: the stroke ends exactly where the pen lifted.\n\n```ts\nimport { stabilizeStroke } from '@vielzeug/ink';\n\nconst live = stabilizeStroke(samples, { strength: 0.5 }); // 0 = raw, 1 = maximum smoothing\n```\n\n## Smooth After Capture\n\n`smoothStroke()` resamples the stroke through a uniform Catmull-Rom spline: each input segment becomes `steps` samples, and the first and last input points are preserved exactly. Use it after capture when you want extra curvature between sparse samples. `pressure` and `time` are interpolated linearly, so widths computed from the output match widths computed from the input.\n\n```ts\nimport { smoothStroke } from '@vielzeug/ink';\n\nconst resampled = smoothStroke(samples, { tension: 1, steps: 8 });\n```\n\n## Profile Widths From Speed and Pressure\n\n`strokeWidths()` derives real pen speed from the `time` field: `distance / Δtime` between consecutive points. That stays correct after any stabilization, smoothing, or simplification — pipeline order no longer matters. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n\n```ts\nimport { strokeWidths } from '@vielzeug/ink';\n\nconst widths = strokeWidths(stabilized, {\n width: 6,\n thinning: 0.5, // 0 disables velocity, 1 is fully inverse-proportional\n referenceSpeed: 0.5, // neutral pen speed in pixels per millisecond\n});\n```\n\nWhen points carry `pressure` (normalized `[0, 1]`), it multiplies the result: `0.5` is neutral and maps to exactly `1`, so a mouse (which reports `0.5`) draws as wide as a device without pressure data. When any point lacks `time`, velocity modulation is disabled for the whole stroke — width becomes `width × pressure` — instead of guessing speed from sample spacing.\n\n`taper` fades the ends: within the first `taper.start` and last `taper.end` units of arc length, the width is multiplied by a smoothstep ramp that bottoms out at `0.15` of full width at the tips. `simulatePressure` gives mouse strokes the same in/out feel by synthesizing pressure for points that have none (ramping to `0.5×` width at each tip over the last 15% of arc length); points with real `pressure` always keep it.\n\n```ts\nconst tapered = strokeWidths(stabilized, {\n width: 6,\n taper: { start: 40, end: 40 }, // 40 px of arc length faded at each end\n simulatePressure: true, // thin the ends of pressure-less mouse strokes\n});\n```\n\n## Build the Outline\n\n`strokeOutline()` offsets each sample by half its width along the local normal and closes the ring with half-circle caps at both ends. The result is a plain `Point[]` you can fill with any renderer.\n\n```ts\nimport { strokeOutline } from '@vielzeug/ink';\n\nconst ring = strokeOutline(stabilized, widths); // variable width, closed polygon\nconst uniform = strokeOutline(stabilized, 6); // constant width, no array needed\n```\n\n`cap` changes the ends: `'butt'` stops at the last offsets, `'square'` extends each end by half the width along the tangent. `join` fixes the crossing spike naive offsetting produces at turns sharper than 90°: `'bevel'` cuts the corner with the two adjacent offset points, and `'miter'` extends to the exact intersection while its length stays within `miterLimit` × half width, falling back to bevel beyond that.\n\n```ts\nconst marker = strokeOutline(stabilized, 6, { cap: 'square', join: 'miter', miterLimit: 6 });\n```\n\n## Simplify Before Serializing\n\nLong strokes accumulate samples. `simplifyStroke()` runs Ramer-Douglas-Peucker and returns a subsequence of the input, so object identity, `pressure`, and `time` survive. Apply it to the outline before emitting SVG to shrink path data.\n\n```ts\nimport { simplifyStroke, polylineToSvgPath } from '@vielzeug/ink';\n\nconst compact = polylineToSvgPath(simplifyStroke(ring, 0.25), { close: true });\n```\n\n## Serialize to SVG Paths\n\n`polylineToSvgPath()` writes `M` plus one `L` per point, rounding coordinates to `precision` decimal places. Pass `close: true` to append `Z` for the closed outline ring; leave it off for a centerline path.\n\n```ts\nimport { polylineToSvgPath } from '@vielzeug/ink';\n\nconst centerline = polylineToSvgPath(simplifyStroke(stabilized, 0.5), { precision: 1 });\nconst outline = polylineToSvgPath(ring, { close: true });\n```\n\n## Framework Integration\n\nInk functions are pure, so they memoize cleanly. Recompute geometry only when the sample array changes.\n\n::: code-group\n\n```tsx [React]\nimport { useMemo } from 'react';\nimport { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths, type StrokePoint } from '@vielzeug/ink';\n\nfunction InkPath({ samples }: { samples: StrokePoint[] }) {\n const d = useMemo(() => {\n const stabilized = stabilizeStroke(samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n }, [samples]);\n\n return <path d={d} />;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { computed } from 'vue';\nimport {\n polylineToSvgPath,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n} from '@vielzeug/ink';\n\nconst props = defineProps<{ samples: StrokePoint[] }>();\nconst d = computed(() => {\n const stabilized = stabilizeStroke(props.samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n});\n</script>\n\n<template>\n <svg><path :d=\"d\" /></svg>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import {\n polylineToSvgPath,\n stabilizeStroke,\n strokeOutline,\n strokeWidths,\n type StrokePoint,\n } from '@vielzeug/ink';\n\n export let samples: StrokePoint[];\n $: d = (() => {\n const stabilized = stabilizeStroke(samples);\n return polylineToSvgPath(strokeOutline(stabilized, strokeWidths(stabilized, { width: 6 })), { close: true });\n })();\n</script>\n\n<svg><path {d} /></svg>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nGesture produces the raw samples: bind a pan or drag handle, append each `current` point (with `event.timeStamp`) to an array, and pass the array to Ink when the stroke ends. Prism (or any SVG renderer) consumes the `d` strings Ink returns.\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\nimport { polylineToSvgPath, stabilizeStroke, type StrokePoint } from '@vielzeug/ink';\n\nconst samples: StrokePoint[] = [];\nconst drag = createDragGesture(surface, {\n onMove: ({ currentX, currentY, event }) => samples.push({ time: event.timeStamp, x: currentX, y: currentY }),\n onEnd: () => {\n path.setAttribute('d', polylineToSvgPath(stabilizeStroke(samples), { precision: 1 }));\n },\n});\n```\n\n## Best Practices\n\n- Pass `time` on every sample (`PointerEvent.timeStamp` or `performance.now()`): without it, widths are pressure-only and speed information is thrown away.\n- Stabilize live, smooth once: run `stabilizeStroke()` per pointer move for a calm preview, and add `smoothStroke()` or `simplifyStroke()` at commit time.\n- Simplify outlines with a tolerance around `0.2`–`0.5` device pixels; larger tolerances visibly flatten caps.\n- Keep `precision` at `1`–`2` for display paths; raise it only when another tool re-processes the output.\n- Treat invalid options errors (`InkConfigError`) as programming bugs: they throw at call time with the offending option named.\n- Memoize per stroke in UI frameworks; the functions are pure and cheap to cache.\n",
|
|
7
|
+
"examples": "---\ntitle: 'Ink: Examples'\ndescription: Practical examples and recipes for @vielzeug/ink.\n---\n\n## Examples\n\n- [Jitter-Free Ink](./examples/jitter-free-ink.md)\n"
|
|
8
|
+
},
|
|
9
|
+
"examples": [
|
|
10
|
+
{
|
|
11
|
+
"id": "ink-outline-options",
|
|
12
|
+
"code": "import { polylineToSvgPath, strokeOutline, strokeWidths } from '@vielzeug/ink'\n\n// A hairpin turn plus a straight run: sharp enough that naive offsets spike.\nconst samples = [\n { time: 0, x: 20, y: 40 },\n { time: 16, x: 150, y: 40 },\n { time: 32, x: 70, y: 110 },\n { time: 48, x: 60, y: 30 },\n]\n\nconst widths = strokeWidths(samples, {\n width: 14,\n taper: { start: 30, end: 30 }, // fade the ends over 30px of arc length\n simulatePressure: true, // mouse strokes have no pressure: synthesize it\n})\n\nconst variants = [\n { label: 'round join + round cap', options: {} },\n { label: 'bevel join + butt cap', options: { cap: 'butt', join: 'bevel' } },\n { label: 'miter join + square cap', options: { cap: 'square', join: 'miter', miterLimit: 6 } },\n]\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '0 0 320 260')\nsvg.style.cssText = 'width:100%;max-width:480px;background:#f8fafc;border-radius:12px;'\n\nvariants.forEach((variant, row) => {\n const outline = strokeOutline(samples, widths, variant.options)\n const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')\n path.setAttribute('d', polylineToSvgPath(outline, { close: true }))\n path.setAttribute('fill', '#0f172a')\n path.setAttribute('transform', `translate(0 ${row * 84})`)\n const label = document.createElementNS('http://www.w3.org/2000/svg', 'text')\n label.setAttribute('x', '8')\n label.setAttribute('y', 12 + row * 84)\n label.setAttribute('font-size', '10')\n label.setAttribute('fill', '#64748b')\n label.textContent = variant.label\n svg.append(label, path)\n console.log(variant.label, 'outline points:', outline.length)\n})\n\ndocument.body.appendChild(svg)",
|
|
13
|
+
"name": "strokeOutline options - caps, joins, and taper"
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"id": "ink-smoothing",
|
|
17
|
+
"code": "import { polylineToSvgPath, stabilizeStroke, strokeOutline, strokeWidths } from '@vielzeug/ink'\n\n// Deterministic zig-zag samples with timestamps: the jitter stabilization must remove.\nconst samples = Array.from({ length: 24 }, (_, i) => ({\n time: i * 16,\n x: 20 + i * 12,\n y: 80 + (i % 2 === 0 ? 14 : -14),\n}))\n\nconst stabilized = stabilizeStroke(samples)\nconst widths = strokeWidths(stabilized, { width: 8 })\nconst outline = strokeOutline(stabilized, widths)\n\nconst svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')\nsvg.setAttribute('viewBox', '0 0 320 160')\nsvg.style.cssText = 'width:100%;max-width:480px;background:#f8fafc;border-radius:12px;'\n\nconst raw = document.createElementNS('http://www.w3.org/2000/svg', 'polyline')\nraw.setAttribute('points', samples.map((p) => `${p.x},${p.y}`).join(' '))\nraw.setAttribute('fill', 'none')\nraw.setAttribute('stroke', '#cbd5e1')\nraw.setAttribute('stroke-dasharray', '4 4')\n\nconst ink = document.createElementNS('http://www.w3.org/2000/svg', 'path')\nink.setAttribute('d', polylineToSvgPath(outline, { close: true }))\nink.setAttribute('fill', '#0f172a')\n\nsvg.append(raw, ink)\ndocument.body.appendChild(svg)\n\nconsole.log('samples:', samples.length, 'stabilized:', stabilized.length, 'outline points:', outline.length)",
|
|
18
|
+
"name": "stabilizeStroke - Jitter-free ink"
|
|
19
|
+
}
|
|
20
|
+
],
|
|
21
|
+
"typeSignatures": {
|
|
22
|
+
"InkConfigError": "export { InkConfigError, InkError } from './errors.js';",
|
|
23
|
+
"InkError": "export { InkConfigError, InkError } from './errors.js';",
|
|
24
|
+
"StrokeCap": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
|
|
25
|
+
"StrokeJoin": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
|
|
26
|
+
"StrokeOutlineOptions": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
|
|
27
|
+
"strokeOutline": "export { type StrokeCap, type StrokeJoin, type StrokeOutlineOptions, strokeOutline } from './outline.js';",
|
|
28
|
+
"simplifyStroke": "export { simplifyStroke } from './simplify.js';",
|
|
29
|
+
"SmoothStrokeOptions": "export { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';",
|
|
30
|
+
"smoothStroke": "export { type SmoothStrokeOptions, smoothStroke } from './smoothing.js';",
|
|
31
|
+
"StabilizeStrokeOptions": "export { type StabilizeStrokeOptions, stabilizeStroke } from './stabilize.js';",
|
|
32
|
+
"stabilizeStroke": "export { type StabilizeStrokeOptions, stabilizeStroke } from './stabilize.js';",
|
|
33
|
+
"PolylineToSvgPathOptions": "export { type PolylineToSvgPathOptions, polylineToSvgPath } from './svg.js';",
|
|
34
|
+
"polylineToSvgPath": "export { type PolylineToSvgPathOptions, polylineToSvgPath } from './svg.js';",
|
|
35
|
+
"Point": "export type { Point, StrokePoint } from './types.js';",
|
|
36
|
+
"StrokePoint": "export type { Point, StrokePoint } from './types.js';",
|
|
37
|
+
"StrokeTaperOptions": "export { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';",
|
|
38
|
+
"StrokeWidthOptions": "export { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';",
|
|
39
|
+
"strokeWidths": "export { type StrokeTaperOptions, type StrokeWidthOptions, strokeWidths } from './widths.js';"
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiSource": "// Public root surface of @vielzeug/palette. Every public export goes through this file.\n\nexport { contrastRatio, readableOn, relativeLuminance } from './contrast.js';\nexport { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';\nexport { PaletteConfigError, PaletteError, PaletteParseError } from './errors.js';\nexport { toHex, toHslString, toOklchString, toRgbString } from './format.js';\nexport { mix, ramp } from './mix.js';\nexport { parseColor } from './parse.js';\nexport type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';\n",
|
|
3
|
+
"docs": {
|
|
4
|
+
"index": "---\ntitle: 'Palette: Color math for design tools'\ndescription: 'Color parsing, conversion, mixing, and contrast for design tools'\npackage: palette\ncategory: utilities\nkeywords: [color, color parsing, oklch, oklab, hsl, contrast, wcag, mix, ramp, luminance]\nexports:\n [\n parseColor,\n toHex,\n toRgbString,\n toHslString,\n toOklchString,\n srgbToOklch,\n oklchToSrgb,\n isDisplayable,\n srgbToHsl,\n hslToSrgb,\n mix,\n contrastRatio,\n relativeLuminance,\n readableOn,\n ramp,\n PaletteParseError,\n PaletteConfigError,\n ]\nrelated: [arsenal, refine]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"palette\" />\n\n## Why Palette?\n\nDesign tools need color math that is correct where it matters — perceptual OKLab mixing, WCAG contrast, lossless extended-range conversions — without pulling in a color library that assumes a DOM, a canvas, or a particular color model.\n\n```ts\n// Before\nconst mid = { r: (a.r + b.r) / 2, g: (a.g + b.g) / 2, b: (a.b + b.b) / 2 }; // gamma-space average, looks wrong\nconst ratio = /* hand-rolled luminance, usually forgets the sRGB transfer function */;\n\n// After\nimport { contrastRatio, mix, parseColor, ramp } from '@vielzeug/palette';\n\nconst mid = mix(parseColor('#000000'), parseColor('#ffffff'), 0.5); // perceptual OKLab midpoint\nconst ratio = contrastRatio(parseColor('#767676'), parseColor('#ffffff')); // 4.54\nconst shades = ramp(parseColor('#3366cc'), { steps: 9 }); // OKLCH lightness ramp\n```\n\n| Feature | Palette | Ad-hoc color helpers |\n| --------------------------------------- | --------------------------------------------- | -------------------- |\n| Bundle size | <PackageInfo package=\"palette\" type=\"size\" /> | n/a |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a |\n| CSS Color 4 `oklab()`/`oklch()` parsing | Built in | Manual |\n| CSS named colors | Built in | Manual |\n| OKLab mixing with premultiplied alpha | Built in, matches `color-mix(in oklab)` | Manual |\n| WCAG 2.x contrast | Built in | Manual |\n| Perceptual ramps | OKLCH lightness, gamut-fitted | Manual |\n\n<div class=\"decision-callout\">\n\n**Use Palette when** an application needs headless color parsing, conversion, mixing, or contrast checks with no DOM or rendering assumptions.\n\n**Consider a rendering-layer color API when** the work is applying colors to a surface rather than computing them.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/palette\n```\n\n```sh [npm]\nnpm install @vielzeug/palette\n```\n\n```sh [yarn]\nyarn add @vielzeug/palette\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { mix, parseColor, ramp, readableOn, toHex } from '@vielzeug/palette';\n\nconst brand = parseColor('#3366cc');\nconst surface = parseColor('rgb(248 250 252)');\n\nconst ink = readableOn(surface, [parseColor('#0f172a'), parseColor('#334155')]);\nconst midpoint = mix(brand, surface, 0.5); // OKLab interpolation, like color-mix(in oklab)\nconst shades = ramp(brand, { steps: 9 }); // OKLCH lightness ramp\n\nconsole.log(toHex(ink ?? brand), toHex(midpoint), shades.map(toHex));\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `parseColor()`: `#rgb`/`#rgba`/`#rrggbb`/`#rrggbbaa`, `rgb()`/`hsl()` comma and space syntax, CSS Color 4 `oklab()`/`oklch()`, and CSS named colors\n- `toHex()`, `toRgbString()`, `toHslString()`, `toOklchString()`: formatting with documented clamping at the display boundary\n- `srgbToOklch()` / `oklchToSrgb()`, `srgbToHsl()` / `hslToSrgb()`: lossless round-trippable conversions via the standard Björn Ottosson OKLab matrices\n- `isDisplayable()`: gamut test for any `Rgba` against sRGB\n- `mix()`: OKLab interpolation with premultiplied alpha, matching CSS `color-mix(in oklab)`\n- `contrastRatio()` and `relativeLuminance()`: WCAG 2.x ratios on clamped sRGB\n- `readableOn()`: picks the first candidate meeting the AA/AAA threshold, with large-text thresholds\n- `ramp()`: deterministic OKLCH lightness ramps that keep hue and stay inside the gamut\n- Typed errors: `PaletteParseError` and `PaletteConfigError` share the `PaletteError` base\n- Pure functions only: no DOM, no disposal contract, zero dependencies\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- [Arsenal](/arsenal/): general-purpose utilities that complement headless color math.\n- [Refine](/refine/): components styled with design tokens that tools like this generate and check.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Palette: API Reference'\ndescription: API reference for color parsing, conversion, mixing, and contrast.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------------- | -------------------------------------------- | --------- | ------------------------------------------------------- |\n| `parseColor()` | Parse a CSS color string into `Rgba` | Sync | `color()` is out of scope; named colors are supported |\n| `toHex()` | Format as `#rrggbb`/`#rrggbbaa` | Sync | Alpha is written when translucent unless `alpha: false` |\n| `toRgbString()` | Format as CSS `rgb()` space syntax | Sync | Channels are clamped to 0–255 |\n| `toHslString()` | Format as CSS `hsl()` space syntax | Sync | Channels are clamped before conversion |\n| `toOklchString()` | Format as CSS `oklch()` syntax | Sync | Writes true channels, even out of gamut |\n| `srgbToOklch()` | Convert sRGB to OKLCH | Sync | Round-trip drifts up to ±1 per channel |\n| `oklchToSrgb()` | Convert OKLCH to sRGB | Sync | Out-of-gamut channels stay unclamped, they do not throw |\n| `isDisplayable()` | Test an `Rgba` against the sRGB gamut | Sync | Allows a small rounding tolerance |\n| `srgbToHsl()` | Convert sRGB to HSL | Sync | `h` is 0–360, `s`/`l` are 0–100 |\n| `hslToSrgb()` | Convert HSL to sRGB | Sync | Hue wraps; channels beyond the gamut stay unclamped |\n| `mix()` | OKLab interpolation with premultiplied alpha | Sync | `t` outside `[0, 1]` throws `PaletteConfigError` |\n| `relativeLuminance()` | WCAG 2.x relative luminance | Sync | Computed on channels clamped to 0–255 |\n| `contrastRatio()` | WCAG 2.x contrast ratio (1–21) | Sync | Ignores alpha by design |\n| `readableOn()` | First candidate meeting a WCAG threshold | Sync | Returns `null` when nothing passes |\n| `ramp()` | OKLCH lightness ramp of a base color | Sync | `steps` must be an integer ≥ 2 |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------- | --------------------------- |\n| `@vielzeug/palette` | Complete public Palette API |\n\n## Parsing\n\n### `parseColor()`\n\n```ts\nfunction parseColor(input: string): Rgba;\n```\n\nParses `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`; `rgb()`/`rgba()` and `hsl()`/`hsla()` in comma and space syntax with optional `/ alpha`; `oklab()`/`oklch()` with alpha per CSS Color 4; and the CSS named colors (case-insensitive, including `transparent`). Percentage `oklab` `a`/`b` and `oklch` `c` map to ±0.4; percentage `rgb` channels map to 0–255. Alpha accepts a number or percentage and clamps to 0–1. Out-of-range channels are kept exactly — nothing clips. Throws `PaletteParseError` including the offending input.\n\n## Formatting\n\n### `toHex()`\n\n```ts\nfunction toHex(color: Rgba, options?: FormatOptions): string;\n```\n\nFormats as `#rrggbb`, or `#rrggbbaa` when the color is translucent or `options.alpha` is `true`. Channels clamp to 0–255 and alpha to 0–1.\n\n### `toRgbString()`\n\n```ts\nfunction toRgbString(color: Rgba, options?: FormatOptions): string;\n```\n\nFormats as `rgb(r g b)` or `rgb(r g b / a)` space syntax. Same clamping as `toHex()`.\n\n### `toHslString()`\n\n```ts\nfunction toHslString(color: Rgba, options?: FormatOptions): string;\n```\n\nFormats as `hsl(h s% l%)` or `hsl(h s% l% / a)`. Channels clamp before conversion.\n\n### `toOklchString()`\n\n```ts\nfunction toOklchString(color: Rgba, options?: FormatOptions): string;\n```\n\nFormats as `oklch(l% c h)` or `oklch(l% c h / a)` on the color's true channels — an out-of-gamut color keeps its exact OKLCH values rather than the clamped ones.\n\n## Conversion\n\n### `srgbToOklch()` / `oklchToSrgb()`\n\n```ts\nfunction srgbToOklch(color: Rgba): Oklch;\nfunction oklchToSrgb(color: Oklch): Rgba;\n```\n\nStandard sRGB → linear → OKLab → OKLCH pipeline (Björn Ottosson's matrices with the sRGB transfer function, sign-extended to negative channels per CSS Color 4). The pipeline is lossless: `oklchToSrgb()` leaves out-of-gamut channels outside 0–255 instead of clipping, so `srgbToOklch()` recovers the original OKLCH values.\n\n### `isDisplayable()`\n\n```ts\nfunction isDisplayable(color: Rgba): boolean;\n```\n\nTrue when every linear-light channel of `color` falls inside `[0, 1]` (within a `0.00015` rounding tolerance, matching CSS Color 4 implementations). Works on any `Rgba` — parsed, converted, or mixed — so it detects out-of-gamut colors before a formatter clamps them.\n\n### `srgbToHsl()` / `hslToSrgb()`\n\n```ts\nfunction srgbToHsl(color: Rgba): Hsla;\nfunction hslToSrgb(color: Hsla): Rgba;\n```\n\n`h` is degrees in `[0, 360)`, `s` and `l` are percentages 0–100. `hslToSrgb()` wraps hue and leaves channels outside 0–255 unclamped (an `l` beyond 100% produces values beyond 255).\n\n## Mixing\n\n### `mix()`\n\n```ts\nfunction mix(a: Rgba, b: Rgba, t: number): Rgba;\n```\n\nInterpolates in OKLab with premultiplied alpha, matching CSS `color-mix(in oklab, ...)`. `t` is 0 for `a`, 1 for `b`; outside `[0, 1]` throws `PaletteConfigError`. A fully transparent endpoint contributes no color: mixing red with `rgba(0 0 0 / 0)` yields red at half alpha, not a darkened blend.\n\n## Contrast\n\n### `relativeLuminance()`\n\n```ts\nfunction relativeLuminance(color: Rgba): number;\n```\n\nWCAG 2.x relative luminance on channels clamped to 0–255.\n\n### `contrastRatio()`\n\n```ts\nfunction contrastRatio(a: Rgba, b: Rgba): number;\n```\n\nWCAG 2.x contrast ratio: 1 for identical colors, 21 for black on white. Symmetric in its arguments.\n\n### `readableOn()`\n\n```ts\nfunction readableOn(background: Rgba, candidates: readonly Rgba[], options?: ReadableOnOptions): Rgba | null;\n```\n\nReturns the first candidate whose contrast against `background` reaches the threshold: 4.5 (`level: 'AA'`, default) or 7 (`'AAA'`), or 3 / 4.5 with `large: true`. Returns `null` when no candidate passes.\n\n## Ramps\n\n### `ramp()`\n\n```ts\nfunction ramp(base: Rgba, options: RampOptions): Rgba[];\n```\n\nBuilds `steps` swatches dark to light by interpolating OKLab lightness between `minLightness` (default 0.15) and `maxLightness` (default 0.95) while keeping the base color's hue. Where a swatch would fall outside the sRGB gamut, its chroma is reduced (binary search at fixed lightness and hue) until it fits — so every swatch is displayable and the hue stays stable instead of shifting under clamping. Deterministic. Throws `PaletteConfigError` for non-integer or sub-2 `steps`, bounds outside `[0, 1]`, or `minLightness > maxLightness`.\n\n## Types\n\n### `Rgba`\n\n```ts\ntype Rgba = Readonly<{ r: number; g: number; b: number; a: number }>;\n```\n\nExtended-range sRGB: `r`/`g`/`b` are 0–255 for displayable colors but may fall outside that range when a color came from an out-of-gamut OKLCH/HSL value or out-of-range channels — the conversion pipeline never clips. `a` is always 0–1. Use `isDisplayable()` to test the gamut and the formatters (which clamp) for display-safe output.\n\n### `Hsla`\n\n```ts\ntype Hsla = Readonly<{ h: number; s: number; l: number; a: number }>;\n```\n\n`h` is degrees 0–360, `s` and `l` are percentages 0–100, `a` is 0–1.\n\n### `Oklch`\n\n```ts\ntype Oklch = Readonly<{ l: number; c: number; h: number; a: number }>;\n```\n\n`l` is lightness 0–1, `c` is chroma, `h` is hue in degrees, `a` is alpha 0–1. OKLab is the internal waypoint between sRGB and OKLCH and is not part of the public surface.\n\n### `FormatOptions`\n\n```ts\ntype FormatOptions = Readonly<{ alpha?: boolean }>;\n```\n\nWhen `alpha` is `true` the alpha channel is always written; otherwise it is written only when the color is translucent.\n\n### `ReadableOnOptions`\n\n```ts\ntype ReadableOnOptions = Readonly<{ level?: 'AA' | 'AAA'; large?: boolean }>;\n```\n\n### `RampOptions`\n\n```ts\ntype RampOptions = Readonly<{ steps: number; minLightness?: number; maxLightness?: number }>;\n```\n\n## Errors\n\n| Error | Thrown by | Meaning |\n| -------------------- | ----------------- | ----------------------------------------------------------------------------------- |\n| `PaletteParseError` | `parseColor()` | Input did not match the supported grammar; the message includes the offending input |\n| `PaletteConfigError` | `mix()`, `ramp()` | Invalid options or positions |\n\nBoth extend `PaletteError`, so `catch (error) { if (error instanceof PaletteError) ... }` narrows both.\n",
|
|
6
|
+
"usage": "---\ntitle: 'Palette: Usage Guide'\ndescription: Parse, convert, mix, and check colors with headless color math.\n---\n\n[[toc]]\n\n## Basic Usage\n\n```ts\nimport { parseColor, toHex } from '@vielzeug/palette';\n\nconst brand = parseColor('#3366cc'); // { r: 51, g: 102, b: 204, a: 1 }\nconsole.log(toHex(brand)); // \"#3366cc\"\n```\n\n`parseColor()` accepts hex (3, 4, 6, and 8 digits), `rgb()`/`rgba()` and `hsl()`/`hsla()` in both comma and space syntax, CSS Color 4 `oklab()`/`oklch()`, and the CSS named colors (case-insensitive, including `transparent`). Anything else throws `PaletteParseError` with the offending input in the message. The `color()` notation is out of scope.\n\n## Parse CSS Colors\n\n```ts\nimport { parseColor } from '@vielzeug/palette';\n\nparseColor('#f09'); // #rgb: digits are duplicated\nparseColor('#f098'); // #rgba\nparseColor('rgb(1, 2, 3)'); // comma syntax\nparseColor('rgba(1, 2, 3, 0.5)'); // legacy comma alpha\nparseColor('rgb(1 2 3 / 0.5)'); // space syntax with slash alpha\nparseColor('rgb(50% 25% 0%)'); // percentages map to 0–255\nparseColor('hsl(120, 100%, 50%)'); // hue wraps: -120 and 480 are valid\nparseColor('oklab(0.5 -0.1 0.1 / 0.5)'); // CSS Color 4\nparseColor('oklch(50% 0.1 240deg)'); // percent lightness, deg hue\nparseColor('RebeccaPurple'); // named colors, any case\nparseColor('transparent'); // { r: 0, g: 0, b: 0, a: 0 }\n```\n\nPercentage `oklab` `a`/`b` and `oklch` `c` map to the CSS Color 4 range of ±0.4. Alpha accepts a number or a percentage and is clamped to 0–1. Out-of-range channels (`rgb(300 0 0)`) are kept exactly — parsing never clips.\n\n## Convert Between Color Spaces\n\n```ts\nimport { hslToSrgb, oklchToSrgb, parseColor, srgbToHsl, srgbToOklch } from '@vielzeug/palette';\n\nconst red = parseColor('#ff0000');\nconst oklch = srgbToOklch(red); // { l: 0.628, c: 0.2577, h: 29.23, a: 1 }\nconst hsl = srgbToHsl(red); // { h: 0, s: 100, l: 50, a: 1 }\n\nconst back = oklchToSrgb(oklch); // round-trips within ±1 per channel\n```\n\nConversions use the standard sRGB → linear → OKLab → OKLCH pipeline (Björn Ottosson's matrices, sRGB transfer function sign-extended per CSS Color 4). The pipeline is lossless: `oklchToSrgb()` leaves out-of-gamut channels outside 0–255, so `srgbToOklch()` recovers the original values, and `isDisplayable()` tells you whether a color fits the screen.\n\n## Format Colors\n\n```ts\nimport { parseColor, toHex, toHslString, toOklchString, toRgbString } from '@vielzeug/palette';\n\nconst translucent = parseColor('rgb(222 173 190 / 0.5)');\ntoHex(translucent); // \"#deadbe80\" — alpha is written when the color is translucent\ntoHex(translucent, { alpha: false }); // \"#deadbe\" — never write alpha...\ntoHex(parseColor('#deadbeef'), { alpha: true }); // \"#deadbeff\" — ...or always write it\ntoRgbString(translucent); // \"rgb(222 173 190 / 0.5)\"\ntoHslString(parseColor('#ff0000')); // \"hsl(0 100% 50%)\"\ntoOklchString(parseColor('#ff0000')); // \"oklch(62.8% 0.2577 29.23)\"\n```\n\n`toHex()`, `toRgbString()`, and `toHslString()` clamp out-of-gamut channels to 0–255 and alpha to 0–1 before writing, so their output is always display-safe. A color produced by `parseColor('rgb(300 0 0)')` keeps its out-of-range channel until formatted, where it clamps to `255`. `toOklchString()` writes the color's true OKLCH values — an out-of-gamut color round-trips through `parseColor()` exactly.\n\n## Mix in OKLab\n\n```ts\nimport { mix, parseColor, toHex } from '@vielzeug/palette';\n\nconst mid = mix(parseColor('#000000'), parseColor('#ffffff'), 0.5);\ntoHex(mid); // \"#636363\" — the perceptual midpoint, not #808080\n\nconst hover = mix(parseColor('#ff0000'), parseColor('rgb(0 0 0 / 0)'), 0.5);\ntoHex(hover); // \"#ff000080\" — transparent endpoints don't darken\n```\n\n`mix()` interpolates in OKLab with premultiplied alpha, matching CSS `color-mix(in oklab, ...)`: midpoints are perceptually even, and a transparent endpoint contributes no color instead of pulling the blend toward black. A `t` outside `[0, 1]` throws `PaletteConfigError`.\n\n## Check Contrast\n\n```ts\nimport { contrastRatio, parseColor, readableOn } from '@vielzeug/palette';\n\ncontrastRatio(parseColor('#000000'), parseColor('#ffffff')); // 21\ncontrastRatio(parseColor('#767676'), parseColor('#ffffff')); // ≈ 4.54 (AA boundary)\n\nconst ink = readableOn(parseColor('#f8fafc'), [parseColor('#94a3b8'), parseColor('#0f172a')]);\n// → #0f172a: the first candidate that reaches the threshold\n```\n\n`contrastRatio()` uses WCAG 2.x relative luminance on channels clamped to 0–255. `readableOn()` picks the first candidate meeting 4.5 (AA) or 7 (AAA), or 3 / 4.5 with `{ large: true }`, and returns `null` when nothing passes.\n\n## Build Lightness Ramps\n\n```ts\nimport { parseColor, ramp, toHex } from '@vielzeug/palette';\n\nconst shades = ramp(parseColor('#3366cc'), { steps: 9 });\nconsole.log(shades.map(toHex)); // nine swatches, dark to light\n```\n\n`ramp()` interpolates OKLab lightness between `minLightness` (default 0.15) and `maxLightness` (default 0.95) at the base color's hue. Where a swatch would leave the sRGB gamut, its chroma is reduced until it fits — every swatch is displayable and the hue never shifts under clamping. The result is deterministic and runs dark to light. Invalid `steps` or lightness bounds throw `PaletteConfigError`.\n\n## Errors\n\nAll failures are `PaletteError` subclasses: `PaletteParseError` for malformed input and `PaletteConfigError` for invalid options. Catch the base class to handle both.\n\n## Best Practices\n\n- Parse once at the boundary, keep `Rgba` values, and format at the edges; conversions are cheap but parsing strings repeatedly is wasteful.\n- Use `mix()` instead of averaging channels — gamma-space averages look muddy.\n- Use `ramp()` for tonal scales and `readableOn()` for ink selection instead of hand-tuned hex pairs.\n- Keep out-of-gamut colors in the pipeline as long as you like — conversions are lossless. Check `isDisplayable()` before handing a color to something that can't represent it, and let the formatters clamp at the display boundary.\n",
|
|
7
|
+
"examples": "---\ntitle: 'Palette: Examples'\ndescription: Practical examples and recipes for @vielzeug/palette.\n---\n\n## Examples\n\n- [Parse, Mix and Contrast](./examples/parse-mix-and-contrast.md)\n"
|
|
8
|
+
},
|
|
9
|
+
"examples": [
|
|
10
|
+
{
|
|
11
|
+
"id": "palette-basic",
|
|
12
|
+
"code": "import { contrastRatio, mix, parseColor, ramp, readableOn, toHex } from '@vielzeug/palette'\n\nconst brand = parseColor('#3366cc')\nconst surface = parseColor('rgb(248 250 252)')\n\nconst hover = mix(brand, surface, 0.5)\nconsole.log('hover', toHex(hover))\n\nconst ink = readableOn(surface, [parseColor('#94a3b8'), parseColor('#0f172a')])\nconsole.log('ink', ink ? toHex(ink) : null)\nconsole.log('contrast', contrastRatio(surface, ink ?? brand).toFixed(2))\n\nconsole.log('ramp', ramp(brand, { steps: 5 }).map(toHex).join(' '))",
|
|
13
|
+
"name": "Basics - parse, mix, contrast, ramp"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"typeSignatures": {
|
|
17
|
+
"contrastRatio": "export { contrastRatio, readableOn, relativeLuminance } from './contrast.js';",
|
|
18
|
+
"readableOn": "export { contrastRatio, readableOn, relativeLuminance } from './contrast.js';",
|
|
19
|
+
"relativeLuminance": "export { contrastRatio, readableOn, relativeLuminance } from './contrast.js';",
|
|
20
|
+
"hslToSrgb": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
|
|
21
|
+
"isDisplayable": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
|
|
22
|
+
"oklchToSrgb": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
|
|
23
|
+
"srgbToHsl": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
|
|
24
|
+
"srgbToOklch": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
|
|
25
|
+
"PaletteConfigError": "export { PaletteConfigError, PaletteError, PaletteParseError } from './errors.js';",
|
|
26
|
+
"PaletteError": "export { PaletteConfigError, PaletteError, PaletteParseError } from './errors.js';",
|
|
27
|
+
"PaletteParseError": "export { PaletteConfigError, PaletteError, PaletteParseError } from './errors.js';",
|
|
28
|
+
"toHex": "export { toHex, toHslString, toOklchString, toRgbString } from './format.js';",
|
|
29
|
+
"toHslString": "export { toHex, toHslString, toOklchString, toRgbString } from './format.js';",
|
|
30
|
+
"toOklchString": "export { toHex, toHslString, toOklchString, toRgbString } from './format.js';",
|
|
31
|
+
"toRgbString": "export { toHex, toHslString, toOklchString, toRgbString } from './format.js';",
|
|
32
|
+
"mix": "export { mix, ramp } from './mix.js';",
|
|
33
|
+
"ramp": "export { mix, ramp } from './mix.js';",
|
|
34
|
+
"parseColor": "export { parseColor } from './parse.js';",
|
|
35
|
+
"FormatOptions": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
|
|
36
|
+
"Hsla": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
|
|
37
|
+
"Oklch": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
|
|
38
|
+
"RampOptions": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
|
|
39
|
+
"ReadableOnOptions": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
|
|
40
|
+
"Rgba": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';"
|
|
41
|
+
}
|
|
42
|
+
}
|