@vielzeug/codex 26.11.20 → 26.11.22

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.
@@ -2,7 +2,7 @@
2
2
  "apiSource": "// Public root surface of @vielzeug/bard. Every public export goes through this file.\nexport { createBard } from './bard';\nexport { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';\nexport type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';\n",
3
3
  "docs": {
4
4
  "index": "---\ntitle: 'Bard'\ndescription: 'Lifecycle-owned Web Audio mixing: buses with ducking, buffered SFX and sprites, procedural synth, streamed tracks, and crossfading music decks'\npackage: bard\ncategory: utilities\nkeywords: [web-audio, audio, sfx, soundboard, crossfade, ducking, audio-sprites]\nrelated: [necromancer]\nexports: [createBard, BardError, BardLoadError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"bard\" />\n\n## Why Bard?\n\nThe Web Audio API gives you nodes and params but no lifecycle: nothing stops voices, removes gesture listeners, or closes the context when your feature unmounts. Bard wraps a lazily created `AudioContext` in one disposable engine with named buses, ducking, voice caps, and a crossfading music deck.\n\n```ts\n// Before: hand-rolled graph, listeners, and teardown you must remember\nconst ctx = new AudioContext();\nconst source = ctx.createBufferSource();\nsource.connect(ctx.destination);\n// ...who disconnects this on unmount?\n\n// After\nconst bard = createBard({ ducking: [{ source: 'voice', target: 'music', gain: 0.3 }] });\nawait bard.load({ confirm: '/confirm.wav' });\nbard.play('confirm');\nbard.dispose(); // stops voices, removes listeners, closes the context\n```\n\n| Feature | Native Web Audio | Bard | Howler.js |\n| ----------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | 0 B | <PackageInfo package=\"bard\" type=\"size\" /> | ~30 kB |\n| Root dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Lifecycle | Manual node teardown | `dispose()` + `Symbol.dispose` | Per-sound unload |\n| Mixing | Hand-built gain graph | Named buses, ducking rules, voice caps | Per-sound volume only |\n| Music transitions | Manual crossfade scheduling | `deck.transition()` with loop points, queue | Not built in |\n\n<div class=\"decision-callout\">\n\n**Use Bard when** an interactive app needs owned audio: UI SFX with voice caps, narration that ducks music, or game-state music transitions with crossfades and loop points.\n\n**Consider a plain `HTMLAudioElement` when** you need one background track with no mixing, sprites, or lifecycle requirements.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/bard\n```\n\n```sh [npm]\nnpm install @vielzeug/bard\n```\n\n```sh [yarn]\nyarn add @vielzeug/bard\n```\n\n:::\n\n## Quick Start\n\nCreate the engine once per app, load assets, and dispose it when the owning feature unmounts. Nothing touches `AudioContext` or the DOM until the first call that needs audio, so server rendering is safe.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard({\n ducking: [{ source: 'voice', target: 'music', gain: 0.3 }],\n});\n\nawait bard.load({\n music: { src: '/theme.mp3', stream: true },\n dice: { src: '/sfx.wav', sprites: { roll: [0, 1.2] } },\n});\n\nconst deck = bard.createDeck();\ndeck.transition('music', { loop: true });\nbard.play('dice:roll', { detune: [-60, 60] });\n\nbard.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createBard()`**: one disposable owner for the context, buses, voices, and decks.\n- **`bus()`**: named gain buses (`music`, `sfx`, `voice`) with click-free volume ramps.\n- **`ducking`**: declarative rules that ramp a target bus while a source bus has active voices.\n- **`play()`**: buffered playback with sprites, voice caps, oldest-first stealing, and detune/rate variance.\n- **`synth()`**: zero-asset oscillator and noise voices with ADSR and frequency sweeps.\n- **`createDeck()`**: two-slot crossfader with loop points, queue with shuffle, and opt-in Media Session.\n- **`tap()`**: observability events for state changes, steals, ducks, and track changes.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Necromancer](/necromancer/): pair visual transitions with deck music transitions from the same game-state change.\n- [Arsenal](/arsenal/): general-purpose utilities used across the monorepo.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Bard: API Reference'\ndescription: Public API of @vielzeug/bard.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ---------------------- | ------------------------------------------- | --------- | ------------------------------------------------------------------------ |\n| `createBard` | Creates the disposable audio engine | Sync | Context is still created lazily on first audio use |\n| `BardError` | Base error for invalid keys, buses, regions | — | Subclasses: `BardLoadError`, `BardDisposedError`, `BardUnsupportedError` |\n| `BardLoadError` | A manifest entry failed to fetch or decode | — | Original failure is in `cause` |\n| `BardDisposedError` | A method ran after `dispose()` | — | Thrown by every engine method except `dispose` |\n| `BardUnsupportedError` | No `AudioContext` in the runtime | — | `unlock()` rejects with it on servers without Web Audio |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | --------------------------------------- |\n| `@vielzeug/bard` | Complete public Bard API |\n| `@vielzeug/bard/testing` | Deterministic Web Audio fakes for tests |\n\n## Engine\n\n### createBard\n\n```ts\nfunction createBard(options?: BardOptions): Bard;\n```\n\nCreates the engine. Touches no browser global until the first method that needs audio.\n\n| Option | Type | Default | Notes |\n| --------------------- | ------------------------ | --------------------------- | --------------------------------------------------------------------------- |\n| `buses` | `readonly string[]` | `['music', 'sfx', 'voice']` | `'master'` is reserved and throws if declared |\n| `volume` | `number` | `1` | Master volume, linear 0..1 |\n| `ducking` | `readonly DuckingRule[]` | `[]` | See Ducking |\n| `maxVoices` | `number` | `32` | Engine-wide concurrent voice cap |\n| `autoUnlock` | `boolean` | `true` | Gesture listeners resume a suspended context |\n| `autoSuspendOnHidden` | `boolean` | `false` | Suspend on page hide, resume on show (only resumes its own suspends) |\n| `context` | `() => AudioContext` | lazy `new AudioContext()` | Injection seam for tests; injected contexts are never closed by `dispose()` |\n\nReturns the `Bard` engine.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard({ volume: 0.9 });\n```\n\n### Bard\n\n| Member | Signature | Notes |\n| ----------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |\n| `state` | `'idle' \\| 'suspended' \\| 'running' \\| 'interrupted' \\| 'closed'` | `'idle'` until first lazy context creation; `'interrupted'` occurs on iOS calls |\n| `context` | `AudioContext \\| null` | Native context for advanced graph work |\n| `unlock()` | `() => Promise<void>` | Creates and resumes the context |\n| `load(manifest, options?)` | `(AssetManifest, { signal? }) => Promise<void>` | Deduplicates concurrent fetches per URL |\n| `unload(keys?)` | `(string \\| readonly string[]) => void` | Stops active voices for the dropped keys |\n| `has(key)` | `(string) => boolean` | Resolves `'key:sprite'` to its parent asset |\n| `play(key, options?)` | `(string, PlayOptions?) => SoundHandle` | Throws `BardError` for unknown keys and streamed assets |\n| `synth(options)` | `(SynthOptions) => SoundHandle` | Procedural voice, self-cleaning |\n| `bus(name)` | `(string) => BusController` | `'master'` is valid; unknown names throw |\n| `createDeck(options?)` | `(DeckOptions?) => MusicDeck` | Multiple decks share the engine |\n| `suspend()` / `resume()` | `() => Promise<void>` | Engine-wide pause for the whole context |\n| `tap(handler, options?)` | `(BardEvent) => void` → unsubscribe | Handler errors are swallowed; auto-detaches on `signal` |\n| `dispose()` | `() => void` | Stops voices and decks, aborts loads, removes listeners, closes an owned context; idempotent |\n| `disposed` / `disposalSignal` | `boolean` / `AbortSignal` | Standard disposal contract |\n\n---\n\n## Playback\n\n### SoundHandle\n\nReturned by `play()` and `synth()`.\n\n| Member | Signature | Notes |\n| --------------------------------------------- | -------------------------------- | ------------------------------------------- |\n| `stop(options?)` | `(FadeOptions?) => void` | Fades (default 15 ms micro-fade) then stops |\n| `setVolume(volume, options?)` | `(number, FadeOptions?) => void` | Ramped, never clicks |\n| `setPan(pan)` | `(-1..1) => void` | Every voice has a panner |\n| `finished` | `Promise<void>` | Resolves on natural end, stop, or dispose |\n| `dispose()` / `disposed` / `[Symbol.dispose]` | | Immediate stop and node release |\n\n### PlayOptions\n\n| Option | Type | Default | Notes |\n| ----------------------- | ---------------------- | ------------- | -------------------------------------- |\n| `bus` | `string` | `'sfx'` | Destination bus |\n| `volume` | `number` | `1` | Linear 0..1 |\n| `pan` | `number` | `0` | -1..1; voices always route via a panner |\n| `loop` | `boolean` | `false` | Loops the buffer or sprite region |\n| `loopStart` / `loopEnd` | `number` | — | Absolute buffer seconds |\n| `offset` | `number` | `0` | Start offset in seconds |\n| `detune` | `number \\| [min, max]` | — | Cents; ranges sampled per voice |\n| `rate` | `number \\| [min, max]` | — | Playback rate; shifts pitch on buffers |\n| `maxVoices` | `number` | — | Per-key cap; oldest copy is stolen |\n| `fadeIn` | `number` | — | Seconds from 0 to `volume` |\n| `random` | `() => number` | `Math.random` | Deterministic sampling in tests |\n\n### SynthOptions\n\n| Option | Type | Default | Notes |\n| ---------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------ | --------------------------------------------------------------- |\n| `type` | `'sine' \\| 'square' \\| 'sawtooth' \\| 'triangle' \\| 'noise'` | `'sine'` | `'noise'` uses a cached white-noise buffer |\n| `freq` | `number \\| [from, to]` | `440` | Tuple sweeps exponentially; maps to filter cutoff for `'noise'` |\n| `duration` | `number` | `0.3` | Total seconds including release; must be positive |\n| `envelope` | `SynthEnvelope` | `{ attack: 0.005, decay: 0.05, sustain: 0.6, release: 0.1 }` | ADSR; `sustain` is a level |\n| `filter` | `SynthFilter` | — | Biquad stage before the envelope |\n| `bus` / `volume` / `pan` / `detune` | as in `PlayOptions` | | |\n\n---\n\n## Mixing\n\n### DuckingRule\n\n```ts\ninterface DuckingRule {\n readonly source: string;\n readonly target: string;\n readonly gain: number; // duck level, linear 0..1\n readonly attack?: number; // seconds, default 0.2\n readonly release?: number; // seconds, default 0.8\n}\n```\n\nWhile the `source` bus has active voices, `target` ramps to `gain`; when they end it ramps back to 1. Multiple rules on one target take the lowest active gain.\n\n### BusController\n\n| Member | Notes |\n| ----------------------------------- | -------------------------------------- |\n| `name` | Bus name |\n| `volume` / `setVolume(v, options?)` | User volume stage, ramped |\n| `muted` / `mute()` / `unmute()` | Ramped mute |\n| `duckLevel` | Current duck multiplier (1 = unducked) |\n\n---\n\n## Music Deck\n\n### MusicDeck\n\n| Member | Signature | Notes |\n| --------------------------------------------- | --------------------------------------------- | ----------------------------------------------- |\n| `current` | `string \\| null` | Active track key |\n| `playing` | `boolean` | `false` while paused or stopped |\n| `transition(key, options?)` | `(string, TransitionOptions?) => void` | Crossfades; transitioning to the live key is a no-op |\n| `queue(keys, options?)` | `(readonly string[], QueueOptions?) => void` | Replaces the queue and starts its first track |\n| `next()` / `previous()` | `() => void` | No-op without a queue |\n| `pause()` / `play()` | `() => void` | `play()` resumes from the paused offset |\n| `stop(options?)` | `(FadeOptions?) => void` | Stops and clears queue and slot |\n| `dispose()` / `disposed` / `[Symbol.dispose]` | | Releases a Media Session claim |\n\n`TransitionOptions`: `fade`, `loop`, `loopStart`, `loopEnd`, `offset`.\n`QueueOptions`: `shuffle`, `crossfade`, `repeat`, `random`.\n\n### DeckOptions\n\n| Option | Type | Default | Notes |\n| -------------- | --------- | --------- | ------------------------------------------------------ |\n| `bus` | `string` | `'music'` | Destination bus |\n| `mediaSession` | `boolean` | `false` | Claims `navigator.mediaSession`; a second claim throws |\n| `fade` | `number` | `2` | Default crossfade seconds |\n\n---\n\n## Assets\n\n### AssetManifest\n\n```ts\ntype AssetManifest = Readonly<Record<string, string | AssetDefinition>>;\n\ninterface AssetDefinition {\n readonly src: string;\n readonly sprites?: Readonly<Record<string, readonly [start: number, duration: number]>>;\n readonly stream?: boolean; // deck-only playback via an owned <audio> element\n readonly meta?: AssetMeta; // Media Session metadata\n}\n```\n\nA bare string is shorthand for `{ src }`. Sprite regions are `[startSeconds, durationSeconds]` and play as `'key:sprite'`; out-of-bounds regions throw `BardError`.\n\n---\n\n## Observability\n\n### BardEvent\n\n| Event | Payload | Fires |\n| ------------ | ---------------------- | ---------------------------------------- |\n| `state` | `state` | Context lifecycle changes |\n| `load` | `key` | A manifest entry finished loading |\n| `load-error` | `key`, `error` | A load failed |\n| `steal` | `key` | A voice was stolen past a cap |\n| `duck` | `bus`, `level`, `ramp` | A bus duck level changed |\n| `track` | `key \\| null` | The deck changed tracks |\n| `dispose` | — | Emitted once at the start of `dispose()` |\n\n---\n\n## Testing\n\n`@vielzeug/bard/testing` exports `FakeAudioContext` (manual clock via `advance(seconds)`, recorded `FakeAudioParam` automation), `FakeMediaElement`, `FakeMediaSession`, and `flush()`. Inject the fake with `createBard({ context: () => fake })`.\n\n---\n\n## Errors\n\n| Error | Trigger | Notes |\n| ------------------- | ---------------------------------------------------------------- | --------------------------------------------------------- |\n| `BardError` | Unknown key/bus/sprite, reserved bus name, streamed-asset misuse | Base class |\n| `BardLoadError` | Fetch or `decodeAudioData` failure | `cause` carries the original error or `{ status }` |\n| `BardDisposedError` | Engine use after `dispose()` | Also `BardUnsupportedError` when no `AudioContext` exists |\n",
5
+ "api": "---\ntitle: 'Bard: API Reference'\ndescription: Public API of @vielzeug/bard.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ---------------------- | ------------------------------------------- | --------- | ------------------------------------------------------------------------ |\n| `createBard` | Creates the disposable audio engine | Sync | Context is still created lazily on first audio use |\n| `BardError` | Base error for invalid keys, buses, regions | — | Subclasses: `BardLoadError`, `BardDisposedError`, `BardUnsupportedError` |\n| `BardLoadError` | A manifest entry failed to fetch or decode | — | Original failure is in `cause` |\n| `BardDisposedError` | A method ran after `dispose()` | — | Thrown by every engine method except `dispose` |\n| `BardUnsupportedError` | No `AudioContext` in the runtime | — | `unlock()` rejects with it on servers without Web Audio |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | --------------------------------------- |\n| `@vielzeug/bard` | Complete public Bard API |\n| `@vielzeug/bard/testing` | Deterministic Web Audio fakes for tests |\n\n## Engine\n\n### createBard\n\n```ts\nfunction createBard(options?: BardOptions): Bard;\n```\n\nCreates the engine. Touches no browser global until the first method that needs audio.\n\n| Option | Type | Default | Notes |\n| --------------------- | ------------------------ | --------------------------- | --------------------------------------------------------------------------- |\n| `buses` | `readonly string[]` | `['music', 'sfx', 'voice']` | `'master'` is reserved and throws if declared |\n| `volume` | `number` | `1` | Master volume, linear 0..1 |\n| `ducking` | `readonly DuckingRule[]` | `[]` | See Ducking |\n| `maxVoices` | `number` | `32` | Engine-wide concurrent voice cap |\n| `autoUnlock` | `boolean` | `true` | Gesture listeners resume a suspended context |\n| `autoSuspendOnHidden` | `boolean` | `false` | Suspend on page hide, resume on show (only resumes its own suspends) |\n| `context` | `() => AudioContext` | lazy `new AudioContext()` | Injection seam for tests; injected contexts are never closed by `dispose()` |\n\nReturns the `Bard` engine.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard({ volume: 0.9 });\n```\n\n### Bard\n\n| Member | Signature | Notes |\n| ----------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |\n| `state` | `'idle' \\| 'suspended' \\| 'running' \\| 'interrupted' \\| 'closed'` | `'idle'` until first lazy context creation; `'interrupted'` occurs on iOS calls |\n| `context` | `AudioContext \\| null` | Native context for advanced graph work |\n| `unlock()` | `() => Promise<void>` | Creates and resumes the context |\n| `load(manifest, options?)` | `(AssetManifest, { signal? }) => Promise<void>` | Deduplicates concurrent fetches per URL |\n| `unload(keys?)` | `(string \\| readonly string[]) => void` | Stops active voices for the dropped keys |\n| `has(key)` | `(string) => boolean` | Resolves `'key:sprite'` to its parent asset |\n| `play(key, options?)` | `(string, PlayOptions?) => SoundHandle` | Throws `BardError` for unknown keys and streamed assets |\n| `synth(options)` | `(SynthOptions) => SoundHandle` | Procedural voice, self-cleaning |\n| `bus(name)` | `(string) => BusController` | `'master'` is valid; unknown names throw |\n| `createDeck(options?)` | `(DeckOptions?) => MusicDeck` | Multiple decks share the engine |\n| `suspend()` / `resume()` | `() => Promise<void>` | Engine-wide pause for the whole context |\n| `tap(handler, options?)` | `(BardEvent) => void` → unsubscribe | Handler errors are swallowed; auto-detaches on `signal` |\n| `dispose()` | `() => void` | Stops voices and decks, aborts loads, removes listeners, closes an owned context; idempotent |\n| `disposed` / `disposalSignal` | `boolean` / `AbortSignal` | Standard disposal contract |\n\n---\n\n## Playback\n\n### SoundHandle\n\nReturned by `play()` and `synth()`.\n\n| Member | Signature | Notes |\n| --------------------------------------------- | -------------------------------- | ------------------------------------------- |\n| `stop(options?)` | `(FadeOptions?) => void` | Fades (default 15 ms micro-fade) then stops |\n| `setVolume(volume, options?)` | `(number, FadeOptions?) => void` | Ramped, never clicks |\n| `setPan(pan)` | `(-1..1) => void` | Every voice has a panner |\n| `finished` | `Promise<void>` | Resolves on natural end, stop, or dispose |\n| `dispose()` / `disposed` / `[Symbol.dispose]` | | Immediate stop and node release |\n\n### PlayOptions\n\n| Option | Type | Default | Notes |\n| ----------------------- | ---------------------- | ------------- | --------------------------------------- |\n| `bus` | `string` | `'sfx'` | Destination bus |\n| `volume` | `number` | `1` | Linear 0..1 |\n| `pan` | `number` | `0` | -1..1; voices always route via a panner |\n| `loop` | `boolean` | `false` | Loops the buffer or sprite region |\n| `loopStart` / `loopEnd` | `number` | — | Absolute buffer seconds |\n| `offset` | `number` | `0` | Start offset in seconds |\n| `detune` | `number \\| [min, max]` | — | Cents; ranges sampled per voice |\n| `rate` | `number \\| [min, max]` | — | Playback rate; shifts pitch on buffers |\n| `maxVoices` | `number` | — | Per-key cap; oldest copy is stolen |\n| `fadeIn` | `number` | — | Seconds from 0 to `volume` |\n| `random` | `() => number` | `Math.random` | Deterministic sampling in tests |\n\n### SynthOptions\n\n| Option | Type | Default | Notes |\n| ----------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------ | --------------------------------------------------------------- |\n| `type` | `'sine' \\| 'square' \\| 'sawtooth' \\| 'triangle' \\| 'noise'` | `'sine'` | `'noise'` uses a cached white-noise buffer |\n| `freq` | `number \\| [from, to]` | `440` | Tuple sweeps exponentially; maps to filter cutoff for `'noise'` |\n| `duration` | `number` | `0.3` | Total seconds including release; must be positive |\n| `envelope` | `SynthEnvelope` | `{ attack: 0.005, decay: 0.05, sustain: 0.6, release: 0.1 }` | ADSR; `sustain` is a level |\n| `filter` | `SynthFilter` | — | Biquad stage before the envelope |\n| `bus` / `volume` / `pan` / `detune` | as in `PlayOptions` | | |\n\n---\n\n## Mixing\n\n### DuckingRule\n\n```ts\ninterface DuckingRule {\n readonly source: string;\n readonly target: string;\n readonly gain: number; // duck level, linear 0..1\n readonly attack?: number; // seconds, default 0.2\n readonly release?: number; // seconds, default 0.8\n}\n```\n\nWhile the `source` bus has active voices, `target` ramps to `gain`; when they end it ramps back to 1. Multiple rules on one target take the lowest active gain.\n\n### BusController\n\n| Member | Notes |\n| ----------------------------------- | -------------------------------------- |\n| `name` | Bus name |\n| `volume` / `setVolume(v, options?)` | User volume stage, ramped |\n| `muted` / `mute()` / `unmute()` | Ramped mute |\n| `duckLevel` | Current duck multiplier (1 = unducked) |\n\n---\n\n## Music Deck\n\n### MusicDeck\n\n| Member | Signature | Notes |\n| --------------------------------------------- | -------------------------------------------- | ---------------------------------------------------- |\n| `current` | `string \\| null` | Active track key |\n| `playing` | `boolean` | `false` while paused or stopped |\n| `transition(key, options?)` | `(string, TransitionOptions?) => void` | Crossfades; transitioning to the live key is a no-op |\n| `queue(keys, options?)` | `(readonly string[], QueueOptions?) => void` | Replaces the queue and starts its first track |\n| `next()` / `previous()` | `() => void` | No-op without a queue |\n| `pause()` / `play()` | `() => void` | `play()` resumes from the paused offset |\n| `stop(options?)` | `(FadeOptions?) => void` | Stops and clears queue and slot |\n| `dispose()` / `disposed` / `[Symbol.dispose]` | | Releases a Media Session claim |\n\n`TransitionOptions`: `fade`, `loop`, `loopStart`, `loopEnd`, `offset`.\n`QueueOptions`: `shuffle`, `crossfade`, `repeat`, `random`.\n\n### DeckOptions\n\n| Option | Type | Default | Notes |\n| -------------- | --------- | --------- | ------------------------------------------------------ |\n| `bus` | `string` | `'music'` | Destination bus |\n| `mediaSession` | `boolean` | `false` | Claims `navigator.mediaSession`; a second claim throws |\n| `fade` | `number` | `2` | Default crossfade seconds |\n\n---\n\n## Assets\n\n### AssetManifest\n\n```ts\ntype AssetManifest = Readonly<Record<string, string | AssetDefinition>>;\n\ninterface AssetDefinition {\n readonly src: string;\n readonly sprites?: Readonly<Record<string, readonly [start: number, duration: number]>>;\n readonly stream?: boolean; // deck-only playback via an owned <audio> element\n readonly meta?: AssetMeta; // Media Session metadata\n}\n```\n\nA bare string is shorthand for `{ src }`. Sprite regions are `[startSeconds, durationSeconds]` and play as `'key:sprite'`; out-of-bounds regions throw `BardError`.\n\n---\n\n## Observability\n\n### BardEvent\n\n| Event | Payload | Fires |\n| ------------ | ---------------------- | ---------------------------------------- |\n| `state` | `state` | Context lifecycle changes |\n| `load` | `key` | A manifest entry finished loading |\n| `load-error` | `key`, `error` | A load failed |\n| `steal` | `key` | A voice was stolen past a cap |\n| `duck` | `bus`, `level`, `ramp` | A bus duck level changed |\n| `track` | `key \\| null` | The deck changed tracks |\n| `dispose` | — | Emitted once at the start of `dispose()` |\n\n---\n\n## Testing\n\n`@vielzeug/bard/testing` exports `FakeAudioContext` (manual clock via `advance(seconds)`, recorded `FakeAudioParam` automation), `FakeMediaElement`, `FakeMediaSession`, and `flush()`. Inject the fake with `createBard({ context: () => fake })`.\n\n---\n\n## Errors\n\n| Error | Trigger | Notes |\n| ------------------- | ---------------------------------------------------------------- | --------------------------------------------------------- |\n| `BardError` | Unknown key/bus/sprite, reserved bus name, streamed-asset misuse | Base class |\n| `BardLoadError` | Fetch or `decodeAudioData` failure | `cause` carries the original error or `{ status }` |\n| `BardDisposedError` | Engine use after `dispose()` | Also `BardUnsupportedError` when no `AudioContext` exists |\n",
6
6
  "usage": "---\ntitle: 'Bard: Usage Guide'\ndescription: Play sounds, mix buses with ducking, generate synth SFX, and crossfade music with @vielzeug/bard.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate one engine per app, load a manifest, and play through a bus. Dispose the engine when its owning feature unmounts.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard();\nawait bard.load({ click: '/click.wav', boom: '/boom.wav' });\n\nconst handle = bard.play('boom', { volume: 0.8, pan: -0.3 });\nawait handle.finished;\nbard.dispose();\n```\n\n`play()` returns a `SoundHandle` immediately; audio starts once the browser allows it. `finished` resolves when the voice ends, is stopped, or is disposed.\n\n## Unlocking Audio\n\nBrowsers start the `AudioContext` suspended until a user gesture. Bard attaches capture-phase listeners for `pointerup`, `touchend`, `keydown`, and `click` and resumes the context inside the first one. All listeners are removed once the context is running.\n\n```ts\nconst bard = createBard(); // listeners attach on first audio use\nawait bard.unlock(); // or resume programmatically inside your own handler\n```\n\n`autoUnlock: false` skips the gesture listeners entirely; call `resume()` from your own gesture handler instead.\n\n## Buses and Volume\n\nVoices route to a named bus: `voice -> [pan] -> bus -> master -> destination`. The defaults are `music`, `sfx`, and `voice`; override with `buses`. Volume changes always ramp, so they never click.\n\n```ts\nconst music = bard.bus('music');\nmusic.setVolume(0.6, { fade: 0.5 });\nmusic.mute();\nmusic.unmute();\n```\n\n`bard.bus('master')` controls the output stage for every bus.\n\n## Ducking\n\nA ducking rule ramps a target bus down while the source bus has active voices, and back up when they end. Narration over music is the canonical case.\n\n```ts\nconst bard = createBard({\n ducking: [{ source: 'voice', target: 'music', gain: 0.3, attack: 0.2, release: 0.8 }],\n});\n\nawait bard.load({ announce: '/announce.wav' });\nconst voice = bard.play('announce', { bus: 'voice' });\n// music is now at 30% until the announcement ends\nawait voice.finished; // music ramps back to 100%\n```\n\nDucking uses its own gain stage per bus, so it never fights user volume automation.\n\n## Sound Sprites\n\nBundle many short SFX into one file and address regions with `key:sprite`. The region is `[startSeconds, durationSeconds]`.\n\n```ts\nawait bard.load({\n ui: { src: '/ui.wav', sprites: { open: [0, 0.4], close: [0.5, 0.4] } },\n});\n\nbard.play('ui:open');\nbard.play('ui:close', { bus: 'sfx' });\n```\n\n## Voice Caps and Variance\n\n`maxVoices` caps concurrent copies of one key; the oldest copy is stolen with a micro-fade. The engine-wide cap is `maxVoices` in `createBard` (default 32). Ranges for `detune` and `rate` keep repeated hits from sounding identical.\n\n```ts\nfor (let i = 0; i < 10; i += 1) {\n bard.play('ui:open', { maxVoices: 3, detune: [-100, 100], rate: [0.95, 1.05] });\n}\n```\n\nNote: `rate` shifts pitch on buffer sources. Pitch-preserving playback belongs on a streamed `HTMLAudioElement`.\n\n## Procedural Synth\n\n`synth()` builds an oscillator or noise burst with an ADSR envelope and optional filter, and disconnects itself when done. No assets required.\n\n```ts\n// countdown tick\nbard.synth({ type: 'square', freq: 880, duration: 0.08 });\n\n// descending error buzz with a lowpass\nbard.synth({\n type: 'sawtooth',\n freq: [220, 55],\n duration: 0.6,\n filter: { type: 'lowpass', frequency: [2400, 400] },\n});\n```\n\n## Music Deck\n\nA deck crossfades between two slots. Transition to game states, loop the body of a track after its intro, or queue continuous playback.\n\n```ts\nconst deck = bard.createDeck({ fade: 2.5 });\n\n// intro plays once, then the region loops seamlessly\ndeck.transition('bossTheme', { loop: true, loopStart: 12.5 });\n\n// later: crossfade to the victory track\ndeck.transition('victory', { fade: 4 });\n\n// continuous ambient playback with deterministic shuffle\ndeck.queue(['forest', 'cave', 'village'], { shuffle: true, crossfade: 6, repeat: true });\ndeck.next();\n```\n\n`pause()` then `play()` resumes from the paused position. A manual `transition()` takes over from the queue.\n\n## Streaming Long Tracks\n\nMark an asset `stream: true` to play it through an owned `<audio>` element instead of decoding it into an `AudioBuffer`. Mobile devices never spike RAM on ten-minute ambient tracks. Streamed assets are deck-only; `play()` on them throws.\n\n```ts\nawait bard.load({\n ambient: { src: 'https://cdn.example.com/forest.mp3', stream: true },\n});\nbard.createDeck().transition('ambient', { loop: true });\n```\n\nThe element requests CORS (`crossOrigin: 'anonymous'`); a CDN without CORS headers plays silent through Web Audio. Streamed loops cover the whole file: `loopStart`/`loopEnd` throw.\n\n## Media Session\n\n`mediaSession: true` claims `navigator.mediaSession` for one deck: metadata from the asset's `meta`, hardware play/pause/next/previous. A second claim throws instead of stealing controls; disposing the deck releases the claim.\n\n```ts\nawait bard.load({\n theme: { src: '/theme.mp3', meta: { title: 'Hunt Theme', artist: 'Bard' } },\n});\nconst deck = bard.createDeck({ mediaSession: true });\ndeck.transition('theme');\n```\n\n## Testing\n\n`@vielzeug/bard/testing` ships deterministic fakes: a context with a manual clock, recorded param automation, and fake media elements. Bard's own suite uses them.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\nimport { FakeAudioContext } from '@vielzeug/bard/testing';\n\nconst ctx = new FakeAudioContext();\nconst bard = createBard({ context: () => ctx });\nawait bard.load({ ping: '/ping.wav' });\nbard.play('ping');\nctx.advance(2); // clock moves, sources past their stop time fire 'ended'\n```\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useState } from 'react';\nimport { createBard, type Bard } from '@vielzeug/bard';\n\nexport function useBard() {\n const [bard, setBard] = useState<Bard | null>(null);\n useEffect(() => {\n const engine = createBard();\n setBard(engine);\n return () => engine.dispose();\n }, []);\n return bard;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, shallowRef } from 'vue';\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = shallowRef<ReturnType<typeof createBard> | null>(null);\nonMounted(() => (bard.value = createBard()));\nonUnmounted(() => bard.value?.dispose());\n</script>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { createBard } from '@vielzeug/bard';\n import { onDestroy } from 'svelte';\n\n const bard = createBard();\n onDestroy(() => bard.dispose());\n</script>\n```\n\n:::\n\nCreate the engine in a mount hook, not at module scope: only mount lifecycle proves a browser runtime exists.\n\n## Best Practices\n\n- Create one engine per app and pass it down; contexts are a limited hardware resource.\n- Dispose the engine with its owning feature; `using` works via `Symbol.dispose`.\n- Keep streamed assets for tracks longer than a few minutes; buffers are better for SFX.\n- Give narration its own `voice` bus and duck `music` from it, rather than fading tracks by hand.\n- Inject `random` in tests so detune, rate, and shuffle are deterministic.\n- Watch `tap()` events (`steal`, `duck`, `load-error`) in development to catch mixing problems early.\n- Call `unlock()` from your own first-gesture UI when you want audio live before the next interaction.\n",
7
7
  "examples": "---\ntitle: 'Bard Examples'\ndescription: Practical sound, ducking, and music-transition recipes for @vielzeug/bard.\n---\n\n## Examples\n\n- [Game-State Music Transitions](./examples/game-state-music-transitions.md)\n- [Duck Music Under Narration](./examples/duck-music-under-narration.md)\n- [UI SFX Without Assets](./examples/ui-sfx-without-assets.md)\n"
8
8
  },
@@ -2,8 +2,8 @@
2
2
  "apiSource": "// Full API aggregate and IIFE bundle entry. For tree-shaken imports prefer the\n// `@vielzeug/dnd/drop` and `@vielzeug/dnd/sortable` subpaths.\nexport * from './drop-zone.js';\nexport { DndError, DndScopeError } from './errors.js';\nexport * from './sortable.js';\nexport * from './types.js';\n",
3
3
  "docs": {
4
4
  "index": "---\ntitle: 'Dnd: Drag-and-drop primitives for the DOM'\ndescription: 'Framework-agnostic drag-and-drop. Drop zones with MIME filtering, sortable lists with drag handles, and explicit connected scopes: zero third-party dependencies.'\npackage: dnd\ncategory: ui-interaction\nkeywords: [drag-drop, sortable, file-upload, drop-zone, dnd, reorder]\nrelated: [gesture, ore, scroll, refine]\nexports: [createDropZone, createSortable, createSortableScope, applyReorder, matchesAccept]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"dnd\" />\n\n## Why Dnd?\n\nThe HTML5 Drag & Drop API requires careful counter tracking to avoid hover state flicker, has no MIME type pre-filtering, and provides no sortable list abstraction.\n\n```ts\n// Before: raw HTML5 Drag & Drop\nlet enterCount = 0;\ndropzone.addEventListener('dragenter', () => {\n enterCount++;\n dropzone.classList.add('over');\n});\ndropzone.addEventListener('dragleave', () => {\n if (--enterCount === 0) dropzone.classList.remove('over');\n});\ndropzone.addEventListener('dragover', (e) => e.preventDefault());\ndropzone.addEventListener('drop', (e) => {\n e.preventDefault();\n enterCount = 0;\n const files = [...e.dataTransfer!.files];\n if (!files.every((f) => f.type.startsWith('image/'))) return showError('Images only');\n uploadFiles(files);\n});\n\n// After: Dnd\nimport { createDropZone } from '@vielzeug/dnd/drop';\nconst zone = createDropZone({\n element: dropzone,\n accept: ['image/*'],\n onDrop: (files) => uploadFiles(files),\n onDropRejected: (files) => showError(`${files.length} file(s) not accepted`),\n onHoverChange: (hovered) => dropzone.classList.toggle('over', hovered),\n});\n```\n\n| Feature | DND | SortableJS | dnd-kit |\n| ----------------------------- | ---------------------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"dnd\" type=\"size\" /> | ~15 kB | ~30 kB |\n| Framework agnostic | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| MIME type filtering | <ore-icon name=\"check\" size=\"16\"></ore-icon> Pre-validated | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Counter-based hover | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | N/A |\n| Sortable lists | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Drag handles | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| `using` support | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Touch support | <ore-icon name=\"check\" size=\"16\"></ore-icon> Scoped opt-in | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Zero third-party dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Dnd when** an item is picked up and dropped: file drop zones, sortable collections, keyboard reordering, or connected lists.\n\n**Use Gesture instead** when a surface follows free or axis-locked pointer movement and application code owns rendering and completion, such as direct manipulation, swipe reveal, carousel navigation, or drawer dismissal.\n\n**Consider dnd-kit** if you are building a React app and need complex multi-container drag interactions or accessibility-first sortable trees.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/dnd\n```\n\n```sh [npm]\nnpm install @vielzeug/dnd\n```\n\n```sh [yarn]\nyarn add @vielzeug/dnd\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createDropZone } from '@vielzeug/dnd/drop';\nimport { createSortable } from '@vielzeug/dnd/sortable';\n\n// File drop zone: with async validation and paste support\nconst dropzone = document.getElementById('dropzone')!;\n\nusing zone = createDropZone({\n element: dropzone,\n accept: ['image/*', '.pdf'],\n paste: true,\n onValidate: (files) => files.every((file) => file.size <= 5_000_000),\n onDrop: (files) => console.log('Upload', files),\n onDropRejected: (files) => {\n console.warn(`${files.length} file(s) rejected`);\n },\n onHoverChange: (hovered) => {\n dropzone.classList.toggle('drag-over', hovered);\n },\n});\n\n// Sortable list: with application-owned rollback for optimistic updates\nlet currentOrder = ['a', 'b', 'c'];\nconst history: Array<{ before: readonly string[] }> = [];\n\nusing sortable = createSortable({\n element: document.getElementById('list')!,\n keyboard: true,\n onBeforeReorder: (from, to) => {\n // record positions here before the DOM commits (for FLIP animations)\n },\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ before, after }) => {\n history.push({ before });\n currentOrder = after;\n },\n});\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **Counter-based hover state**: `onHoverChange` stays accurate when dragging over child elements; hover only activates when the drag payload passes the `accept` filter, with symmetric enter/leave pairing to prevent flicker\n- **MIME type pre-validation**: queries `dataTransfer.items` during drag to set `dropEffect='none'` before the drop; confirmed against `File.type` on drop\n- **Flexible accept patterns**: MIME types (`image/png`), wildcards (`image/*`), and file extensions (`.pdf`)\n- **`maxFiles` limit**: cap the number of accepted files per drop; excess files are forwarded to `onDropRejected`\n- **`onValidate` async gating**: optional cancellable async step after type filtering; `zone.validating` remains `true` until every pending validation settles\n- **Clipboard paste support**: `paste: true` routes pasted files through the same `accept`, `maxFiles`, and `onValidate` pipeline; `onPaste` provides a separate callback; paste rejections are forwarded to `onDropRejected` with the same `(files: File[]) => void` signature as drop rejections\n- **`onDropRejected`**: separate callback for files that didn't match `accept`, exceeded `maxFiles`, or were rejected by `onValidate`\n- **Sortable lists**: reorders DOM children with a placeholder indicator; fires `onReorder` only when the order actually changes\n- **Drag handles**: scope dragging to a child selector via `handle`; whole item is draggable when omitted\n- **Custom drag preview**: pass an element or a `(id, item, event) => element | null` factory; control hotspot with `dragImageOffset`\n- **`onBeforeReorder` FLIP hook**: fires before commit for both drag and keyboard moves; pair it with [`captureLayout()`](/necromancer/api.md#capturelayout) for lifecycle-owned FLIP animation\n- **Application-owned rollback**: `onReorder` emits `{ before, after, item }` so application history can own undo/rollback instead of the drag controller\n- **Boundary-safe keyboard reordering**: arrow keys at the first/last item no longer suppress `preventDefault`, so the browser can scroll the page normally\n- **Transactional connected scopes**: one `onMove` callback receives each cross-list transfer with both final orders\n- **Scoped touch support**: `createSortableScope({ touch: true })` handles only items registered to that scope and uses an inert outline preview\n- **Explicit DOM refresh**: call `sortable.refresh()` after DOM mutations, or provide an `items()` provider for explicit item ownership\n- **`[Symbol.dispose]`**: both primitives support the `using` keyword for automatic cleanup\n- **Reactive-friendly options**: `disabled` is re-read on each event (reassign `options.disabled = true` to toggle); `accept` is normalized and snapshotted at construction; recreate the zone to change accepted types\n- **Shared pointer recognition**: touch sorting uses `@vielzeug/gesture`; Dnd retains previews, hit-testing, drag events, and sortable transactions\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- [Orbit](/orbit/): floating element positioning; use alongside Dnd to anchor drag previews and drop-zone indicators to precise positions\n- [Gesture](/gesture/): pointer recognition used by Dnd touch sorting and directly by swipe, reveal, carousel, and drawer interactions\n- [Ore](/ore/): web-component authoring framework for application-owned draggable and sortable surfaces\n- [Refine](/refine/): accessible web components; Dnd powers Refine's file-drop input behavior\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Dnd: API Reference'\ndescription: Complete API reference for Dnd.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------------------- | -------------------------------------------- | -------------- | ----------------------------------------------------------------- |\n| `createDropZone()` | Create a typed drop-zone controller | Sync | Dispose the controller during teardown |\n| `createSortable()` | Add sortable drag-and-drop behavior to lists | Sync | Provide stable item identity for reorder operations |\n| `createSortableScope()` | Create a shared scope for connected lists | Sync | Each set of connected containers needs its own scope instance |\n| `applyReorder()` | Apply ordered IDs to data arrays | Sync | Unknown IDs are skipped; non-mentioned items are appended |\n| `DropZoneOptions.accept` | Filter file types before processing | Sync | Mismatch between MIME and extension can reject files unexpectedly |\n| `DropZoneOptions.maxFiles` | Cap accepted files per drop | Sync | Excess accepted files become rejected; `onDropRejected` is called |\n| `matchesAccept()` | Test a single `File` against an accept list | Sync | Extension patterns are case-insensitive; empty list accepts all |\n| `DndError` | Base class for Dnd errors | Sync | Use `instanceof DndError` to narrow unknown errors |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | ---------------------------------------------------------------- |\n| `@vielzeug/dnd` | Backward-compat root barrel |\n| `@vielzeug/dnd/drop` | Drop-zone APIs plus `DndError` and `Disposable` |\n| `@vielzeug/dnd/sortable` | Sortable APIs plus `DndError`, `DndScopeError`, and `Disposable` |\n\nDnd has no third-party runtime dependencies. Its sortable touch adapter uses `@vielzeug/gesture` for shared pointer recognition.\n\n## Types\n\n### `Disposable`\n\n```ts\ninterface Disposable {\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n```\n\n### `DropZoneOptions`\n\n```ts\ninterface DropZoneOptions {\n element: HTMLElement;\n accept?: readonly string[];\n maxFiles?: number;\n onValidate?: (files: File[], context: DropValidationContext) => boolean | Promise<boolean>;\n disabled?: boolean;\n dropEffect?: DataTransfer['dropEffect'];\n onDrop?: (files: File[]) => void;\n onDropRejected?: (files: File[]) => void;\n onHoverChange?: (hovered: boolean) => void;\n onValidatingChange?: (validating: boolean) => void;\n paste?: boolean;\n onPaste?: (files: File[]) => void;\n}\n```\n\n### `DropZone`\n\n```ts\ninterface DropZone extends Disposable {\n readonly hovered: boolean;\n readonly validating: boolean;\n}\n```\n\n### `DropValidationContext`\n\n```ts\ninterface DropValidationContext {\n readonly signal: AbortSignal;\n}\n```\n\n### `SortableOptions`\n\n```ts\ninterface SortableOptions {\n element: HTMLElement;\n getKey: (element: HTMLElement) => string;\n scope?: SortableScope;\n handle?: string;\n keyboard?: boolean;\n axis?: 'vertical' | 'horizontal';\n autoScroll?: boolean | AutoScrollOptions;\n dragImage?: HTMLElement | ((id: string, item: HTMLElement, event: DragEvent) => HTMLElement | null | undefined);\n dragImageOffset?: [number, number];\n placeholderClass?: string;\n disabled?: boolean;\n onDragStart?: (id: string, event: DragEvent) => void;\n onDragEnd?: (id: string, event: DragEvent) => void;\n onInteraction?: (event: SortableInteractionEvent) => void;\n onBeforeReorder?: (from: readonly string[], to: readonly string[]) => void;\n onReorder?: (event: ReorderEvent) => void;\n items?: () => readonly HTMLElement[];\n}\n```\n\n### `AutoScrollOptions`\n\n```ts\ninterface AutoScrollOptions {\n edgeThreshold?: number;\n speed?: number;\n container?: boolean;\n viewport?: boolean;\n}\n```\n\n### `ReorderEvent`\n\n```ts\ninterface ReorderEvent {\n before: readonly string[];\n after: readonly string[];\n item: string;\n}\n```\n\n### `Sortable`\n\n```ts\ninterface Sortable extends Disposable {\n readonly isDragging: boolean;\n refresh(): void;\n}\n```\n\n### `SortableScope`\n\n```ts\ninterface SortableScope extends Disposable {\n readonly isDragging: boolean;\n}\n```\n\n### `SortableScopeOptions`\n\n```ts\ninterface SortableScopeOptions {\n onMove?: (event: SortableMoveEvent) => void;\n touch?: boolean | SortableTouchOptions;\n}\n```\n\n### `SortableMoveEvent`\n\n```ts\ninterface SortableMoveEvent {\n readonly itemId: string;\n readonly source: HTMLElement;\n readonly sourceBeforeIds: readonly string[];\n readonly sourceIds: readonly string[];\n readonly target: HTMLElement;\n readonly targetBeforeIds: readonly string[];\n readonly targetIds: readonly string[];\n}\n```\n\n### `SortableInteractionEvent`\n\nStructured accessibility/observability event for sortable interactions. Drag emits `pickup` on dragstart, `drop` on commit, `cancel` on cancel. Keyboard emits `move` on each successful arrow/Home/End reorder (direct-commit model).\n\n```ts\ntype SortableInteractionEvent =\n | { readonly type: 'pickup'; readonly itemId: string; readonly index: number; readonly total: number }\n | {\n readonly type: 'move';\n readonly itemId: string;\n readonly previousIndex: number;\n readonly index: number;\n readonly total: number;\n }\n | { readonly type: 'drop'; readonly itemId: string; readonly index: number; readonly total: number }\n | { readonly type: 'cancel'; readonly itemId: string; readonly index: number; readonly total: number };\n```\n\nWire a consumer-side announcer to provide screen-reader feedback:\n\n```ts\nimport { createSortable } from '@vielzeug/dnd/sortable';\n\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.id!,\n onInteraction(event) {\n switch (event.type) {\n case 'pickup':\n announce(`Picked up ${event.itemId}, position ${event.index + 1} of ${event.total}`);\n break;\n case 'move':\n announce(`Moved ${event.itemId} to position ${event.index + 1} of ${event.total}`);\n break;\n case 'drop':\n announce(`Dropped ${event.itemId} at position ${event.index + 1} of ${event.total}`);\n break;\n case 'cancel':\n announce(`Cancelled, ${event.itemId} returned to position ${event.index + 1} of ${event.total}`);\n break;\n }\n },\n});\n```\n\n### `SortableTouchOptions`\n\n```ts\ntype SortableTouchOptions = Readonly<{\n activationDistance?: number;\n preview?: false | ((item: HTMLElement) => HTMLElement | null);\n}>;\n```\n\n`activationDistance` is the non-negative finite movement threshold in pixels before touch sorting starts (default `6`). Invalid values throw `DndError`.\n\n`preview` returns a template that Dnd clones before mounting it as a transient touch preview, so returning an element from the sortable item does not reparent or remove caller-owned DOM. Return `false` to disable the preview.\n\nTouch sorting delegates one-pointer activation, movement, identity, and cancellation to Gesture's `createDragGesture()` with pointer capture disabled for document hit-testing. Dnd retains preview rendering, hit-testing, synthetic drag events, and sortable transactions. Non-primary pointers are ignored, and cancellation restores the pre-drag order without firing `onReorder`.\n\n## `createDropZone()`\n\n```ts\ndeclare function createDropZone(options: DropZoneOptions): DropZone;\n```\n\nAttaches drag-and-drop file handling to a DOM element. Returns a `DropZone` handle.\n\n| Option | Type | Default | Description |\n| -------------------- | ---------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `element` | `HTMLElement` | N/A | **Required.** The element to attach drag listeners to. |\n| `accept` | `string[]` | `[]` | Accepted file types, normalized and snapshotted at construction. Empty array accepts everything; invalid MIME, wildcard, or extension patterns throw `DndError`. |\n| `maxFiles` | `number` | N/A | Non-negative safe-integer file limit. Excess files are passed to `onDropRejected`; invalid values throw `DndError` during construction. |\n| `onValidate` | `(files, { signal }) => boolean \\| Promise<boolean>` | N/A | Optional async gating step. Return or resolve `false` to reject all accepted files. `validating` remains true until every operation settles; `signal` aborts on disposal. |\n| `disabled` | `boolean` | N/A | When `true`, all drag and paste events are ignored. A disabled zone does not call `preventDefault` on `dragenter`, `dragover`, `drop`, or `paste`, so underlying elements (text editors, etc.) receive them normally. |\n| `dropEffect` | `'copy' \\| 'move' \\| 'link' \\| 'none'` | `'copy'` | The `dropEffect` set on `dataTransfer` during `dragover`. Controls the cursor indicator. |\n| `onDrop` | `(files: File[]) => void` | N/A | Called with accepted files only. Not called if all dropped files are rejected. Also receives paste events when `paste: true` and `onPaste` is omitted. |\n| `onDropRejected` | `(files: File[]) => void` | N/A | Called with files that did not match `accept`, exceeded `maxFiles`, or were rejected by `onValidate`. |\n| `onHoverChange` | `(hovered: boolean) => void` | N/A | Called when hover state toggles. Use this callback for drag-over styling. |\n| `onValidatingChange` | `(validating: boolean) => void` | N/A | Called whenever the aggregate async validation state changes. |\n| `paste` | `boolean` | `false` | When `true`, attaches a `paste` listener to `element`. Pasted files run through the same `accept`, `maxFiles`, and `onValidate` pipeline as dropped files. |\n| `onPaste` | `(files: File[]) => void` | N/A | Called when files are pasted from the clipboard. Falls back to `onDrop` when omitted. Only active when `paste: true`. |\n\n**Returns:** `DropZone`\n\nNotes:\n\n- Extension accept patterns are approximate during pre-check (`DataTransferItem` has no filename); exact filtering is applied at drop time.\n- Hover state (`hovered`) only becomes `true` when the dragged payload passes the `accept` filter. Drags carrying rejected file types enter and leave the zone without triggering `onHoverChange`.\n- Hover state is reset on element drop and also global `window` `drop`/`dragend` to avoid stuck hover state when drags leave the viewport.\n- Disposal aborts validation and transitions `validating` to `false` before teardown completes.\n- Consumer callback failures are reported through Dnd's development warning channel and never reclassify accepted files as rejected.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*', '.pdf'],\n onDrop: (files) => {\n upload(files);\n },\n onDropRejected: (files) => {\n showError(`${files.length} rejected`);\n },\n onHoverChange: (hovered) => {\n dropEl.classList.toggle('drag-over', hovered);\n },\n});\n```\n\n## `DropZone` Interface\n\n### `zone.hovered`\n\n`readonly hovered: boolean`\n\n`true` when a drag is currently over the zone. Updated synchronously by the internal counter: safe to read at any time.\n\n### `zone.validating`\n\n`readonly validating: boolean`\n\n`true` while an `onValidate` promise is pending. Use this to render a loading indicator between file selection and the acceptance/rejection callbacks firing.\n\n```ts\nconsole.log(zone.validating); // true between drop and onValidate resolution\n```\n\n### `zone.disposed`\n\n`readonly disposed: boolean`\n\n`true` once `dispose()` has been called. Safe to read at any time.\n\n### `zone.disposalSignal`\n\n`readonly disposalSignal: AbortSignal`\n\nAn `AbortSignal` that fires when `dispose()` is called. Use it to cancel in-flight requests tied to the zone's lifetime.\n\n### `zone.dispose()`\n\n`dispose(): void`\n\nRemoves all event listeners, aborts pending validation, and resets `hovered` and `validating`. Idempotent: safe to call multiple times.\n\n```ts\nzone.dispose();\n```\n\n### `zone[Symbol.dispose]()`\n\n`[Symbol.dispose](): void`\n\nAlias for `dispose()`. Called automatically when used with the `using` keyword.\n\n```ts\n{\n using zone = createDropZone({ element: dropEl, onDrop: handleFiles });\n} // zone.dispose() runs here\n```\n\n## `createSortable()`\n\n```ts\ndeclare function createSortable(options: SortableOptions): Sortable;\n```\n\nMakes the direct children of a container element reorderable via drag. Returns a `Sortable` handle.\n\n`createSortable` adds drag and keyboard defaults only when callers have not already supplied semantics. Every changed attribute and inline style is restored to its prior value on disposal.\n\n- `element`: `HTMLElement`, required. The container whose children become sortable.\n- `getKey`: `(element: HTMLElement) => string`, required. Maps each item element to its stable string identity. Children for which `getKey` returns a falsy value are skipped.\n- `scope`: `SortableScope`, default private scope. Connects sortable lists explicitly; containers only exchange items when they share the same scope instance.\n- `handle`: `string`. Valid CSS selector for a drag handle inside each item. Invalid selectors throw `DndError`; an empty selector warns and disables dragging.\n- `keyboard`: `boolean`, default `true`. Enables keyboard reordering with arrow keys plus `Home` and `End`, matched through `matchKey` from `@vielzeug/keymap`: modifier chords (e.g. Ctrl+ArrowDown, browser back/forward) are ignored. Events from interactive descendants are ignored unless they match the configured handle.\n- `axis`: `'vertical' | 'horizontal'`, default `'vertical'`. Controls midpoint calculation for placeholder insertion.\n- `autoScroll`: `boolean | AutoScrollOptions`, default `true`. Scrolls near edges; threshold must be finite and non-negative and speed finite and positive.\n- `dragImage`: `HTMLElement | ((id, item, event) => HTMLElement | null | undefined)`. Custom native drag preview passed to `dataTransfer.setDragImage()`. A `null` or `undefined` return skips `setDragImage` entirely.\n- `dragImageOffset`: `[number, number]`, default `[0, 0]`. The `[x, y]` hotspot offset passed to `setDragImage`. Controls which point of the preview image follows the cursor.\n- `placeholderClass`: `string`, default `'dnd-placeholder'`. CSS class applied to the generated placeholder element.\n- `disabled`: `boolean`. Blocks drag interactions. If a list becomes disabled mid-drag, Dnd cancels the drag and restores the original order.\n- `onDragStart`: `(id: string, event: DragEvent) => void`. Called when a drag starts.\n- `onDragEnd`: `(id: string, event: DragEvent) => void`. Called when a drag ends, whether completed or cancelled.\n- `onInteraction`: `(event: SortableInteractionEvent) => void`. Structured accessibility event for pickup/move/drop/cancel: wire to a consumer-side announcer for screen-reader feedback. See [`SortableInteractionEvent`](#sortableinteractionevent).\n- `onBeforeReorder`: `(from: readonly string[], to: readonly string[]) => void`. Called with the before/after order snapshots just before a successful reorder commits: for both drag and keyboard. Items are still in their pre-commit positions at the time of the call, making it ideal for [`captureLayout()`](/necromancer/api.md#capturelayout) setup.\n- `items`: `() => readonly HTMLElement[]`. Returns direct children owned by this sortable. `refresh()` restores elements no longer returned before marking the current set.\n- `onReorder`: `(event: ReorderEvent) => void`. Called after a successful reorder (drag or keyboard), only when the order changed. The event carries `before`, `after`, and `item` so application history can own rollback.\n\nOrder arrays and interaction events are frozen snapshots. Callback failures are reported through Dnd's development warning channel and cannot interrupt session completion or corrupt later events. Native touch scrolling is preserved unless the shared scope enables touch input.\n\n**Returns:** `Sortable`\n\n```ts\nconst boardScope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => saveMove(itemId, sourceIds, targetIds),\n touch: true,\n});\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.id!,\n handle: '.drag-handle',\n onDragStart: (id) => {\n listEl.classList.add('sorting');\n },\n onDragEnd: (id) => {\n listEl.classList.remove('sorting');\n },\n onReorder: ({ before, after }) => {\n history.push({ revert: () => saveOrder(before) });\n saveOrder(after);\n },\n scope: boardScope,\n});\n```\n\n### `createSortableScope()`\n\n```ts\ndeclare function createSortableScope(options?: SortableScopeOptions): SortableScope;\n```\n\nUse one scope per connected set of containers. `onMove` fires once for cross-list moves with both final orders; local reorders continue to call the sortable's `onReorder`.\n\n| Parameter | Type | Description |\n| --------- | ---------------------- | --------------------------------------------------------------------- |\n| `options` | `SortableScopeOptions` | Optional cross-list move callback and scope-owned touch configuration |\n\n**Returns:** `SortableScope`.\n\n```ts\nimport { createSortableScope } from '@vielzeug/dnd/sortable';\n\nconst scope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => {\n persistMove(itemId, sourceIds, targetIds);\n },\n touch: true,\n});\n```\n\n## `Sortable` Interface\n\n### `sortable.isDragging`\n\n`readonly isDragging: boolean`\n\n`true` while an item drag is in progress.\n\n### `sortable.refresh()`\n\n`refresh(): void`\n\nRe-reads items from the `items` provider (or the container's direct children) and reapplies `draggable`, `role`, and handle attributes. Call it after adding, removing, or replacing sortable children.\n\n### `sortable.disposed`\n\n`readonly disposed: boolean`\n\n`true` once `dispose()` has been called.\n\n### `sortable.disposalSignal`\n\n`readonly disposalSignal: AbortSignal`\n\nAn `AbortSignal` that fires when `dispose()` is called.\n\n### `sortable.dispose()`\n\n`dispose(): void`\n\nRemoves all event listeners from the container, strips sortable attributes from items and handles, and cancels any in-progress drag by restoring the original order. Idempotent: safe to call multiple times.\n\n### `sortable[Symbol.dispose]()`\n\n`[Symbol.dispose](): void`\n\nAlias for `dispose()`.\n\n## `SortableScope` Interface\n\n### `scope.isDragging`\n\n`readonly isDragging: boolean`\n\n`true` while any sortable registered to the scope is dragging.\n\n### `scope.dispose()`\n\n`dispose(): void`\n\nDisposes scope-owned touch input and all registered sortables. Registering a new sortable with a disposed scope throws `DndScopeError`.\n\n## DOM Attributes\n\nDnd reads and writes the following DOM attributes:\n\n- `data-dnd-item`: internal marker applied by `createSortable` to children that return a truthy key from `getKey`. Restored on `dispose()`.\n- `draggable`, roles, tabindex, and `touchAction`: managed only as needed and restored to their exact prior values on `dispose()`.\n- `data-dragging`: set during drag, removed on `dragend` or `dispose()`. Use it as your styling hook for drag state.\n- `data-dnd-handle`: internal marker set by `createSortable` and `sortable.refresh()`, removed by `dispose()`. Lets Dnd clean up only the handle attributes it applied.\n- `aria-hidden=\"true\"`: set on placeholder creation and removed with the placeholder. Applied to the `.dnd-placeholder` element.\n- `style.touchAction = 'none'` (inline style): set by `createSortable` and `sortable.refresh()` on the item (or the handle, when `handle` is set), then restored on `dispose()`.\n\n## CSS Classes\n\n| Class | Applied to | When |\n| ----------------- | ---------------------------- | ------------------------------------------------------------- |\n| `dnd-placeholder` | `<div>` inserted by sortable | While an item is being dragged, in the placeholder's position |\n\n## `matchesAccept()`\n\n```ts\ndeclare function matchesAccept(file: File, accept: readonly string[]): boolean;\n```\n\nTests whether a `File` matches an accept pattern list. Each pattern can be:\n\n- A MIME type: `'image/png'`\n- A MIME wildcard: `'image/*'`\n- A file extension: `'.pdf'`\n\nAn empty list accepts everything. Extension matching is case-insensitive.\n\n**Returns:** `true` when the file matches at least one pattern, or when `accept` is empty.\n\n```ts\nimport { matchesAccept } from '@vielzeug/dnd/drop';\n\nmatchesAccept(file, ['image/*', '.pdf']); // true or false\n```\n\n## `applyReorder()`\n\n```ts\ndeclare function applyReorder<T>(items: readonly T[], ids: readonly string[], getKey: (item: T) => string): T[];\n```\n\nApplies a DOM reorder result (`orderedIds`) to your backing array.\n\n- IDs missing from `items` are ignored.\n- Items not listed in `ids` are appended in original order.\n- Duplicate IDs in `ids`: first occurrence wins, later occurrences are ignored.\n- Duplicate keys in `items` throw `DndError`; data is never silently discarded.\n\n**Returns:** A new array ordered by `ids`, with omitted items appended in their original order.\n\n```ts\nconst next = applyReorder(items, orderedIds, (item) => item.id);\n```\n\n## Errors\n\n| Error | Trigger | Notable property |\n| --------------- | ------------------------------------------------------------------------------------------- | ----------------------------- |\n| `DndError` | Invalid configuration, duplicate item data, or duplicate sortable registration in one scope | Base class for package errors |\n| `DndScopeError` | A sortable receives an invalid or disposed scope | Extends `DndError` |\n",
6
- "usage": "---\ntitle: 'Dnd: Usage Guide'\ndescription: Drop zones, sortable lists, explicit connected scopes, keyboard sorting, and cleanup patterns with Dnd.\n---\n\n[[toc]]\n\n## Basic Usage\n\n`createDropZone` attaches drag-and-drop behavior to any DOM element and keeps hover state stable with a counter.\n\n```ts\nimport { createDropZone } from '@vielzeug/dnd/drop';\n\nconst dropzone = document.getElementById('dropzone')!;\n\nconst zone = createDropZone({\n element: dropzone,\n onDrop: (files) => {\n console.log('Accepted files:', files);\n },\n});\n```\n\n### Accept filtering\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*', '.pdf', 'application/json'],\n onDrop: (files) => {\n // accepted files only\n },\n onDropRejected: (files) => {\n showToast(`${files.length} file(s) not accepted`);\n },\n});\n```\n\nThe `accept` list is normalized and snapshotted at construction. MIME matching is case-insensitive; invalid patterns throw `DndError`. Recreate the zone to change accepted types.\n\n### Hover state\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n onHoverChange: (hovered) => {\n dropEl.classList.toggle('drag-over', hovered);\n },\n});\n```\n\nRead zone state imperatively:\n\n```ts\nconsole.log(zone.hovered);\nconsole.log(zone.validating);\n```\n\n### Drop effect\n\n```ts\ncreateDropZone({\n element: dropEl,\n dropEffect: 'move',\n onDrop: (files) => {\n // ...\n },\n});\n```\n\n### Disabled state\n\n```ts\nconst options = { disabled: false, element: dropEl, onDrop: handleFiles };\nconst zone = createDropZone(options);\n\n// options.disabled is read live on each event: mutate to toggle:\noptions.disabled = isReadOnly;\n```\n\n### File limit\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*'],\n maxFiles: 5,\n onDrop: (files) => {\n // 1-5 accepted files\n },\n onDropRejected: (files) => {\n showToast(`Only 5 files at a time. ${files.length} were ignored.`);\n },\n});\n```\n\n### Cleanup\n\n```ts\nzone.dispose();\n// or:\nusing zone = createDropZone({ element: dropEl, onDrop: handleFiles });\n```\n\n`maxFiles` must be a non-negative safe integer.\n\n### Async validation\n\nGate drops behind an async check with `onValidate`. The zone remains `validating: true` until every pending validation settles, and disposal aborts each validation signal.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*'],\n onValidate: async (files, { signal }) => {\n const ok = await checkServerQuota(files, { signal });\n return ok; // false → all files forwarded to onDropRejected\n },\n onDrop: (files) => uploadFiles(files),\n onDropRejected: (files) => showError('Quota exceeded'),\n});\n\n// show a spinner while checking\nconsole.log(zone.validating); // true during pending check\n```\n\nA synchronous boolean return skips the microtask queue entirely:\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n onValidate: (files) => files.every((f) => f.size < 5_000_000), // sync\n onDrop: handleFiles,\n});\n```\n\n### Clipboard paste\n\nSet `paste: true` to accept files pasted through the drop-zone element. The focused paste target must be the element or its descendant; the same `accept`, `maxFiles`, and `onValidate` pipeline applies.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n paste: true,\n accept: ['image/*'],\n onPaste: (files) => {\n uploadFiles(files);\n },\n onDropRejected: (files) => {\n showError(`${files.length} file(s) not accepted`);\n },\n});\n```\n\nWhen `onPaste` is omitted, accepted pasted files fall through to `onDrop`.\n\n## Sortable\n\n`createSortable` makes direct children of a container reorderable via drag.\n\n### Setup\n\n```html\n<ul id=\"task-list\">\n <li data-sort-id=\"task-1\">Design</li>\n <li data-sort-id=\"task-2\">Develop</li>\n <li data-sort-id=\"task-3\">Review</li>\n</ul>\n```\n\n```ts\nconst sortable = createSortable({\n element: document.getElementById('task-list')!,\n getKey: (el) => el.dataset.sortId!,\n axis: 'vertical',\n onReorder: ({ after }) => {\n saveTaskOrder(after);\n },\n});\n```\n\nDnd automatically sets:\n\n- `draggable=\"true\"` on sortable nodes (or handles)\n- `role=\"listitem\"` on each item\n- `role=\"list\"` on the container\n- `tabindex=\"0\"` on each item for keyboard reordering\n\n### Drag handles\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n handle: '.drag-handle',\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Keyboard reordering\n\nFocus an item and use arrow keys to move it. `Home` and `End` move to the boundary positions.\n\nWhen an item is already at the first or last position, the boundary key press is not consumed: the browser handles it normally (for example, scrolling the page). Only keys that actually move an item call `preventDefault`. Arrow keys from buttons, links, form fields, and editable descendants remain native unless that descendant matches the configured drag handle. Wire `onInteraction` to an application live region for screen-reader announcements.\n\n### Connected lists\n\nCreate a shared scope when items should move between containers:\n\n```ts\nconst boardScope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => {\n persistMove(itemId, sourceIds, targetIds);\n },\n touch: true,\n});\n\ncreateSortable({\n element: todoEl,\n getKey: (el) => el.dataset.sortId!,\n scope: boardScope,\n});\ncreateSortable({\n element: doneEl,\n getKey: (el) => el.dataset.sortId!,\n scope: boardScope,\n});\n```\n\n### Auto-scroll and drag preview\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n autoScroll: { edgeThreshold: 40, speed: 24, viewport: true },\n dragImage: (id, item) => item,\n dragImageOffset: [8, 8],\n});\n```\n\nViewport scrolling is opt-in. Container scrolling stays enabled by default.\n\n### Lifecycle hooks\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onDragStart: (id) => {\n listEl.classList.add('sorting');\n },\n onDragEnd: (id) => {\n listEl.classList.remove('sorting');\n },\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Custom identity function\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.getAttribute('data-id')!,\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Dynamic lists\n\nCall `sortable.refresh()` after adding, removing, or replacing sortable items. It restores Dnd-managed semantics on elements no longer returned by `items()` before marking the current direct children.\n\n```ts\nconst item = document.createElement('li');\nitem.dataset.sortId = 'task-4';\nitem.textContent = 'Deploy';\nlistEl.appendChild(item);\nsortable.refresh();\n```\n\n### Disabled state\n\n```ts\nimport { createSortable, type SortableOptions } from '@vielzeug/dnd/sortable';\n\nconst options: SortableOptions = {\n disabled: false,\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => saveOrder(after),\n};\nconst sortable = createSortable(options);\n\n// options.disabled is read live on each event: mutate to toggle:\noptions.disabled = isLocked;\n```\n\n### Placeholder styling\n\n```css\n.dnd-placeholder {\n background: var(--color-primary-50);\n border: 2px dashed var(--color-primary-300);\n border-radius: 4px;\n box-sizing: border-box;\n}\n\n[data-dragging] {\n opacity: 0.35;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n}\n```\n\n### Mapping DOM order back to data\n\n```ts\nimport { applyReorder, createSortable } from '@vielzeug/dnd/sortable';\n\nlet items = [\n { id: 'task-1', title: 'Design' },\n { id: 'task-2', title: 'Develop' },\n { id: 'task-3', title: 'Review' },\n];\n\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n items = applyReorder(items, after, (item) => item.id);\n },\n});\n```\n\n### Cleanup\n\n```ts\nsortable.dispose();\n// or:\nusing sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### FLIP animation hook\n\n`onBeforeReorder` fires just before the DOM reorder commits, for both drag and keyboard moves. Pair it with [`captureLayout()`](/necromancer/api.md#capturelayout) to animate the resulting layout without managing rectangles, transforms, or animation frames yourself.\n\n```ts\nimport { captureLayout, type LayoutTransition } from '@vielzeug/necromancer';\n\nlet layout: LayoutTransition<HTMLElement> | undefined;\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onBeforeReorder: () => {\n layout = captureLayout(listEl.querySelectorAll<HTMLElement>('[data-sort-id]'), {\n getKey: (el) => el.dataset.sortId!,\n });\n },\n onReorder: ({ after }) => {\n saveOrder(after); // Commit a framework render here when needed.\n layout?.animate({\n duration: 200,\n easing: 'ease-out',\n elements: listEl.querySelectorAll('[data-sort-id]'),\n });\n layout = undefined;\n },\n});\n```\n\nIf `saveOrder()` triggers a render that replaces list items, call `layout?.animate({ elements: committedItems })` after that render commits. When DnD's own reordered elements remain in the DOM, call `layout?.animate()` directly. Dnd does not depend on Necromancer: the application installs it only when FLIP animation is required. Dnd's sole runtime dependency is Gesture for touch pointer recognition.\n\n### Optimistic updates and rollback\n\nThe `onReorder` event carries `before`, `after`, and `item`. Application history owns rollback: use `before` to record an undo entry.\n\n```ts\nconst history: Array<{ before: readonly string[] }> = [];\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ before, after }) => {\n history.push({ before });\n setOrder(after); // optimistic update\n },\n});\n\n// On server error:\ntry {\n await api.saveOrder(currentOrder);\n} catch {\n const entry = history.pop();\n if (entry) setOrder(entry.before);\n}\n```\n\n## Touch Support\n\nThe HTML Drag and Drop API has no reliable native touch path. Enable touch on a sortable scope; it only recognizes items registered to that scope, never unrelated `draggable` elements.\n\n```ts\nimport { createSortable, createSortableScope } from '@vielzeug/dnd/sortable';\n\nusing scope = createSortableScope({ touch: true });\nusing sortable = createSortable({ element: listEl, getKey: (el) => el.dataset.id!, scope });\n```\n\nGesture tracks the primary touch pointer for the active drag. Additional contacts cannot move, finish, or replace it. Pointer cancellation restores the original item order and removes the transient preview.\n\n### Touch preview\n\nTouch uses an inert outline by default, avoiding cloned application DOM. Provide a preview factory or opt out when your item styling supplies its own feedback.\n\n```ts\nconst scope = createSortableScope({\n touch: {\n activationDistance: 8,\n // The returned element is cloned before Dnd mounts it as a transient preview.\n preview: (item) => item.querySelector<HTMLElement>('.drag-preview'),\n },\n});\n```\n\n### Why touch-enabled items get `touch-action: none`\n\nWhen a sortable scope enables touch input, `createSortable` sets `touch-action: none` on the managed item or handle. This prevents a mobile browser from claiming the gesture as page scrolling before the scope controller starts the drag. Sortables without touch input preserve native touch scrolling.\n\n## Testing\n\nTest observable callbacks and controller state with your DOM test runner. Construct the zone in each test, dispatch a real `drop` event, then dispose it during teardown.\n\n```ts\nimport { afterEach, expect, it, vi } from 'vitest';\nimport { createDropZone } from '@vielzeug/dnd/drop';\n\nconst zones: Array<{ dispose(): void }> = [];\n\nafterEach(() => zones.splice(0).forEach((zone) => zone.dispose()));\n\nit('forwards accepted files', async () => {\n const element = document.createElement('div');\n const onDrop = vi.fn();\n const zone = createDropZone({ element, onDrop });\n zones.push(zone);\n const file = new File(['content'], 'readme.txt', { type: 'text/plain' });\n const event = new Event('drop') as DragEvent;\n\n Object.defineProperty(event, 'dataTransfer', { value: { files: [file] } });\n element.dispatchEvent(event);\n\n await Promise.resolve();\n\n expect(onDrop).toHaveBeenCalledWith([file]);\n expect(zone.disposed).toBe(false);\n});\n```\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\nimport { createSortable, applyReorder } from '@vielzeug/dnd/sortable';\n\nfunction SortableList({ initialItems }: { initialItems: { id: string; text: string }[] }) {\n const listRef = useRef<HTMLUListElement>(null);\n const items = useRef(initialItems);\n\n useEffect(() => {\n const sortable = createSortable({\n element: listRef.current!,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n items.current = applyReorder(items.current, after, (i) => i.id);\n },\n });\n return () => sortable.dispose();\n }, []);\n\n return (\n <ul ref={listRef}>\n {initialItems.map((item) => (\n <li key={item.id} data-sort-id={item.id}>\n {item.text}\n </li>\n ))}\n </ul>\n );\n}\n```\n\n```ts [Vue 3]\nimport { ref, onMounted, onUnmounted } from 'vue';\nimport { createSortable, applyReorder, type Sortable } from '@vielzeug/dnd/sortable';\n\nfunction useSortable(items: { id: string; text: string }[]) {\n const listRef = ref<HTMLElement | null>(null);\n const orderedItems = ref(items);\n let sortable: Sortable | null = null;\n\n onMounted(() => {\n sortable = createSortable({\n element: listRef.value!,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n orderedItems.value = applyReorder(orderedItems.value, after, (i) => i.id);\n },\n });\n });\n\n onUnmounted(() => sortable?.dispose());\n return { listRef, orderedItems };\n}\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createSortable, applyReorder } from '@vielzeug/dnd/sortable';\n\n export let initialItems: { id: string; text: string }[] = [];\n let items = initialItems;\n let listEl: HTMLUListElement;\n\n onMount(() => {\n const sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => { items = applyReorder(items, after, (i) => i.id); },\n });\n return () => sortable.dispose();\n });\n</script>\n\n<ul bind:this={listEl}>\n {#each items as item (item.id)}\n <li data-sort-id={item.id}>{item.text}</li>\n {/each}\n</ul>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Ore\n\nUse Dnd in custom web components by attaching behavior in component lifecycle hooks.\n\n```ts\nimport { createSortable } from '@vielzeug/dnd/sortable';\nimport { define, getHost, html, onMounted } from '@vielzeug/ore';\n\ndefine('task-list', {\n setup(_props) {\n const el = getHost();\n\n onMounted(() => {\n const sortable = createSortable({\n element: el,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => save(after),\n });\n return () => sortable.dispose();\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\n### With Gesture\n\nKeep direct manipulation separate from drag-and-drop semantics. Use Gesture for one-axis surfaces that follow the pointer and let application code decide the outcome; use Dnd when an item enters a drag lifecycle and is dropped into a zone or reordered collection. Dnd touch sorting uses Gesture's two-dimensional pointer recognizer, then adds previews, hit-testing, synthetic drag events, and sortable transactions. Direct-manipulation consumers use Gesture without Dnd.\n\n## Best Practices\n\n- Attach `createDropZone` and `createSortable` after the container element is in the DOM: use `onMounted` in component frameworks.\n- Call `.dispose()` in the cleanup phase of your framework (useEffect return, onUnmounted, onDestroy) to prevent memory leaks.\n- Use `data-sort-id` attributes that match your data's identity field: do not use DOM index as an identifier.\n- Prefer `applyReorder()` over manual array splicing, and guarantee unique backing keys; duplicates throw `DndError` rather than dropping data.\n- Use `createSortableScope()` only when items should genuinely move between containers.\n- Use drag handles (`.handle` selector) when the full item surface area conflicts with other interactions such as text selection.\n- Test keyboard reordering explicitly: Dnd sets `tabindex` on items and supports arrow keys by default.\n- Enable `touch: true` only on scopes that own touch-sortable lists.\n",
5
+ "api": "---\ntitle: 'Dnd: API Reference'\ndescription: Complete API reference for Dnd.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------------------- | -------------------------------------------- | -------------- | ----------------------------------------------------------------- |\n| `createDropZone()` | Create a typed drop-zone controller | Sync | Dispose the controller during teardown |\n| `createSortable()` | Add sortable drag-and-drop behavior to lists | Sync | Provide stable item identity for reorder operations |\n| `createSortableScope()` | Create a shared scope for connected lists | Sync | Each set of connected containers needs its own scope instance |\n| `applyReorder()` | Apply ordered IDs to data arrays | Sync | Unknown IDs are skipped; non-mentioned items are appended |\n| `DropZoneOptions.accept` | Filter file types before processing | Sync | Mismatch between MIME and extension can reject files unexpectedly |\n| `DropZoneOptions.maxFiles` | Cap accepted files per drop | Sync | Excess accepted files become rejected; `onDropRejected` is called |\n| `matchesAccept()` | Test a single `File` against an accept list | Sync | Extension patterns are case-insensitive; empty list accepts all |\n| `DndError` | Base class for Dnd errors | Sync | Use `instanceof DndError` to narrow unknown errors |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | ---------------------------------------------------------------- |\n| `@vielzeug/dnd` | Backward-compat root barrel |\n| `@vielzeug/dnd/drop` | Drop-zone APIs plus `DndError` and `Disposable` |\n| `@vielzeug/dnd/sortable` | Sortable APIs plus `DndError`, `DndScopeError`, and `Disposable` |\n\nDnd has no third-party runtime dependencies. Its sortable touch adapter uses `@vielzeug/gesture` for shared pointer recognition.\n\n## Types\n\n### `Disposable`\n\n```ts\ninterface Disposable {\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n```\n\n### `DropZoneOptions`\n\n```ts\ninterface DropZoneOptions {\n element: HTMLElement;\n accept?: readonly string[];\n maxFiles?: number;\n onValidate?: (files: File[], context: DropValidationContext) => boolean | Promise<boolean>;\n disabled?: boolean;\n dropEffect?: DataTransfer['dropEffect'];\n onDrop?: (files: File[]) => void;\n onDropRejected?: (files: File[]) => void;\n onHoverChange?: (hovered: boolean) => void;\n onValidatingChange?: (validating: boolean) => void;\n paste?: boolean;\n onPaste?: (files: File[]) => void;\n}\n```\n\n### `DropZone`\n\n```ts\ninterface DropZone extends Disposable {\n readonly hovered: boolean;\n readonly validating: boolean;\n}\n```\n\n### `DropValidationContext`\n\n```ts\ninterface DropValidationContext {\n readonly signal: AbortSignal;\n}\n```\n\n### `SortableOptions`\n\n```ts\ninterface SortableOptions {\n element: HTMLElement;\n getKey: (element: HTMLElement) => string;\n scope?: SortableScope;\n handle?: string;\n keyboard?: boolean;\n axis?: 'vertical' | 'horizontal';\n autoScroll?: boolean | AutoScrollOptions;\n dragImage?: HTMLElement | ((id: string, item: HTMLElement, event: DragEvent) => HTMLElement | null | undefined);\n dragImageOffset?: [number, number];\n placeholderClass?: string;\n disabled?: boolean;\n onDragStart?: (id: string, event: DragEvent) => void;\n onDragEnd?: (id: string, event: DragEvent) => void;\n onInteraction?: (event: SortableInteractionEvent) => void;\n onBeforeReorder?: (from: readonly string[], to: readonly string[]) => void;\n onReorder?: (event: ReorderEvent) => void;\n items?: () => readonly HTMLElement[];\n}\n```\n\n### `AutoScrollOptions`\n\n```ts\ninterface AutoScrollOptions {\n edgeThreshold?: number;\n speed?: number;\n container?: boolean;\n viewport?: boolean;\n}\n```\n\n### `ReorderEvent`\n\n```ts\ninterface ReorderEvent {\n before: readonly string[];\n after: readonly string[];\n item: string;\n}\n```\n\n### `Sortable`\n\n```ts\ninterface Sortable extends Disposable {\n readonly isDragging: boolean;\n refresh(): void;\n}\n```\n\n### `SortableScope`\n\n```ts\ninterface SortableScope extends Disposable {\n readonly isDragging: boolean;\n}\n```\n\n### `SortableScopeOptions`\n\n```ts\ninterface SortableScopeOptions {\n onMove?: (event: SortableMoveEvent) => void;\n touch?: boolean | SortableTouchOptions;\n}\n```\n\n### `SortableMoveEvent`\n\n```ts\ninterface SortableMoveEvent {\n readonly itemId: string;\n readonly source: HTMLElement;\n readonly sourceBeforeIds: readonly string[];\n readonly sourceIds: readonly string[];\n readonly target: HTMLElement;\n readonly targetBeforeIds: readonly string[];\n readonly targetIds: readonly string[];\n}\n```\n\n### `SortableInteractionEvent`\n\nStructured accessibility/observability event for sortable interactions. Drag emits `pickup` on dragstart, `drop` on commit, `cancel` on cancel. Keyboard emits `move` on each successful arrow/Home/End reorder (direct-commit model).\n\n```ts\ntype SortableInteractionEvent =\n | { readonly type: 'pickup'; readonly itemId: string; readonly index: number; readonly total: number }\n | {\n readonly type: 'move';\n readonly itemId: string;\n readonly previousIndex: number;\n readonly index: number;\n readonly total: number;\n }\n | { readonly type: 'drop'; readonly itemId: string; readonly index: number; readonly total: number }\n | { readonly type: 'cancel'; readonly itemId: string; readonly index: number; readonly total: number };\n```\n\nWire a consumer-side announcer to provide screen-reader feedback:\n\n```ts\nimport { createSortable } from '@vielzeug/dnd/sortable';\n\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.id!,\n onInteraction(event) {\n switch (event.type) {\n case 'pickup':\n announce(`Picked up ${event.itemId}, position ${event.index + 1} of ${event.total}`);\n break;\n case 'move':\n announce(`Moved ${event.itemId} to position ${event.index + 1} of ${event.total}`);\n break;\n case 'drop':\n announce(`Dropped ${event.itemId} at position ${event.index + 1} of ${event.total}`);\n break;\n case 'cancel':\n announce(`Cancelled, ${event.itemId} returned to position ${event.index + 1} of ${event.total}`);\n break;\n }\n },\n});\n```\n\n### `SortableTouchOptions`\n\n```ts\ntype SortableTouchOptions = Readonly<{\n activationDistance?: number;\n preview?: false | ((item: HTMLElement) => HTMLElement | null);\n}>;\n```\n\n`activationDistance` is the non-negative finite movement threshold in pixels before touch sorting starts (default `6`). Invalid values throw `DndError`.\n\n`preview` returns a template that Dnd clones before mounting it as a transient touch preview, so returning an element from the sortable item does not reparent or remove caller-owned DOM. Return `false` to disable the preview.\n\nTouch sorting delegates activation, movement, identity, and cancellation to Gesture's `createDragGesture()` with pointer capture disabled for document hit-testing. Dnd retains preview rendering, hit-testing, synthetic drag events, and sortable transactions. A second touch cancels sorting and restores the pre-drag order without firing `onReorder` or `onMove`. Without a configured handle, touch starts on editing controls, buttons, links, ARIA controls, and `[data-no-drag]` subtrees are excluded. Explicit handles remain eligible, including button handles.\n\n## `createDropZone()`\n\n```ts\ndeclare function createDropZone(options: DropZoneOptions): DropZone;\n```\n\nAttaches drag-and-drop file handling to a DOM element. Returns a `DropZone` handle.\n\n| Option | Type | Default | Description |\n| -------------------- | ---------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `element` | `HTMLElement` | N/A | **Required.** The element to attach drag listeners to. |\n| `accept` | `string[]` | `[]` | Accepted file types, normalized and snapshotted at construction. Empty array accepts everything; invalid MIME, wildcard, or extension patterns throw `DndError`. |\n| `maxFiles` | `number` | N/A | Non-negative safe-integer file limit. Excess files are passed to `onDropRejected`; invalid values throw `DndError` during construction. |\n| `onValidate` | `(files, { signal }) => boolean \\| Promise<boolean>` | N/A | Optional async gating step. Return or resolve `false` to reject all accepted files. `validating` remains true until every operation settles; `signal` aborts on disposal. |\n| `disabled` | `boolean` | N/A | When `true`, all drag and paste events are ignored. A disabled zone does not call `preventDefault` on `dragenter`, `dragover`, `drop`, or `paste`, so underlying elements (text editors, etc.) receive them normally. |\n| `dropEffect` | `'copy' \\| 'move' \\| 'link' \\| 'none'` | `'copy'` | The `dropEffect` set on `dataTransfer` during `dragover`. Controls the cursor indicator. |\n| `onDrop` | `(files: File[]) => void` | N/A | Called with accepted files only. Not called if all dropped files are rejected. Also receives paste events when `paste: true` and `onPaste` is omitted. |\n| `onDropRejected` | `(files: File[]) => void` | N/A | Called with files that did not match `accept`, exceeded `maxFiles`, or were rejected by `onValidate`. |\n| `onHoverChange` | `(hovered: boolean) => void` | N/A | Called when hover state toggles. Use this callback for drag-over styling. |\n| `onValidatingChange` | `(validating: boolean) => void` | N/A | Called whenever the aggregate async validation state changes. |\n| `paste` | `boolean` | `false` | When `true`, attaches a `paste` listener to `element`. Pasted files run through the same `accept`, `maxFiles`, and `onValidate` pipeline as dropped files. |\n| `onPaste` | `(files: File[]) => void` | N/A | Called when files are pasted from the clipboard. Falls back to `onDrop` when omitted. Only active when `paste: true`. |\n\n**Returns:** `DropZone`\n\nNotes:\n\n- Extension accept patterns are approximate during pre-check (`DataTransferItem` has no filename); exact filtering is applied at drop time.\n- Hover state (`hovered`) only becomes `true` when the dragged payload passes the `accept` filter. Drags carrying rejected file types enter and leave the zone without triggering `onHoverChange`.\n- Hover state is reset on element drop and also global `window` `drop`/`dragend` to avoid stuck hover state when drags leave the viewport.\n- Disposal aborts validation and transitions `validating` to `false` before teardown completes.\n- Consumer callback failures are reported through Dnd's development warning channel and never reclassify accepted files as rejected.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*', '.pdf'],\n onDrop: (files) => {\n upload(files);\n },\n onDropRejected: (files) => {\n showError(`${files.length} rejected`);\n },\n onHoverChange: (hovered) => {\n dropEl.classList.toggle('drag-over', hovered);\n },\n});\n```\n\n## `DropZone` Interface\n\n### `zone.hovered`\n\n`readonly hovered: boolean`\n\n`true` when a drag is currently over the zone. Updated synchronously by the internal counter: safe to read at any time.\n\n### `zone.validating`\n\n`readonly validating: boolean`\n\n`true` while an `onValidate` promise is pending. Use this to render a loading indicator between file selection and the acceptance/rejection callbacks firing.\n\n```ts\nconsole.log(zone.validating); // true between drop and onValidate resolution\n```\n\n### `zone.disposed`\n\n`readonly disposed: boolean`\n\n`true` once `dispose()` has been called. Safe to read at any time.\n\n### `zone.disposalSignal`\n\n`readonly disposalSignal: AbortSignal`\n\nAn `AbortSignal` that fires when `dispose()` is called. Use it to cancel in-flight requests tied to the zone's lifetime.\n\n### `zone.dispose()`\n\n`dispose(): void`\n\nRemoves all event listeners, aborts pending validation, and resets `hovered` and `validating`. Idempotent: safe to call multiple times.\n\n```ts\nzone.dispose();\n```\n\n### `zone[Symbol.dispose]()`\n\n`[Symbol.dispose](): void`\n\nAlias for `dispose()`. Called automatically when used with the `using` keyword.\n\n```ts\n{\n using zone = createDropZone({ element: dropEl, onDrop: handleFiles });\n} // zone.dispose() runs here\n```\n\n## `createSortable()`\n\n```ts\ndeclare function createSortable(options: SortableOptions): Sortable;\n```\n\nMakes the direct children of a container element reorderable via drag. Returns a `Sortable` handle.\n\n`createSortable` adds drag and keyboard defaults only when callers have not already supplied semantics. Every changed attribute and inline style is restored to its prior value on disposal.\n\n- `element`: `HTMLElement`, required. The container whose children become sortable.\n- `getKey`: `(element: HTMLElement) => string`, required. Maps each item element to its stable string identity. Children for which `getKey` returns a falsy value are skipped.\n- `scope`: `SortableScope`, default private scope. Connects sortable lists explicitly; containers only exchange items when they share the same scope instance.\n- `handle`: `string`. Valid CSS selector for a drag handle inside each item. Invalid selectors throw `DndError`; an empty selector warns and disables dragging.\n- `keyboard`: `boolean`, default `true`. Enables keyboard reordering with arrow keys plus `Home` and `End`, matched through `matchKey` from `@vielzeug/keymap`: modifier chords (e.g. Ctrl+ArrowDown, browser back/forward) are ignored. Events from interactive descendants are ignored unless they match the configured handle.\n- `axis`: `'vertical' | 'horizontal'`, default `'vertical'`. Controls midpoint calculation for placeholder insertion.\n- `autoScroll`: `boolean | AutoScrollOptions`, default `true`. Scrolls near edges; threshold must be finite and non-negative and speed finite and positive.\n- `dragImage`: `HTMLElement | ((id, item, event) => HTMLElement | null | undefined)`. Custom native drag preview passed to `dataTransfer.setDragImage()`. A `null` or `undefined` return skips `setDragImage` entirely.\n- `dragImageOffset`: `[number, number]`, default `[0, 0]`. The `[x, y]` hotspot offset passed to `setDragImage`. Controls which point of the preview image follows the cursor.\n- `placeholderClass`: `string`, default `'dnd-placeholder'`. CSS class applied to the generated placeholder element.\n- `disabled`: `boolean`. Blocks drag interactions. If a list becomes disabled mid-drag, Dnd cancels the drag and restores the original order.\n- `onDragStart`: `(id: string, event: DragEvent) => void`. Called when a drag starts.\n- `onDragEnd`: `(id: string, event: DragEvent) => void`. Called when a drag ends, whether completed or cancelled.\n- `onInteraction`: `(event: SortableInteractionEvent) => void`. Structured accessibility event for pickup/move/drop/cancel: wire to a consumer-side announcer for screen-reader feedback. See [`SortableInteractionEvent`](#sortableinteractionevent).\n- `onBeforeReorder`: `(from: readonly string[], to: readonly string[]) => void`. Called with the before/after order snapshots just before a successful reorder commits: for both drag and keyboard. Items are still in their pre-commit positions at the time of the call, making it ideal for [`captureLayout()`](/necromancer/api.md#capturelayout) setup.\n- `items`: `() => readonly HTMLElement[]`. Returns direct children owned by this sortable. `refresh()` restores elements no longer returned before marking the current set.\n- `onReorder`: `(event: ReorderEvent) => void`. Called after a successful reorder (drag or keyboard), only when the order changed. The event carries `before`, `after`, and `item` so application history can own rollback.\n\nOrder arrays and interaction events are frozen snapshots. Callback failures are reported through Dnd's development warning channel and cannot interrupt session completion or corrupt later events. Native touch scrolling is preserved unless the shared scope enables touch input.\n\n**Returns:** `Sortable`\n\n```ts\nconst boardScope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => saveMove(itemId, sourceIds, targetIds),\n touch: true,\n});\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.id!,\n handle: '.drag-handle',\n onDragStart: (id) => {\n listEl.classList.add('sorting');\n },\n onDragEnd: (id) => {\n listEl.classList.remove('sorting');\n },\n onReorder: ({ before, after }) => {\n history.push({ revert: () => saveOrder(before) });\n saveOrder(after);\n },\n scope: boardScope,\n});\n```\n\n### `createSortableScope()`\n\n```ts\ndeclare function createSortableScope(options?: SortableScopeOptions): SortableScope;\n```\n\nUse one scope per connected set of containers. `onMove` fires once for cross-list moves with both final orders; local reorders continue to call the sortable's `onReorder`.\n\n| Parameter | Type | Description |\n| --------- | ---------------------- | --------------------------------------------------------------------- |\n| `options` | `SortableScopeOptions` | Optional cross-list move callback and scope-owned touch configuration |\n\n**Returns:** `SortableScope`.\n\n```ts\nimport { createSortableScope } from '@vielzeug/dnd/sortable';\n\nconst scope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => {\n persistMove(itemId, sourceIds, targetIds);\n },\n touch: true,\n});\n```\n\n## `Sortable` Interface\n\n### `sortable.isDragging`\n\n`readonly isDragging: boolean`\n\n`true` while an item drag is in progress.\n\n### `sortable.refresh()`\n\n`refresh(): void`\n\nRe-reads items from the `items` provider (or the container's direct children) and reapplies `draggable`, `role`, and handle attributes. Call it after adding, removing, or replacing sortable children.\n\n### `sortable.disposed`\n\n`readonly disposed: boolean`\n\n`true` once `dispose()` has been called.\n\n### `sortable.disposalSignal`\n\n`readonly disposalSignal: AbortSignal`\n\nAn `AbortSignal` that fires when `dispose()` is called.\n\n### `sortable.dispose()`\n\n`dispose(): void`\n\nRemoves all event listeners from the container, strips sortable attributes from items and handles, and cancels any in-progress drag by restoring the original order. Idempotent: safe to call multiple times.\n\n### `sortable[Symbol.dispose]()`\n\n`[Symbol.dispose](): void`\n\nAlias for `dispose()`.\n\n## `SortableScope` Interface\n\n### `scope.isDragging`\n\n`readonly isDragging: boolean`\n\n`true` while any sortable registered to the scope is dragging.\n\n### `scope.dispose()`\n\n`dispose(): void`\n\nDisposes scope-owned touch input and all registered sortables. Registering a new sortable with a disposed scope throws `DndScopeError`.\n\n## DOM Attributes\n\nDnd reads and writes the following DOM attributes:\n\n- `data-dnd-item`: internal marker applied by `createSortable` to children that return a truthy key from `getKey`. Restored on `dispose()`.\n- `draggable`, roles, tabindex, and `touchAction`: managed only as needed and restored to their exact prior values on `dispose()`.\n- `data-dragging`: set during drag, removed on `dragend` or `dispose()`. Use it as your styling hook for drag state.\n- `data-dnd-handle`: internal marker set by `createSortable` and `sortable.refresh()`, removed by `dispose()`. Lets Dnd clean up only the handle attributes it applied.\n- `aria-hidden=\"true\"`: set on placeholder creation and removed with the placeholder. Applied to the `.dnd-placeholder` element.\n- `style.touchAction = 'none'` (inline style): set by `createSortable` and `sortable.refresh()` on the item (or the handle, when `handle` is set), then restored on `dispose()`.\n\n## CSS Classes\n\n| Class | Applied to | When |\n| ----------------- | ---------------------------- | ------------------------------------------------------------- |\n| `dnd-placeholder` | `<div>` inserted by sortable | While an item is being dragged, in the placeholder's position |\n\n## `matchesAccept()`\n\n```ts\ndeclare function matchesAccept(file: File, accept: readonly string[]): boolean;\n```\n\nTests whether a `File` matches an accept pattern list. Each pattern can be:\n\n- A MIME type: `'image/png'`\n- A MIME wildcard: `'image/*'`\n- A file extension: `'.pdf'`\n\nAn empty list accepts everything. Extension matching is case-insensitive.\n\n**Returns:** `true` when the file matches at least one pattern, or when `accept` is empty.\n\n```ts\nimport { matchesAccept } from '@vielzeug/dnd/drop';\n\nmatchesAccept(file, ['image/*', '.pdf']); // true or false\n```\n\n## `applyReorder()`\n\n```ts\ndeclare function applyReorder<T>(items: readonly T[], ids: readonly string[], getKey: (item: T) => string): T[];\n```\n\nApplies a DOM reorder result (`orderedIds`) to your backing array.\n\n- IDs missing from `items` are ignored.\n- Items not listed in `ids` are appended in original order.\n- Duplicate IDs in `ids`: first occurrence wins, later occurrences are ignored.\n- Duplicate keys in `items` throw `DndError`; data is never silently discarded.\n\n**Returns:** A new array ordered by `ids`, with omitted items appended in their original order.\n\n```ts\nconst next = applyReorder(items, orderedIds, (item) => item.id);\n```\n\n## Errors\n\n| Error | Trigger | Notable property |\n| --------------- | ------------------------------------------------------------------------------------------- | ----------------------------- |\n| `DndError` | Invalid configuration, duplicate item data, or duplicate sortable registration in one scope | Base class for package errors |\n| `DndScopeError` | A sortable receives an invalid or disposed scope | Extends `DndError` |\n",
6
+ "usage": "---\ntitle: 'Dnd: Usage Guide'\ndescription: Drop zones, sortable lists, explicit connected scopes, keyboard sorting, and cleanup patterns with Dnd.\n---\n\n[[toc]]\n\n## Basic Usage\n\n`createDropZone` attaches drag-and-drop behavior to any DOM element and keeps hover state stable with a counter.\n\n```ts\nimport { createDropZone } from '@vielzeug/dnd/drop';\n\nconst dropzone = document.getElementById('dropzone')!;\n\nconst zone = createDropZone({\n element: dropzone,\n onDrop: (files) => {\n console.log('Accepted files:', files);\n },\n});\n```\n\n### Accept filtering\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*', '.pdf', 'application/json'],\n onDrop: (files) => {\n // accepted files only\n },\n onDropRejected: (files) => {\n showToast(`${files.length} file(s) not accepted`);\n },\n});\n```\n\nThe `accept` list is normalized and snapshotted at construction. MIME matching is case-insensitive; invalid patterns throw `DndError`. Recreate the zone to change accepted types.\n\n### Hover state\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n onHoverChange: (hovered) => {\n dropEl.classList.toggle('drag-over', hovered);\n },\n});\n```\n\nRead zone state imperatively:\n\n```ts\nconsole.log(zone.hovered);\nconsole.log(zone.validating);\n```\n\n### Drop effect\n\n```ts\ncreateDropZone({\n element: dropEl,\n dropEffect: 'move',\n onDrop: (files) => {\n // ...\n },\n});\n```\n\n### Disabled state\n\n```ts\nconst options = { disabled: false, element: dropEl, onDrop: handleFiles };\nconst zone = createDropZone(options);\n\n// options.disabled is read live on each event: mutate to toggle:\noptions.disabled = isReadOnly;\n```\n\n### File limit\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*'],\n maxFiles: 5,\n onDrop: (files) => {\n // 1-5 accepted files\n },\n onDropRejected: (files) => {\n showToast(`Only 5 files at a time. ${files.length} were ignored.`);\n },\n});\n```\n\n### Cleanup\n\n```ts\nzone.dispose();\n// or:\nusing zone = createDropZone({ element: dropEl, onDrop: handleFiles });\n```\n\n`maxFiles` must be a non-negative safe integer.\n\n### Async validation\n\nGate drops behind an async check with `onValidate`. The zone remains `validating: true` until every pending validation settles, and disposal aborts each validation signal.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*'],\n onValidate: async (files, { signal }) => {\n const ok = await checkServerQuota(files, { signal });\n return ok; // false → all files forwarded to onDropRejected\n },\n onDrop: (files) => uploadFiles(files),\n onDropRejected: (files) => showError('Quota exceeded'),\n});\n\n// show a spinner while checking\nconsole.log(zone.validating); // true during pending check\n```\n\nA synchronous boolean return skips the microtask queue entirely:\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n onValidate: (files) => files.every((f) => f.size < 5_000_000), // sync\n onDrop: handleFiles,\n});\n```\n\n### Clipboard paste\n\nSet `paste: true` to accept files pasted through the drop-zone element. The focused paste target must be the element or its descendant; the same `accept`, `maxFiles`, and `onValidate` pipeline applies.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n paste: true,\n accept: ['image/*'],\n onPaste: (files) => {\n uploadFiles(files);\n },\n onDropRejected: (files) => {\n showError(`${files.length} file(s) not accepted`);\n },\n});\n```\n\nWhen `onPaste` is omitted, accepted pasted files fall through to `onDrop`.\n\n## Sortable\n\n`createSortable` makes direct children of a container reorderable via drag.\n\n### Setup\n\n```html\n<ul id=\"task-list\">\n <li data-sort-id=\"task-1\">Design</li>\n <li data-sort-id=\"task-2\">Develop</li>\n <li data-sort-id=\"task-3\">Review</li>\n</ul>\n```\n\n```ts\nconst sortable = createSortable({\n element: document.getElementById('task-list')!,\n getKey: (el) => el.dataset.sortId!,\n axis: 'vertical',\n onReorder: ({ after }) => {\n saveTaskOrder(after);\n },\n});\n```\n\nDnd automatically sets:\n\n- `draggable=\"true\"` on sortable nodes (or handles)\n- `role=\"listitem\"` on each item\n- `role=\"list\"` on the container\n- `tabindex=\"0\"` on each item for keyboard reordering\n\n### Drag handles\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n handle: '.drag-handle',\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\nTouch sorting ignores controls inside an item unless they belong to the configured handle. Put `data-no-drag` on a custom interaction subtree to exclude it when sorting whole items. A second finger cancels the drag and restores the original order; it never commits a reorder.\n\n### Keyboard reordering\n\nFocus an item and use arrow keys to move it. `Home` and `End` move to the boundary positions.\n\nWhen an item is already at the first or last position, the boundary key press is not consumed: the browser handles it normally (for example, scrolling the page). Only keys that actually move an item call `preventDefault`. Arrow keys from buttons, links, form fields, and editable descendants remain native unless that descendant matches the configured drag handle. Wire `onInteraction` to an application live region for screen-reader announcements.\n\n### Connected lists\n\nCreate a shared scope when items should move between containers:\n\n```ts\nconst boardScope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => {\n persistMove(itemId, sourceIds, targetIds);\n },\n touch: true,\n});\n\ncreateSortable({\n element: todoEl,\n getKey: (el) => el.dataset.sortId!,\n scope: boardScope,\n});\ncreateSortable({\n element: doneEl,\n getKey: (el) => el.dataset.sortId!,\n scope: boardScope,\n});\n```\n\n### Auto-scroll and drag preview\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n autoScroll: { edgeThreshold: 40, speed: 24, viewport: true },\n dragImage: (id, item) => item,\n dragImageOffset: [8, 8],\n});\n```\n\nViewport scrolling is opt-in. Container scrolling stays enabled by default.\n\n### Lifecycle hooks\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onDragStart: (id) => {\n listEl.classList.add('sorting');\n },\n onDragEnd: (id) => {\n listEl.classList.remove('sorting');\n },\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Custom identity function\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.getAttribute('data-id')!,\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Dynamic lists\n\nCall `sortable.refresh()` after adding, removing, or replacing sortable items. It restores Dnd-managed semantics on elements no longer returned by `items()` before marking the current direct children.\n\n```ts\nconst item = document.createElement('li');\nitem.dataset.sortId = 'task-4';\nitem.textContent = 'Deploy';\nlistEl.appendChild(item);\nsortable.refresh();\n```\n\n### Disabled state\n\n```ts\nimport { createSortable, type SortableOptions } from '@vielzeug/dnd/sortable';\n\nconst options: SortableOptions = {\n disabled: false,\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => saveOrder(after),\n};\nconst sortable = createSortable(options);\n\n// options.disabled is read live on each event: mutate to toggle:\noptions.disabled = isLocked;\n```\n\n### Placeholder styling\n\n```css\n.dnd-placeholder {\n background: var(--color-primary-50);\n border: 2px dashed var(--color-primary-300);\n border-radius: 4px;\n box-sizing: border-box;\n}\n\n[data-dragging] {\n opacity: 0.35;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n}\n```\n\n### Mapping DOM order back to data\n\n```ts\nimport { applyReorder, createSortable } from '@vielzeug/dnd/sortable';\n\nlet items = [\n { id: 'task-1', title: 'Design' },\n { id: 'task-2', title: 'Develop' },\n { id: 'task-3', title: 'Review' },\n];\n\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n items = applyReorder(items, after, (item) => item.id);\n },\n});\n```\n\n### Cleanup\n\n```ts\nsortable.dispose();\n// or:\nusing sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### FLIP animation hook\n\n`onBeforeReorder` fires just before the DOM reorder commits, for both drag and keyboard moves. Pair it with [`captureLayout()`](/necromancer/api.md#capturelayout) to animate the resulting layout without managing rectangles, transforms, or animation frames yourself.\n\n```ts\nimport { captureLayout, type LayoutTransition } from '@vielzeug/necromancer';\n\nlet layout: LayoutTransition<HTMLElement> | undefined;\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onBeforeReorder: () => {\n layout = captureLayout(listEl.querySelectorAll<HTMLElement>('[data-sort-id]'), {\n getKey: (el) => el.dataset.sortId!,\n });\n },\n onReorder: ({ after }) => {\n saveOrder(after); // Commit a framework render here when needed.\n layout?.animate({\n duration: 200,\n easing: 'ease-out',\n elements: listEl.querySelectorAll('[data-sort-id]'),\n });\n layout = undefined;\n },\n});\n```\n\nIf `saveOrder()` triggers a render that replaces list items, call `layout?.animate({ elements: committedItems })` after that render commits. When DnD's own reordered elements remain in the DOM, call `layout?.animate()` directly. Dnd does not depend on Necromancer: the application installs it only when FLIP animation is required. Dnd's sole runtime dependency is Gesture for touch pointer recognition.\n\n### Optimistic updates and rollback\n\nThe `onReorder` event carries `before`, `after`, and `item`. Application history owns rollback: use `before` to record an undo entry.\n\n```ts\nconst history: Array<{ before: readonly string[] }> = [];\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ before, after }) => {\n history.push({ before });\n setOrder(after); // optimistic update\n },\n});\n\n// On server error:\ntry {\n await api.saveOrder(currentOrder);\n} catch {\n const entry = history.pop();\n if (entry) setOrder(entry.before);\n}\n```\n\n## Touch Support\n\nThe HTML Drag and Drop API has no reliable native touch path. Enable touch on a sortable scope; it only recognizes items registered to that scope, never unrelated `draggable` elements.\n\n```ts\nimport { createSortable, createSortableScope } from '@vielzeug/dnd/sortable';\n\nusing scope = createSortableScope({ touch: true });\nusing sortable = createSortable({ element: listEl, getKey: (el) => el.dataset.id!, scope });\n```\n\nGesture tracks the primary touch pointer for the active drag. Additional contacts cannot move, finish, or replace it. Pointer cancellation restores the original item order and removes the transient preview.\n\n### Touch preview\n\nTouch uses an inert outline by default, avoiding cloned application DOM. Provide a preview factory or opt out when your item styling supplies its own feedback.\n\n```ts\nconst scope = createSortableScope({\n touch: {\n activationDistance: 8,\n // The returned element is cloned before Dnd mounts it as a transient preview.\n preview: (item) => item.querySelector<HTMLElement>('.drag-preview'),\n },\n});\n```\n\n### Why touch-enabled items get `touch-action: none`\n\nWhen a sortable scope enables touch input, `createSortable` sets `touch-action: none` on the managed item or handle. This prevents a mobile browser from claiming the gesture as page scrolling before the scope controller starts the drag. Sortables without touch input preserve native touch scrolling.\n\n## Testing\n\nTest observable callbacks and controller state with your DOM test runner. Construct the zone in each test, dispatch a real `drop` event, then dispose it during teardown.\n\n```ts\nimport { afterEach, expect, it, vi } from 'vitest';\nimport { createDropZone } from '@vielzeug/dnd/drop';\n\nconst zones: Array<{ dispose(): void }> = [];\n\nafterEach(() => zones.splice(0).forEach((zone) => zone.dispose()));\n\nit('forwards accepted files', async () => {\n const element = document.createElement('div');\n const onDrop = vi.fn();\n const zone = createDropZone({ element, onDrop });\n zones.push(zone);\n const file = new File(['content'], 'readme.txt', { type: 'text/plain' });\n const event = new Event('drop') as DragEvent;\n\n Object.defineProperty(event, 'dataTransfer', { value: { files: [file] } });\n element.dispatchEvent(event);\n\n await Promise.resolve();\n\n expect(onDrop).toHaveBeenCalledWith([file]);\n expect(zone.disposed).toBe(false);\n});\n```\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\nimport { createSortable, applyReorder } from '@vielzeug/dnd/sortable';\n\nfunction SortableList({ initialItems }: { initialItems: { id: string; text: string }[] }) {\n const listRef = useRef<HTMLUListElement>(null);\n const items = useRef(initialItems);\n\n useEffect(() => {\n const sortable = createSortable({\n element: listRef.current!,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n items.current = applyReorder(items.current, after, (i) => i.id);\n },\n });\n return () => sortable.dispose();\n }, []);\n\n return (\n <ul ref={listRef}>\n {initialItems.map((item) => (\n <li key={item.id} data-sort-id={item.id}>\n {item.text}\n </li>\n ))}\n </ul>\n );\n}\n```\n\n```ts [Vue 3]\nimport { ref, onMounted, onUnmounted } from 'vue';\nimport { createSortable, applyReorder, type Sortable } from '@vielzeug/dnd/sortable';\n\nfunction useSortable(items: { id: string; text: string }[]) {\n const listRef = ref<HTMLElement | null>(null);\n const orderedItems = ref(items);\n let sortable: Sortable | null = null;\n\n onMounted(() => {\n sortable = createSortable({\n element: listRef.value!,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n orderedItems.value = applyReorder(orderedItems.value, after, (i) => i.id);\n },\n });\n });\n\n onUnmounted(() => sortable?.dispose());\n return { listRef, orderedItems };\n}\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createSortable, applyReorder } from '@vielzeug/dnd/sortable';\n\n export let initialItems: { id: string; text: string }[] = [];\n let items = initialItems;\n let listEl: HTMLUListElement;\n\n onMount(() => {\n const sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => { items = applyReorder(items, after, (i) => i.id); },\n });\n return () => sortable.dispose();\n });\n</script>\n\n<ul bind:this={listEl}>\n {#each items as item (item.id)}\n <li data-sort-id={item.id}>{item.text}</li>\n {/each}\n</ul>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Ore\n\nUse Dnd in custom web components by attaching behavior in component lifecycle hooks.\n\n```ts\nimport { createSortable } from '@vielzeug/dnd/sortable';\nimport { define, getHost, html, onMounted } from '@vielzeug/ore';\n\ndefine('task-list', {\n setup(_props) {\n const el = getHost();\n\n onMounted(() => {\n const sortable = createSortable({\n element: el,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => save(after),\n });\n return () => sortable.dispose();\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\n### With Gesture\n\nKeep direct manipulation separate from drag-and-drop semantics. Use Gesture for one-axis surfaces that follow the pointer and let application code decide the outcome; use Dnd when an item enters a drag lifecycle and is dropped into a zone or reordered collection. Dnd touch sorting uses Gesture's two-dimensional pointer recognizer, then adds previews, hit-testing, synthetic drag events, and sortable transactions. Direct-manipulation consumers use Gesture without Dnd.\n\n## Best Practices\n\n- Attach `createDropZone` and `createSortable` after the container element is in the DOM: use `onMounted` in component frameworks.\n- Call `.dispose()` in the cleanup phase of your framework (useEffect return, onUnmounted, onDestroy) to prevent memory leaks.\n- Use `data-sort-id` attributes that match your data's identity field: do not use DOM index as an identifier.\n- Prefer `applyReorder()` over manual array splicing, and guarantee unique backing keys; duplicates throw `DndError` rather than dropping data.\n- Use `createSortableScope()` only when items should genuinely move between containers.\n- Use drag handles (`.handle` selector) when the full item surface area conflicts with other interactions such as text selection.\n- Test keyboard reordering explicitly: Dnd sets `tabindex` on items and supports arrow keys by default.\n- Enable `touch: true` only on scopes that own touch-sortable lists.\n",
7
7
  "examples": "---\ntitle: 'Dnd: Examples'\ndescription: Practical examples and recipes for dnd.\n---\n\n## Examples\n\n- [Sortable List](./examples/sortable-list.md)\n- [Touch-Enabled Sortable List](./examples/touch-enabled-sortable-list.md)\n- [File Upload Drop Zone](./examples/file-upload-drop-zone.md)\n- [Optimistic Reorder with Revert and FLIP Animation](./examples/optimistic-reorder-with-revert.md)\n- [Combined Sortable With Inline Editing](./examples/combined-sortable-with-inline-editing.md)\n- [Connected Kanban Keyboard Sorting](./examples/connected-kanban-keyboard-sorting.md)\n- [Web Component With Ore](./examples/web-component-with-craft.md)\n- [Using `using` for scoped cleanup](./examples/using-using-for-scoped-cleanup.md)\n"
8
8
  },
9
9
  "examples": [
@@ -2,8 +2,8 @@
2
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",
3
3
  "docs": {
4
4
  "index": "---\ntitle: 'Gesture: Pointer movement primitives'\ndescription: Framework-neutral two-dimensional pointer drag and one-axis pan recognition with lifecycle-owned handles.\npackage: gesture\ncategory: input\nkeywords: [pointer, pan, swipe, gesture, touch, drag, long press]\nexports: [createDragGesture, createPanGesture, createLongPress, 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- 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 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` cancels back to a normal press, and window blur or a hidden document cancels a pending hold. The click that follows a fired hold is swallowed through a capture-phase listener on `target`, so releasing never commits what the hold opened; bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers.\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}>;\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 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}>;\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 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\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| `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`, and pointer capture loss on the gesture target cancel active recognition. A `lostpointercapture` event bubbling from a descendant does not cancel the target's gesture.\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. It activates only after movement 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;\n}\n```\n\n```ts\nconst pan = createPanGesture(row, { axis: 'x', onMove });\n```\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",
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",
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": [