@vielzeug/codex 2.2.7 → 2.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +1842 -0
- package/data/llms-full.txt +30872 -0
- package/data/llms.txt +44 -0
- package/data/manifest.json +8 -0
- package/data/packages/arsenal.json +210 -0
- package/data/packages/assay.json +39 -0
- package/data/packages/clockwork.json +67 -0
- package/data/packages/codex.json +43 -0
- package/data/packages/coins.json +102 -0
- package/data/packages/conduit.json +60 -0
- package/data/packages/courier.json +58 -0
- package/data/packages/dnd.json +77 -0
- package/data/packages/familiar.json +40 -0
- package/data/packages/flux.json +93 -0
- package/data/packages/focus.json +37 -0
- package/data/packages/forge.json +83 -0
- package/data/packages/gesture.json +25 -0
- package/data/packages/herald.json +108 -0
- package/data/packages/illusionist.json +132 -0
- package/data/packages/keymap.json +60 -0
- package/data/packages/ledger.json +57 -0
- package/data/packages/lingua.json +68 -0
- package/data/packages/necromancer.json +50 -0
- package/data/packages/orbit.json +99 -0
- package/data/packages/ore.json +68 -0
- package/data/packages/prism.json +66 -0
- package/data/packages/pulse.json +69 -0
- package/data/packages/refine.json +12 -0
- package/data/packages/ripple.json +83 -0
- package/data/packages/rune.json +79 -0
- package/data/packages/sandbox.json +40 -0
- package/data/packages/scout.json +60 -0
- package/data/packages/scroll.json +109 -0
- package/data/packages/sentinel.json +35 -0
- package/data/packages/sourcerer.json +73 -0
- package/data/packages/spell.json +133 -0
- package/data/packages/tempo.json +81 -0
- package/data/packages/vault.json +85 -0
- package/data/packages/ward.json +114 -0
- package/data/packages/wayfinder.json +110 -0
- package/data/refine.json +11887 -0
- package/data/search.json +1556 -0
- package/package.json +1 -1
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiSource": "export { type Courier, type CourierOptions, createCourier } from './courier';\nexport {\n CourierAbortError,\n CourierDisposedError,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierParseError,\n CourierSchemaValidationError,\n CourierTimeoutError,\n} from './errors';\nexport { withBearerAuth, withLogging, withRequestId } from './interceptors';\nexport type { StreamEvent, StreamOptions } from './stream';\nexport type { FetchContext, Interceptor, TransportOptions } from './transport';\nexport type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';\nexport type { HttpRequestConfig as RequestConfig, Params } from './url';\n",
|
|
3
|
+
"docs": {
|
|
4
|
+
"index": "---\ntitle: Courier — HTTP, queries, and streaming\ndescription: A framework-neutral fetch client with explicit cache keys, direct mutations, and abortable streams.\npackage: courier\ncategory: http\nkeywords: [http-client, fetch, caching, queries, mutations, sse, streaming, interceptors]\nrelated: [flux, ripple, spell]\nexports:\n [\n createCourier,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierTimeoutError,\n CourierAbortError,\n CourierSchemaValidationError,\n withBearerAuth,\n withRequestId,\n withLogging,\n ]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"courier\" />\n\n## Why Courier?\n\nNative `fetch` leaves request policy, cached reads, and stream lifecycles to each application. Courier keeps\nthose concerns in one client while making cache identity and fetch policy explicit at every cached read.\n\n```ts\n// Before\nconst response = await fetch(`/api/users/${userId}`);\nif (!response.ok) throw new Error(`HTTP ${response.status}`);\nconst user = await response.json();\n\n// After\nawait courier.queries.fetch({\n key: ['users', userId],\n fetch: ({ signal }) => courier.get('/users/{id}', { params: { id: userId }, signal }),\n});\n```\n\n| Feature | Courier | TanStack Query | ky |\n| --- | --- | --- | --- |\n| Bundle size | <PackageInfo package=\"courier\" type=\"size\" /> | Framework adapter required | Separate package |\n| Zero runtime dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Native fetch transport | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Bring your own | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Explicit cache keys | <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| SSE and NDJSON iteration | <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| External runtime dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Courier when** one application client should own typed HTTP, explicit cached reads, direct writes, and\nabortable response streams.\n\n**Consider TanStack Query when** you need a maintained framework adapter or advanced cache features such as\ninfinite queries. **Consider ky when** you only need a compact fetch wrapper without caching or streams.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/courier\n```\n\n```sh [npm]\nnpm install @vielzeug/courier\n```\n\n```sh [yarn]\nyarn add @vielzeug/courier\n```\n\n:::\n\n## Quick Start\n\nCreate one client for an application or request scope, then fetch a cache entry by its explicit key.\n\n```ts\nimport { CourierHttpError, createCourier } from '@vielzeug/courier';\n\ntype User = { id: number; name: string };\n\nconst courier = createCourier({ baseUrl: 'https://api.example.com', query: { staleTime: 30_000 } });\nconst key = ['users', 42] as const;\n\ntry {\n await courier.queries.fetch({\n key,\n fetch: ({ signal }) => courier.get('/users/{id}', { params: { id: 42 }, signal }),\n });\n console.log(courier.queries.getSnapshot<User>(key)?.data);\n} catch (error) {\n if (CourierHttpError.is(error, 404)) console.log('User not found');\n else throw error;\n} finally {\n courier.dispose();\n}\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createCourier()`** — one lifecycle, interceptor pipeline, header store, and cancellation boundary.\n- **`get()` / `post()` / `put()` / `patch()` / `delete()`** — typed paths, query strings, request bodies, validation, and structured errors.\n- **`queries.fetch()`** — key-based cached reads, subscriptions, invalidation with refetch, and automatic garbage collection.\n- **`mutate()`** — direct write operation with `invalidateKeys` for one-step cache refetch, without hidden retries or a second state store.\n- **`events()` / `read()`** — abortable SSE, text, and NDJSON iteration with normalized request errors.\n- **`withBearerAuth()` / `withRequestId()` / `withLogging()`** — composable transport policies.\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- [Flux](/flux/) — adapts Courier cache entries and event iterators into composable streams.\n- [Ripple](/ripple/) — stores Courier snapshots in fine-grained reactive state.\n- [Spell](/spell/) — validates parsed HTTP payloads through Courier's schema option.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: Courier — API Reference\ndescription: Reference for Courier HTTP, cache, mutation, interceptor, and stream APIs.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `createCourier()` | Creates unified application client | Sync | Dispose only when whole scope ends |\n| `Courier` HTTP methods | Sends and parses HTTP requests | Async | Direct calls never deduplicate |\n| `queries.fetch()` | Fetches one keyed cache entry | Async | Key must include all response identity inputs |\n| `mutate()` | Runs one write operation | Async | It never retries automatically |\n| `events()` / `read()` | Opens abortable response iterators | Async iteration | Breaking iteration aborts request |\n| `withBearerAuth()` | Adds authorization interceptor | Sync | Token provider runs per request |\n| `withRequestId()` | Adds request identifier interceptor | Sync | Default generator uses `uuid()` |\n| `withLogging()` | Logs request result metadata | Sync | Requires explicit logger; URLs may contain sensitive query values |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/courier` | Client factory, errors, interceptors, and public types |\n\n## Client\n\n### `createCourier()`\n\n```ts\ncreateCourier(options?: CourierOptions): Courier;\n```\n\nReturns client sharing transport configuration, headers, interceptors, cancellation, cache, mutations, and streams.\n\n| `CourierOptions` field | Type | Default | Description |\n| --- | --- | --- | --- |\n| `baseUrl` | `string` | `''` | Prefix for relative request paths |\n| `fetch` | `typeof globalThis.fetch` | `globalThis.fetch` | Fetch implementation |\n| `headers` | `Record<string, string>` | `{}` | Global request headers |\n| `timeout` | `number` | `30_000` | Default HTTP timeout in milliseconds |\n| `query.staleTime` | `number` | `0` | Cache freshness duration |\n| `query.gcTime` | `number` | `300_000` | Garbage-collect entries with no subscribers after this duration (ms); `Infinity` disables |\n\n**Returns:** `Courier`.\n\n```ts\nimport { createCourier } from '@vielzeug/courier';\n\nconst courier = createCourier({ baseUrl: 'https://api.example.com' });\n```\n\n| `Courier` member | Signature | Description |\n| --- | --- | --- |\n| `get` / `post` / `put` / `patch` / `delete` | `<T, P>(url: P, config?) => Promise<T>` | Sends one HTTP request |\n| `setHeaders` | `(updates) => void` | Updates global headers |\n| `getHeaders` | `() => Readonly<Record<string, string>>` | Returns header snapshot |\n| `use` | `(interceptor) => () => void` | Registers interceptor |\n| `cancelAll` | `() => void` | Aborts active HTTP, cache, and mutation work; a subsequent `queries.fetch()` starts a fresh request |\n| `queries` | `QueryCache` | Owns keyed cache entries |\n| `mutate` | `<T>(options) => Promise<T>` | Runs one write operation |\n| `events` | `<T, P>(url, options?) => AsyncIterableIterator<StreamEvent<T>>` | Opens SSE iterator |\n| `read` | `<T, P>(url, options?) => AsyncIterableIterator<T>` | Opens text or NDJSON iterator |\n| `dispose` | `() => void` | Final disposal; aborts work and clears cache |\n| `disposed` | `boolean` | Whether final disposal occurred |\n| `disposalSignal` | `AbortSignal` | Aborts on final disposal |\n\n---\n\n## Queries\n\n### `queries.fetch()`\n\n```ts\nfetch<T>(definition: QueryDefinition<T>, options?: { force?: boolean }): Promise<T>;\n```\n\nRegisters latest definition for `definition.key`, then returns fresh cached data or runs its fetch function.\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| `definition.key` | `QueryKey` | Cache identity; include every response identity input |\n| `definition.fetch` | `(context: QueryContext) => Promise<T>` | Request function for this key |\n| `definition.staleTime` | `number` | Per-entry freshness duration |\n| `options.force` | `boolean` | Fetch even when cached data is fresh |\n\n**Returns:** Cached or fetched data.\n\n```ts\nconst key = ['profile', 1] as const;\nawait courier.queries.fetch({\n key,\n fetch: ({ signal }) => courier.get('/profile/{id}', { params: { id: 1 }, signal }),\n});\n```\n\n| `QueryCache` method | Returns | Description |\n| --- | --- | --- |\n| `get(key)` | `T \\| undefined` | Returns successful cached data |\n| `getSnapshot(key)` | `AsyncState<T> \\| null` | Returns snapshot by key |\n| `set(key, data, options?)` | `void` | Sets successful cache value |\n| `delete(key)` | `void` | Removes one cache entry and aborts its active fetch if present |\n| `invalidate(prefix, options?)` | `void` | Marks matching key prefixes stale; `options.refetch` triggers background refetch |\n| `keys()` | `QueryKey[]` | Lists known keys |\n| `subscribe(key, listener)` | `Unsubscribe` | Subscribes to one key |\n| `clear()` | `void` | Removes every cache entry |\n\n---\n\n## Mutations\n\n### `mutate()`\n\n```ts\nmutate<T>(options: MutationOptions<T>): Promise<T>;\n```\n\nRuns `options.request` once, then calls `onSuccess` after successful completion, then invalidates (and refetches) each key in `invalidateKeys`.\n\n| `MutationOptions<T>` field | Type | Description |\n| --- | --- | --- |\n| `request` | `(context: MutationContext) => Promise<T>` | Write operation |\n| `onSuccess` | `(data, queries) => void \\| Promise<void>` | Cache update callback |\n| `invalidateKeys` | `readonly (readonly unknown[])[]` | Key prefixes to invalidate and refetch after success |\n| `signal` | `AbortSignal` | Caller-controlled cancellation |\n\n**Returns:** Request result.\n\n---\n\n## Streams\n\n### `events()` and `read()`\n\n```ts\nevents<T, P extends string>(url: P, options?: StreamOptions<P>): AsyncIterableIterator<StreamEvent<T>>;\nread<T, P extends string>(url: P, options?: StreamOptions<P> & { parse?: 'ndjson' | 'text' }): AsyncIterableIterator<T>;\n```\n\nBoth iterators abort request when `return()` runs or `for await` loop exits. `events()` parses `event` and `data`\nfields; it does not retain event IDs or reconnect.\n\n`StreamOptions<P>` extends `RequestConfig<P>` (typed path params) with an optional `method` field. It omits\n`responseType` and `schema` (not applicable to streaming).\n\n**Returns:** Abortable async iterator.\n\n---\n\n## Interceptors\n\n### Interceptor helpers\n\n```ts\nwithBearerAuth(token: string | (() => string | Promise<string>)): Interceptor;\nwithRequestId(options?: { generate?: () => string; header?: string }): Interceptor;\nwithLogging(options: {\n logger: (message: string, meta: { duration: number; method: string; status: number; url: string }) => void;\n}): Interceptor;\n```\n\nEach helper returns an `Interceptor` accepted by `courier.use()`. `withLogging` requires an explicit `logger`\nfunction — no default console output.\n\n## Types\n\n```ts\ntype TransportOptions = {\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n headers?: Record<string, string>;\n timeout?: number;\n};\n\ntype CourierOptions = TransportOptions & {\n query?: { gcTime?: number; staleTime?: number };\n};\n\ntype FetchContext = {\n readonly headers: Readonly<Record<string, string>>;\n readonly init: Readonly<Omit<RequestInit, 'headers'>>;\n readonly url: string;\n withHeaders(updates: Record<string, string>): FetchContext;\n};\n\ntype Interceptor = (ctx: FetchContext, next: (ctx: FetchContext) => Promise<Response>) => Promise<Response>;\n\ntype AsyncState<T> =\n | { data: undefined; error: null; isFetching: boolean; status: 'loading'; updatedAt: undefined }\n | { data: T; error: null; isFetching: boolean; status: 'success'; updatedAt: number }\n | { data: T | undefined; error: Error; isFetching: false; status: 'error'; updatedAt: number };\n\ntype QueryContext = { readonly key: QueryKey; readonly signal: AbortSignal };\ntype QueryDefinition<T> = { fetch: (context: QueryContext) => Promise<T>; key: QueryKey; staleTime?: number };\ntype QueryKey = readonly [QueryKeyAtom, ...QueryKeyAtom[]];\ntype QueryKeyAtom = string | number | boolean | null;\ntype QueryCache = {\n clear(): void;\n delete(key: QueryKey): void;\n fetch<T>(definition: QueryDefinition<T>, options?: { force?: boolean }): Promise<T>;\n get<T>(key: QueryKey): T | undefined;\n getSnapshot<T>(key: QueryKey): AsyncState<T> | null;\n invalidate(prefix: readonly unknown[], options?: { refetch?: boolean }): void;\n keys(): QueryKey[];\n set<T>(key: QueryKey, data: T, options?: { updatedAt?: number }): void;\n subscribe(key: QueryKey, listener: () => void): Unsubscribe;\n};\ntype MutationContext = { readonly signal: AbortSignal };\ntype MutationOptions<T> = {\n invalidateKeys?: readonly (readonly unknown[])[];\n onSuccess?: (data: T, queries: QueryCache) => void | Promise<void>;\n request: (context: MutationContext) => Promise<T>;\n signal?: AbortSignal;\n};\ntype StreamEvent<T = unknown> = { readonly data: T; readonly event: string };\ntype StreamOptions<P extends string = string> = Omit<RequestConfig<P>, 'responseType' | 'schema'> & {\n method?: string;\n};\ntype Unsubscribe = () => void;\n```\n\n```ts\ntype ParamValue = string | number | boolean | null | readonly (string | number | boolean | null)[] | undefined;\ntype Params = Record<string, ParamValue>;\ntype RequestConfig<P extends string = string, T = unknown> = {\n body?: unknown;\n fetchInit?: Omit<RequestInit, 'body' | 'headers' | 'method' | 'signal'>;\n headers?: Record<string, string>;\n params?: Record<string, string | number | boolean>;\n query?: Params;\n responseType?: 'auto' | 'json' | 'text' | 'blob' | 'arrayBuffer' | 'raw';\n schema?: { parse(data: unknown): T };\n signal?: AbortSignal;\n timeout?: number;\n};\n```\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| --- | --- | --- |\n| `CourierError` | Base class for all Courier errors | Use `instanceof` to narrow |\n| `CourierHttpError` | Non-2xx HTTP response | `status`, `data`, `headers`, `method`, `url`; `CourierHttpError.is(e, status?)` narrows by status |\n| `CourierNetworkError` | Request failure without response | `method`, `url`, `cause` |\n| `CourierTimeoutError` | Timeout signal aborts request | `method`, `url`, `cause` |\n| `CourierAbortError` | Caller, client, or iterator cancellation | `method`, `url`, `cause` |\n| `CourierSchemaValidationError` | Response schema fails | `data`, `cause` |\n| `CourierParseError` | Response body cannot parse | — |\n| `CourierDisposedError` | Work starts after disposal | — |\n",
|
|
6
|
+
"usage": "---\ntitle: Courier — Usage Guide\ndescription: Use one Courier client for HTTP, explicit cached reads, direct mutations, and abortable streams.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate one Courier client for an application or request scope. Its transport policy and disposal lifecycle apply\nto every request, cache entry, mutation, and stream.\n\n```ts\nimport { createCourier } from '@vielzeug/courier';\n\ntype User = { id: number; name: string };\n\nconst courier = createCourier({ baseUrl: 'https://api.example.com', query: { staleTime: 30_000 } });\nconst key = ['users', 1] as const;\n\nawait courier.queries.fetch({\n key,\n fetch: ({ signal }) => courier.get<User>('/users/{id}', { params: { id: 1 }, signal }),\n});\nconsole.log(courier.queries.get<User>(key)?.name);\n```\n\n## HTTP Requests\n\nUse root methods for REST requests. Courier encodes path parameters, serializes plain-object bodies, and parses\nsuccessful response bodies. Each direct HTTP call is independent; use a query key when concurrent cached reads\nshould share work.\n\n```ts\nconst posts = await courier.get<{ id: number; title: string }[]>('/users/{id}/posts', {\n params: { id: 1 },\n query: { limit: 20, status: 'published' },\n});\n\nawait courier.patch('/posts/{id}', {\n body: { title: 'Updated title' },\n params: { id: posts[0].id },\n});\n```\n\nCall `courier.setHeaders({ authorization: 'Bearer token' })` to update subsequent calls.\n\n## Interceptors\n\nInterceptors apply to HTTP and streaming requests. Register a policy once, then remove it when its containing\nscope ends.\n\n```ts\nimport { withBearerAuth, withRequestId } from '@vielzeug/courier';\n\nconst removeAuth = courier.use(withBearerAuth(async () => sessionStorage.getItem('access-token') ?? ''));\nconst removeRequestId = courier.use(withRequestId());\n\nremoveRequestId();\nremoveAuth();\n```\n\nUse `withLogging()` with an explicit `logger` function to log requests during local development. `withLogging()`\nincludes full URLs, so sanitize query values before persistent logging.\n\n```ts\nimport { withLogging } from '@vielzeug/courier';\n\ncourier.use(withLogging({ logger: (msg) => console.log(msg) }));\n```\n\n## Cached Queries\n\nPass a stable key and fetch definition to `queries.fetch()`. The cache owns data, snapshots, subscriptions, and\nin-flight deduplication for that key. Entries with no subscribers are garbage-collected after `gcTime` (default\n5 min; `Infinity` disables).\n\n```ts\nconst key = ['profile', 1] as const;\nconst definition = {\n key,\n fetch: ({ signal }) => courier.get<{ id: number; name: string }>('/profile/{id}', { params: { id: 1 }, signal }),\n staleTime: 60_000,\n};\n\nconst stop = courier.queries.subscribe(key, () => {\n const state = courier.queries.getSnapshot<{ id: number; name: string }>(key);\n if (state?.status === 'success') console.log(state.data.name);\n if (state?.status === 'error') console.error(state.error);\n});\n\nawait courier.queries.fetch(definition);\nstop();\n```\n\n`queries.fetch(definition)` reuses fresh data. Pass `{ force: true }` to fetch regardless of freshness.\n`invalidate(prefix, { refetch: true })` marks matching key prefixes stale and refetches them in the background\nin a single call.\n\n## Direct Mutations\n\nUse `mutate()` for a write operation. Pass `invalidateKeys` to invalidate and refetch cache entries after a\nsuccessful write — no manual `invalidate()` + refetch boilerplate. Use `onSuccess` for custom cache writes\n(e.g. seeding a created entity). Courier never retries writes: retry only operations your application can prove\nidempotent.\n\n```ts\ntype User = { id: number; name: string };\n\nconst created = await courier.mutate<User>({\n request: ({ signal }) => courier.post<User>('/users', { body: { name: 'Ada' }, signal }),\n onSuccess: (user, queries) => queries.set(['users', user.id], user),\n invalidateKeys: [['users']],\n});\n\nconsole.log(created.id);\n```\n\nPass an external `signal` when caller owns cancellation. Keep pending and error UI state in framework that owns\nthat UI.\n\n## Server-Sent Events\n\n`events()` returns an abortable `AsyncIterableIterator`. Breaking loop, calling `return()`, aborting a provided\nsignal, or disposing client stops its request immediately. Courier sends `Accept: text/event-stream` and\n`Cache-Control: no-cache` by default; pass headers to override either value.\n\n```ts\ntype Notification = { text: string };\n\nfor await (const event of courier.events<Notification>('/events')) {\n if (event.event !== 'message') continue;\n console.log(event.data.text);\n break;\n}\n```\n\nCourier parses valid JSON event data and otherwise returns text. It does not reconnect automatically or retain\nSSE event IDs; application owns reconnect policy.\n\n## HTTP Streaming\n\nUse `read()` for text chunks or NDJSON records.\n\n```ts\ntype ChatChunk = { done: boolean; delta: string };\n\nfor await (const chunk of courier.read<ChatChunk>('/chat', {\n body: { prompt: 'Explain cached queries.' },\n method: 'POST',\n parse: 'ndjson',\n})) {\n console.log(chunk.delta);\n if (chunk.done) break;\n}\n```\n\nStreams have no timeout unless `timeout` is supplied. HTTP, network, timeout, and cancellation failures use\nCourier error classes; starting a stream after disposal throws `CourierDisposedError`.\n\n## Framework Integration\n\nCreate Courier at application or route boundary. Views read a key snapshot synchronously, subscribe during\ntheir lifecycle, and let framework own rendering state.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useSyncExternalStore } from 'react';\nimport { createCourier } from '@vielzeug/courier';\nimport type { AsyncState, QueryDefinition } from '@vielzeug/courier';\n\ntype User = { id: number; name: string };\n\nexport function Profile({ courier, definition }: { courier: ReturnType<typeof createCourier>; definition: QueryDefinition<User> }) {\n const state = useSyncExternalStore(\n (listener) => courier.queries.subscribe(definition.key, listener),\n () => courier.queries.getSnapshot<User>(definition.key),\n () => courier.queries.getSnapshot<User>(definition.key),\n ) as AsyncState<User> | null;\n\n useEffect(() => void courier.queries.fetch(definition), [courier, definition]);\n\n if (!state || state.status === 'loading') return <p>Loading...</p>;\n if (state.status === 'error') return <p role=\"alert\">{state.error.message}</p>;\n return <p>{state.data.name}</p>;\n}\n```\n\n```ts [Vue 3]\nimport { onMounted, onUnmounted, ref } from 'vue';\nimport { createCourier } from '@vielzeug/courier';\nimport type { AsyncState, QueryDefinition } from '@vielzeug/courier';\n\ntype User = { id: number; name: string };\n\nexport function useProfile(courier: ReturnType<typeof createCourier>, definition: QueryDefinition<User>) {\n const state = ref<AsyncState<User> | null>(courier.queries.getSnapshot(definition.key));\n const unsubscribe = courier.queries.subscribe(definition.key, () => {\n state.value = courier.queries.getSnapshot(definition.key);\n });\n\n onMounted(() => void courier.queries.fetch(definition));\n onUnmounted(unsubscribe);\n\n return { state };\n}\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createCourier } from '@vielzeug/courier';\n import type { AsyncState, QueryDefinition } from '@vielzeug/courier';\n\n type User = { id: number; name: string };\n\n export let courier: ReturnType<typeof createCourier>;\n export let definition: QueryDefinition<User>;\n let state: AsyncState<User> | null = courier.queries.getSnapshot(definition.key);\n\n onMount(() => {\n const unsubscribe = courier.queries.subscribe(definition.key, () => (state = courier.queries.getSnapshot(definition.key)));\n void courier.queries.fetch(definition);\n return unsubscribe;\n });\n</script>\n\n{#if state?.status === 'success'}\n <p>{state.data.name}</p>\n{/if}\n```\n\n:::\n\nCourier exposes no framework-specific loading or error store. Render `AsyncState` in framework that owns view.\n\n## Working with Other Vielzeug Libraries\n\n### Flux\n\nUse Flux when cache snapshots or SSE events need filtering, composition, or subscription lifecycle separate from\nUI framework. Pass cache and query definition to `fromQuery()`.\n\n```ts\nimport { fromQuery } from '@vielzeug/flux/courier';\n\nconst profile = {\n key: ['profile'] as const,\n fetch: ({ signal }: { signal: AbortSignal }) => courier.get<{ id: number; name: string }>('/profile', { signal }),\n};\nconst profile$ = fromQuery(courier.queries, profile);\n\nvoid courier.queries.fetch(profile);\n\nconst profileSubscription = profile$.subscribe((state) => console.log(state?.status));\n\nprofileSubscription.unsubscribe();\n```\n\n### Ripple\n\nUse a Ripple signal when Courier data must participate in fine-grained reactive state outside a component. Mirror\nonly cache snapshot into signal.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\n\nconst key = ['profile', 1] as const;\nconst profileState = signal(courier.queries.getSnapshot<{ id: number; name: string }>(key));\nconst unsubscribe = courier.queries.subscribe(key, () => (profileState.value = courier.queries.getSnapshot(key)));\n\nawait courier.queries.fetch({\n key,\n fetch: ({ signal }) => courier.get('/profile/{id}', { params: { id: 1 }, signal }),\n});\n\nunsubscribe();\n```\n\n## Gotchas\n\n### `mutate()` runs `onSuccess` before `invalidateKeys`\n\n`mutate()` executes in order: `request` → `onSuccess` → `invalidateKeys`. If `onSuccess` calls `queries.set()` for a key also in `invalidateKeys`, the seeded data is overwritten by the background refetch. This is correct — `invalidateKeys` means \"refetch to confirm\" — but the order matters when `onSuccess` seeds optimistic data that `invalidateKeys` then replaces.\n\n### Optimistic rollback should use `getSnapshot()`, not `get()`\n\n`queries.get()` only returns successful data and drops snapshot metadata (`status`, `error`, `updatedAt`). It also cannot distinguish a missing entry from a successful cached value of `undefined`. For optimistic rollback, capture `getSnapshot()` first so you can restore prior success data with `updatedAt`, or `delete(key)` when no previous success snapshot existed.\n\n### `baseUrl` should not include query parameters\n\n`buildUrl` joins `baseUrl` and path with `/`. A base URL like `https://api.example.com?token=abc` produces broken URLs (`https://api.example.com?token=abc/users`). Pass query parameters per-request via `config.query` instead.\n\n### Background refetch after error transitions through `loading`\n\nWhen `invalidate({ refetch: true })` triggers a background refetch on an error-state entry, the snapshot transitions to `loading` (losing the previous error). Consumers building \"error + retrying\" UI should track retry state separately — `AsyncState` has no `error` with `isFetching: true` variant.\n\n## Best Practices\n\n- Create one Courier client per application or SSR request scope.\n- Use stable, complete cache keys for every cached response identity.\n- Fetch through `queries.fetch()` when work should deduplicate and cache.\n- Use `invalidateKeys` on mutations to refetch affected cache entries in one step.\n- Keep retries outside mutations until operation idempotency is proven.\n- Dispose only at final application or request boundary.\n- Keep credentials out of URLs when using logging interceptors.\n",
|
|
7
|
+
"examples": "---\ntitle: Courier — Examples\ndescription: Practical examples and recipes for courier.\n---\n\n## Examples\n\n- [Authentication](./examples/authentication.md)\n- [CRUD Operations](./examples/crud-operations.md)\n- [Disposal](./examples/disposal.md)\n- [Error Handling Patterns](./examples/error-handling-patterns.md)\n- [File Uploads](./examples/file-uploads.md)\n- [Optimistic Updates](./examples/optimistic-updates.md)\n- [Polling](./examples/polling.md)\n- [Real-time Events](./examples/sse-events.md)\n- [AI Token Stream](./examples/ai-token-stream.md)\n"
|
|
8
|
+
},
|
|
9
|
+
"examples": [
|
|
10
|
+
{
|
|
11
|
+
"id": "create-courier",
|
|
12
|
+
"code": "import { createCourier, withLogging } from '@vielzeug/courier'\n\nconst fetch: typeof globalThis.fetch = async (_url, init) =>\n new Response(JSON.stringify(init?.method === 'POST' ? { id: 3, name: 'Courier' } : { id: 1, name: 'Ada' }), {\n headers: { 'content-type': 'application/json' },\n })\n\nconst courier = createCourier({\n baseUrl: 'https://api.example.com',\n fetch,\n timeout: 8_000,\n query: { staleTime: 10_000 },\n})\n\ncourier.use(withLogging({ logger: (msg) => console.log(msg) }))\n\nconst user = await courier.get('/users/1')\nconsole.log('User:', user.name)\n\nconst key = ['users', 1]\nawait courier.queries.fetch({\n key,\n fetch: ({ signal }) => courier.get('/users/1', { signal }),\n})\nconsole.log('Cached user:', courier.queries.getSnapshot(key)?.data.name)\n\nconst created = await courier.mutate({\n request: ({ signal }) => courier.post('/users', { body: { name: 'Courier' }, signal }),\n invalidateKeys: [['users']],\n})\n\nconsole.log('Created id:', created.id)\ncourier.dispose()\nconsole.log('✓ Client disposed')",
|
|
13
|
+
"name": "createCourier - Unified Client"
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"id": "query-handle",
|
|
17
|
+
"code": "import { createCourier } from '@vielzeug/courier'\n\nconst fetch: typeof globalThis.fetch = async () =>\n new Response(JSON.stringify({ id: 1, name: 'Ada' }), { headers: { 'content-type': 'application/json' } })\nconst courier = createCourier({ baseUrl: 'https://api.example.com', fetch })\nconst key = ['users', 1]\nconst user = {\n key,\n fetch: ({ signal }: { signal: AbortSignal }) => courier.get('/users/1', { signal }),\n staleTime: 30_000,\n}\n\ncourier.queries.subscribe(key, () => {\n const state = courier.queries.getSnapshot(key)\n console.log('State:', state?.status, '| fetching:', state?.isFetching)\n})\n\nawait courier.queries.fetch(user)\nconsole.log('Name:', courier.queries.getSnapshot(key)?.data.name)\n\ncourier.queries.invalidate(key)\nawait courier.queries.fetch(user, { force: true })\n\nconsole.log('Final snapshot:', courier.queries.getSnapshot(key))",
|
|
18
|
+
"name": "queryCache - Cached Async Data"
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"id": "stream-cancellation",
|
|
22
|
+
"code": "import { createCourier } from '@vielzeug/courier'\n\n// Breaking a stream loop aborts its active request immediately.\n const fetch: typeof globalThis.fetch = async () =>\n new Response('{\"id\":1,\"message\":\"First record\"}\\n{\"id\":2,\"message\":\"Second record\"}\\n')\n const courier = createCourier({ baseUrl: 'https://api.example.com', fetch })\nconst iterator = courier.read('/chat', { body: { prompt: 'Show one stream record.' }, parse: 'ndjson' })\nconst records = []\n\nfor await (const record of iterator) {\n records.push(record)\n console.log('First record:', record)\n break\n}\n\nconsole.log('Stopped stream after', records.length, 'record')\nconsole.log('Records:', records)",
|
|
23
|
+
"name": "streamCancellation - Abortable Iteration"
|
|
24
|
+
}
|
|
25
|
+
],
|
|
26
|
+
"typeSignatures": {
|
|
27
|
+
"Courier": "export { type Courier, type CourierOptions, createCourier } from './courier';",
|
|
28
|
+
"CourierOptions": "export { type Courier, type CourierOptions, createCourier } from './courier';",
|
|
29
|
+
"createCourier": "export { type Courier, type CourierOptions, createCourier } from './courier';",
|
|
30
|
+
"CourierAbortError": "export {\n CourierAbortError,\n CourierDisposedError,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierParseError,\n CourierSchemaValidationError,\n CourierTimeoutError,\n} from './errors';",
|
|
31
|
+
"CourierDisposedError": "export {\n CourierAbortError,\n CourierDisposedError,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierParseError,\n CourierSchemaValidationError,\n CourierTimeoutError,\n} from './errors';",
|
|
32
|
+
"CourierError": "export {\n CourierAbortError,\n CourierDisposedError,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierParseError,\n CourierSchemaValidationError,\n CourierTimeoutError,\n} from './errors';",
|
|
33
|
+
"CourierHttpError": "export {\n CourierAbortError,\n CourierDisposedError,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierParseError,\n CourierSchemaValidationError,\n CourierTimeoutError,\n} from './errors';",
|
|
34
|
+
"CourierNetworkError": "export {\n CourierAbortError,\n CourierDisposedError,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierParseError,\n CourierSchemaValidationError,\n CourierTimeoutError,\n} from './errors';",
|
|
35
|
+
"CourierParseError": "export {\n CourierAbortError,\n CourierDisposedError,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierParseError,\n CourierSchemaValidationError,\n CourierTimeoutError,\n} from './errors';",
|
|
36
|
+
"CourierSchemaValidationError": "export {\n CourierAbortError,\n CourierDisposedError,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierParseError,\n CourierSchemaValidationError,\n CourierTimeoutError,\n} from './errors';",
|
|
37
|
+
"CourierTimeoutError": "export {\n CourierAbortError,\n CourierDisposedError,\n CourierError,\n CourierHttpError,\n CourierNetworkError,\n CourierParseError,\n CourierSchemaValidationError,\n CourierTimeoutError,\n} from './errors';",
|
|
38
|
+
"withBearerAuth": "export { withBearerAuth, withLogging, withRequestId } from './interceptors';",
|
|
39
|
+
"withLogging": "export { withBearerAuth, withLogging, withRequestId } from './interceptors';",
|
|
40
|
+
"withRequestId": "export { withBearerAuth, withLogging, withRequestId } from './interceptors';",
|
|
41
|
+
"StreamEvent": "export type { StreamEvent, StreamOptions } from './stream';",
|
|
42
|
+
"StreamOptions": "export type { StreamEvent, StreamOptions } from './stream';",
|
|
43
|
+
"FetchContext": "export type { FetchContext, Interceptor, TransportOptions } from './transport';",
|
|
44
|
+
"Interceptor": "export type { FetchContext, Interceptor, TransportOptions } from './transport';",
|
|
45
|
+
"TransportOptions": "export type { FetchContext, Interceptor, TransportOptions } from './transport';",
|
|
46
|
+
"AsyncState": "export type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';",
|
|
47
|
+
"MutationContext": "export type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';",
|
|
48
|
+
"MutationOptions": "export type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';",
|
|
49
|
+
"QueryCache": "export type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';",
|
|
50
|
+
"QueryContext": "export type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';",
|
|
51
|
+
"QueryDefinition": "export type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';",
|
|
52
|
+
"QueryKey": "export type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';",
|
|
53
|
+
"QueryKeyAtom": "export type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';",
|
|
54
|
+
"Unsubscribe": "export type {\n AsyncState,\n MutationContext,\n MutationOptions,\n QueryCache,\n QueryContext,\n QueryDefinition,\n QueryKey,\n QueryKeyAtom,\n Unsubscribe,\n} from './types';",
|
|
55
|
+
"RequestConfig": "export type { HttpRequestConfig as RequestConfig, Params } from './url';",
|
|
56
|
+
"Params": "export type { HttpRequestConfig as RequestConfig, Params } from './url';"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiSource": "export * from './drop-zone';\nexport { DndError, DndScopeError } from './errors';\nexport * from './sortable';\nexport * from './types';\n",
|
|
3
|
+
"docs": {
|
|
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 dependencies.\npackage: dnd\ncategory: ui-interaction\nkeywords: [drag-drop, sortable, file-upload, drop-zone, dnd, reorder]\nrelated: [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';\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 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** you need reliable file drop zones with MIME filtering or sortable lists in a framework-agnostic environment.\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, createSortable } from '@vielzeug/dnd';\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 revert support for optimistic updates\nlet currentOrder = ['a', 'b', 'c'];\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: ({ ids, setRevert }) => {\n const prev = currentOrder;\n currentOrder = ids;\n setRevert(() => {\n currentOrder = prev;\n });\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`; event type reflects whether the rejection came from a drop or a paste\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- **`sortable.revert()`** — register a revert function via `event.setRevert(fn)` inside `onReorder`; `sortable.revert()` invokes it and clears it for rolling back optimistic updates on server failure\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 sync** — call `sortable.sync()` after DOM mutations instead of relying on hidden observers\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` captures the array reference, so push/splice mutations are reflected without recreating the zone\n- **Zero dependencies** — <PackageInfo package=\"dnd\" type=\"size\" /> gzipped, <PackageInfo package=\"dnd\" type=\"dependencies\" /> dependencies\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Orbit](/orbit/) — floating element positioning; use alongside Dnd to anchor drag previews and drop-zone indicators to precise positions\n- [Ore](/ore/) — web-component authoring framework; build draggable custom elements with Dnd's pointer event primitives\n- [Refine](/refine/) — accessible web components; Dnd powers the drag-and-drop inside Refine's sortable list and kanban components\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 `DndError.is()` to narrow unknown errors |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------- | ---------------------- |\n| `@vielzeug/dnd` | Main exports and types |\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?: 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 onBeforeReorder?: (from: string[], to: string[]) => void;\n onReorder?: (event: ReorderEvent) => void;\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 ids: string[];\n setRevert(fn: () => void): void;\n}\n```\n\n### `Sortable`\n\n```ts\ninterface Sortable extends Disposable {\n readonly isDragging: boolean;\n revert(): void;\n sync(): void;\n}\n```\n\n### `SortableScope`\n\n```ts\ninterface SortableScope extends Disposable {\n readonly isDragging: boolean;\n revert(): void;\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 sourceIds: string[];\n readonly target: HTMLElement;\n readonly targetIds: string[];\n setRevert(fn: () => void): void;\n}\n```\n\n### `SortableTouchOptions`\n\n```ts\ninterface SortableTouchOptions {\n preview?: false | ((item: HTMLElement) => HTMLElement | null);\n}\n```\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 tracks the initiating touch by identifier. Secondary touches are ignored, and cancellation of the initiating touch 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` | — | **Required.** The element to attach drag listeners to. |\n| `accept` | `string[]` | `[]` | Accepted file types. Empty array accepts everything. Each entry is a MIME type (`'image/png'`), MIME wildcard (`'image/*'`), or file extension (`'.pdf'`). |\n| `maxFiles` | `number` | — | Maximum files accepted per drop. Files beyond this limit are passed to `onDropRejected`. When omitted there is no limit. |\n| `onValidate` | `(files, { signal }) => boolean \\| Promise<boolean>` | — | 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` | — | 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` | — | 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` | — | Called with files that did not match `accept`, exceeded `maxFiles`, or were rejected by `onValidate`. |\n| `onHoverChange` | `(hovered: boolean) => void` | — | Called when hover state toggles. Use this callback for drag-over styling. |\n| `onValidatingChange` | `(validating: boolean) => void` | — | Called whenever the aggregate async validation state changes. |\n| `paste` | `boolean` | `false` | When `true`, attaches a `paste` listener to `window`. Pasted files run through the same `accept`, `maxFiles`, and `onValidate` pipeline as dropped files. |\n| `onPaste` | `(files: File[]) => void` | — | 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\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 from the element, resets the drag counter and hover state, and clears the `hovered` flag. 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`. CSS selector for a drag handle inside each item. When omitted, the whole item is draggable.\n- `keyboard`: `boolean`, default `true`. Enables keyboard reordering with arrow keys plus `Home` and `End`.\n- `axis`: `'vertical' | 'horizontal'`, default `'vertical'`. Controls midpoint calculation for placeholder insertion.\n- `autoScroll`: `boolean | AutoScrollOptions`, default `true`. Scrolls the container near its edges; enable viewport scrolling with `autoScroll.viewport`.\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- `onBeforeReorder`: `(from: string[], to: 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- `onReorder`: `(event: ReorderEvent) => void`. Called after a successful reorder (drag or keyboard), only when the order changed. Use `event.setRevert(fn)` to register a revert function that `sortable.revert()` will invoke.\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: ({ ids, setRevert }) => {\n const prev = currentOrder;\n saveOrder(ids);\n setRevert(() => saveOrder(prev));\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';\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.revert()`\n\n`revert(): void`\n\nCalls the revert function registered via `setRevert` in the last `onReorder` invocation (if any) and clears it. A no-op when no revert function was registered or it has already been consumed. Works for both drag-based and keyboard-based reorders.\n\nOnly the most recent reorder can be reverted — a new reorder overwrites the stored function.\n\n```ts\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ ids, setRevert }) => {\n const prev = currentOrder;\n setOrder(ids);\n setRevert(() => setOrder(prev)); // ← enable revert\n },\n});\n\n// On server error:\ntry {\n await api.saveOrder(ids);\n} catch {\n sortable.revert();\n}\n```\n\n### `sortable.sync()`\n\n`sync(): void`\n\nRe-applies `draggable`, `role`, and handle attributes after DOM mutations. 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.revert()`\n\n`revert(): void`\n\nCalls and clears the rollback registered with `SortableMoveEvent.setRevert()` for the latest cross-list move. It is a no-op when no rollback is registered.\n\n### `scope.dispose()`\n\n`dispose(): void`\n\nDisposes scope-owned touch input and prevents registered lists from participating in future connected moves.\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.sync()`, 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.sync()` 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: 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';\n\nmatchesAccept(file, ['image/*', '.pdf']); // true or false\n```\n\n## `applyReorder()`\n\n```ts\ndeclare function applyReorder<T>(items: T[], ids: 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\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` | Base class for package errors | `DndError.is(error)` |\n| `DndScopeError` | A sortable receives a scope not created by `createSortableScope()` | — |\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';\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 read at drop-time, so mutating the array dynamically adjusts what is accepted for the next drop.\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### 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 from the clipboard. 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: ({ ids }) => {\n saveTaskOrder(ids);\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: ({ ids }) => saveOrder(ids),\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`.\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: ({ ids }) => saveOrder(ids),\n});\n```\n\n### Custom identity function\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.getAttribute('data-id')!,\n onReorder: ({ ids }) => saveOrder(ids),\n});\n```\n\n### Dynamic lists\n\nCall `sortable.sync()` after adding, removing, or replacing sortable items.\n\n```ts\nconst item = document.createElement('li');\nitem.dataset.sortId = 'task-4';\nitem.textContent = 'Deploy';\nlistEl.appendChild(item);\nsortable.sync();\n```\n\n### Disabled state\n\n```ts\nimport { createSortable, type SortableOptions } from '@vielzeug/dnd';\n\nconst options: SortableOptions = {\n disabled: false,\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ ids }) => saveOrder(ids),\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';\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: ({ ids }) => {\n items = applyReorder(items, ids, (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: ({ ids }) => saveOrder(ids),\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 | undefined;\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onBeforeReorder: () => {\n layout = captureLayout(listEl.querySelectorAll('[data-sort-id]'), {\n getKey: (el) => el.dataset.sortId!,\n });\n },\n onReorder: ({ ids }) => {\n saveOrder(ids); // 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 stays dependency-free: the application chooses to install and import Necromancer when it wants this integration.\n\n### Optimistic updates and revert\n\nCall `sortable.revert()` to roll back the most recent reorder. Register a revert function via `setRevert` inside `onReorder`.\n\n```ts\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ ids, setRevert }) => {\n const prev = currentOrder;\n setOrder(ids); // optimistic update\n setRevert(() => setOrder(prev)); // registered for sortable.revert()\n },\n});\n\n// On server error:\ntry {\n await api.saveOrder(currentOrder);\n} catch {\n sortable.revert();\n}\n```\n\n## Touch Support\n\nHTML5 drag-and-drop has no native touch story. 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';\n\nusing scope = createSortableScope({ touch: true });\nusing sortable = createSortable({ element: listEl, getKey: (el) => el.dataset.id!, scope });\n```\n\nThe scope tracks the touch that initiated the drag by its identifier. Additional fingers cannot move, finish, or replace the active drag. If the initiating touch is cancelled, Dnd 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 // 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 draggable items get `touch-action: none`\n\n`createSortable` sets `touch-action: none` on every element it marks as draggable (the item itself, or the handle when `handle` is set). This prevents a mobile browser from treating the initial movement as page scrolling before the scope controller can start the drag.\n\nThis has no effect on mouse/pointer input.\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';\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';\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: ({ ids }) => {\n items.current = applyReorder(items.current, ids, (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';\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: ({ ids }) => {\n orderedItems.value = applyReorder(orderedItems.value, ids, (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';\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: ({ ids }) => { items = applyReorder(items, ids, (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';\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: ({ ids }) => save(ids),\n });\n return () => sortable.dispose();\n });\n\n return html`<slot></slot>`;\n },\n});\n```\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 to keep your data array in sync with DOM order.\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
|
+
"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
|
+
},
|
|
9
|
+
"examples": [
|
|
10
|
+
{
|
|
11
|
+
"id": "drop-zone-accept",
|
|
12
|
+
"code": "import { createDropZone } from '@vielzeug/dnd'\n\nconst app = document.createElement('div')\napp.style.cssText = 'display:flex;flex-direction:column;gap:12px;align-items:flex-start;'\ndocument.body.appendChild(app)\n\nconst button = document.createElement('button')\nbutton.type = 'button'\nbutton.style.cssText = 'padding:8px 12px;border:1px solid #d1d5db;border-radius:8px;background:#fff;cursor:pointer;font:inherit;'\napp.appendChild(button)\n\nconst dropEl = document.createElement('div')\ndropEl.style.cssText = 'width:300px;height:200px;border:2px dashed #ccc;border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;background:#fff;transition:border-color 120ms ease, background 120ms ease, opacity 120ms ease;'\napp.appendChild(dropEl)\n\nconst title = document.createElement('span')\nconst hint = document.createElement('small')\nhint.style.color = '#666'\ndropEl.append(title, hint)\n\nconst options = {\n element: dropEl,\n accept: ['image/*', '.pdf'],\n disabled: false,\n onDrop: (files) => {\n console.log('Accepted files:')\n files.forEach(f => console.log(' ✓', f.name))\n },\n onDropRejected: (files) => {\n console.log('Rejected files (wrong type):')\n files.forEach(f => console.log(' ✗', f.name, '-', f.type || 'unknown'))\n },\n onHoverChange: (hovered) => {\n render(hovered)\n },\n}\n\nconst zone = createDropZone(options)\n\nconst render = (hovered = false) => {\n button.textContent = options.disabled ? 'Enable drop zone' : 'Disable drop zone'\n title.textContent = options.disabled ? 'Drop zone disabled' : hovered ? 'Release to drop files' : 'Drop images or PDFs here'\n hint.textContent = options.disabled ? 'Drops are ignored while disabled' : 'Accepted: image/* and .pdf'\n dropEl.style.opacity = options.disabled ? '0.6' : '1'\n dropEl.style.borderColor = options.disabled ? '#94a3b8' : hovered ? '#10b981' : '#ccc'\n dropEl.style.background = !options.disabled && hovered ? '#ecfdf5' : '#fff'\n}\n\nbutton.addEventListener('click', () => {\n options.disabled = !options.disabled\n render()\n console.log('Disabled:', options.disabled)\n})\n\nrender()\nconsole.log('Drop zone ready. Current hover state:', zone.hovered)",
|
|
13
|
+
"name": "createDropZone - Accept Filter"
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"id": "drop-zone-basic",
|
|
17
|
+
"code": "import { createDropZone } from '@vielzeug/dnd'\n\nconst dropEl = document.createElement('div')\ndropEl.id = 'drop-zone'\ndropEl.style.cssText = 'width:300px;height:200px;border:2px dashed #ccc;display:flex;align-items:center;justify-content:center;cursor:pointer;'\ndropEl.textContent = 'Drop files here'\ndocument.body.appendChild(dropEl)\n\nconst zone = createDropZone({\n element: dropEl,\n onDrop: (files) => {\n console.log('Dropped', files.length, 'file(s):')\n files.forEach(f => console.log(` - ${f.name} (${f.type}) - ${Math.round(f.size / 1024)}KB`))\n },\n onHoverChange: (hovered) => {\n dropEl.style.borderColor = hovered ? '#3b82f6' : '#ccc'\n dropEl.style.background = hovered ? '#eff6ff' : ''\n dropEl.textContent = hovered ? 'Release to drop!' : 'Drop files here'\n },\n})\n\nconsole.log('Drop zone created and attached to #drop-zone')\nconsole.log('API: zone.hovered =', zone.hovered)\nconsole.log('Tip: Try dragging files over the drop zone element')",
|
|
18
|
+
"name": "createDropZone - Basic"
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"id": "drop-zone-disposal",
|
|
22
|
+
"code": "import { createDropZone } from '@vielzeug/dnd'\n\nconst dropEl = document.createElement('div')\ndropEl.style.cssText = 'width:300px;height:150px;border:2px dashed #ccc;display:flex;align-items:center;justify-content:center;'\ndropEl.textContent = 'Drop files here'\ndocument.body.appendChild(dropEl)\n\nconst zone = createDropZone({\n element: dropEl,\n onDrop: (files) => console.log('Dropped:', files.map(f => f.name)),\n onHoverChange: (hovered) => {\n dropEl.style.borderColor = hovered ? '#3b82f6' : '#ccc'\n },\n})\n\nconsole.log('zone.disposed:', zone.disposed) // false\nconsole.log('zone.disposalSignal.aborted:', zone.disposalSignal.aborted) // false\n\n// Use disposalSignal to cancel an in-flight request when the zone is torn down\nconst signal = zone.disposalSignal\nsignal.addEventListener('abort', () => {\n console.log('disposalSignal fired — zone was disposed')\n})\n\n// Dispose after 2 seconds to demonstrate\nsetTimeout(() => {\n zone.dispose()\n console.log('zone.disposed:', zone.disposed) // true\n console.log('zone.disposalSignal.aborted:', zone.disposalSignal.aborted) // true\n\n // dispose() is idempotent — calling it again is safe\n zone.dispose()\n console.log('Second dispose() call did not throw')\n}, 2000)",
|
|
23
|
+
"name": "DropZone — disposed & disposalSignal"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"id": "drop-zone-matches-accept",
|
|
27
|
+
"code": "import { matchesAccept } from '@vielzeug/dnd'\n\n// matchesAccept tests a File against an accept pattern list\nconst png = new File([''], 'photo.png', { type: 'image/png' })\nconst pdf = new File([''], 'report.pdf', { type: 'application/pdf' })\nconst txt = new File([''], 'readme.txt', { type: 'text/plain' })\n\nconsole.log('--- MIME wildcard ---')\nconsole.log('image/* matches photo.png:', matchesAccept(png, ['image/*'])) // true\nconsole.log('image/* matches report.pdf:', matchesAccept(pdf, ['image/*'])) // false\n\nconsole.log('--- File extension ---')\nconsole.log('.pdf matches report.pdf:', matchesAccept(pdf, ['.pdf'])) // true\nconsole.log('.PDF matches report.pdf:', matchesAccept(pdf, ['.PDF'])) // true — case-insensitive\nconsole.log('.pdf matches photo.png:', matchesAccept(png, ['.pdf'])) // false\n\nconsole.log('--- Exact MIME type ---')\nconsole.log('image/png matches photo.png:', matchesAccept(png, ['image/png'])) // true\nconsole.log('image/jpeg matches photo.png:', matchesAccept(png, ['image/jpeg'])) // false\n\nconsole.log('--- Empty list accepts everything ---')\nconsole.log('[] matches readme.txt:', matchesAccept(txt, [])) // true\n\nconsole.log('--- Combined list ---')\nconst accept = ['image/*', '.pdf']\nconsole.log('Combined matches photo.png:', matchesAccept(png, accept)) // true\nconsole.log('Combined matches report.pdf:', matchesAccept(pdf, accept)) // true\nconsole.log('Combined matches readme.txt:', matchesAccept(txt, accept)) // false",
|
|
28
|
+
"name": "matchesAccept - Accept Pattern Testing"
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"id": "drop-zone-validate",
|
|
32
|
+
"code": "import { createDropZone } from '@vielzeug/dnd'\n\nconst app = document.createElement('div')\napp.style.cssText = 'display:flex;flex-direction:column;gap:12px;width:320px;'\ndocument.body.appendChild(app)\n\nconst dropEl = document.createElement('div')\ndropEl.style.cssText = 'height:160px;border:2px dashed #d1d5db;border-radius:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;background:#fff;transition:all 120ms ease;'\napp.appendChild(dropEl)\n\nconst statusEl = document.createElement('div')\nstatusEl.style.cssText = 'font-size:13px;color:#6b7280;min-height:20px;'\napp.appendChild(statusEl)\n\nconst title = document.createElement('span')\ntitle.style.cssText = 'font-size:14px;color:#374151;'\ntitle.textContent = 'Drop images here'\n\nconst hint = document.createElement('small')\nhint.style.cssText = 'font-size:12px;color:#9ca3af;'\nhint.textContent = 'Max 2 MB each — async size check via onValidate'\n\ndropEl.append(title, hint)\n\n// Simulate async server-side quota check\nconst simulatedValidate = async (files) => {\n statusEl.textContent = 'Checking file size…'\n await new Promise(res => setTimeout(res, 600))\n const allUnder2MB = files.every(f => f.size < 2_097_152)\n return allUnder2MB\n}\n\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*'],\n onValidate: simulatedValidate,\n onDrop: (files) => {\n statusEl.textContent = ''\n console.log('Accepted:', files.map(f => `${f.name} (${Math.round(f.size / 1024)}KB)`).join(', '))\n },\n onDropRejected: (files) => {\n statusEl.textContent = ''\n console.log('Rejected:', files.map(f => f.name).join(', '))\n },\n onHoverChange: (hovered) => {\n dropEl.style.borderColor = hovered ? '#3b82f6' : '#d1d5db'\n dropEl.style.background = hovered ? '#eff6ff' : '#fff'\n title.textContent = hovered ? 'Release to drop!' : 'Drop images here'\n },\n})\n\nconsole.log('Drop zone with onValidate ready')\nconsole.log('zone.validating starts false:', zone.validating)",
|
|
33
|
+
"name": "createDropZone - Async Validate"
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"id": "sortable-connected",
|
|
37
|
+
"code": "import { applyReorder, createSortable, createSortableScope } from '@vielzeug/dnd'\n\nconst scope = createSortableScope({\n onMove: ({ source, sourceIds, target, targetIds }) => {\n if (source === todoEl) todoItems = applyReorder(todoItems, sourceIds, i => i.id)\n if (target === todoEl) todoItems = applyReorder(todoItems, targetIds, i => i.id)\n if (source === doneEl) doneItems = applyReorder(doneItems, sourceIds, i => i.id)\n if (target === doneEl) doneItems = applyReorder(doneItems, targetIds, i => i.id)\n console.log('Moved item between lists')\n },\n})\n\nconst wrapper = document.createElement('div')\nwrapper.style.cssText = 'display:flex;gap:24px;align-items:flex-start;'\ndocument.body.appendChild(wrapper)\n\nlet todoItems = [\n { id: 'task-a', title: 'Design' },\n { id: 'task-b', title: 'Develop' },\n { id: 'task-c', title: 'Review' },\n]\nlet doneItems = [\n { id: 'task-d', title: 'Planning' },\n]\n\nconst itemStyle = 'padding:8px 12px;background:#fff;border:1px solid #e5e7eb;border-radius:6px;cursor:grab;font-size:14px;'\nconst listStyle = 'list-style:none;padding:8px;margin:0;min-height:48px;width:160px;background:#f9fafb;border:2px dashed #d1d5db;border-radius:8px;display:flex;flex-direction:column;gap:6px;'\n\nfunction makeColumn(label) {\n const col = document.createElement('div')\n col.style.cssText = 'display:flex;flex-direction:column;gap:8px;'\n const heading = document.createElement('strong')\n heading.style.cssText = 'font-size:13px;color:#374151;'\n heading.textContent = label\n const ul = document.createElement('ul')\n ul.style.cssText = listStyle\n col.append(heading, ul)\n wrapper.appendChild(col)\n return ul\n}\n\nconst todoEl = makeColumn('To Do')\nconst doneEl = makeColumn('Done')\n\nfunction renderList(ul, items) {\n ul.innerHTML = ''\n items.forEach(item => {\n const li = document.createElement('li')\n li.dataset.id = item.id\n li.style.cssText = itemStyle\n li.textContent = item.title\n ul.appendChild(li)\n })\n}\n\nrenderList(todoEl, todoItems)\nrenderList(doneEl, doneItems)\n\nconst getKey = (el) => el.dataset.id ?? ''\n\nconst todoSortable = createSortable({\n element: todoEl,\n getKey,\n scope,\n})\n\nconst doneSortable = createSortable({\n element: doneEl,\n getKey,\n scope,\n})\n\nconsole.log('Connected lists ready — drag items between columns')\nconsole.log('Scope is shared:', typeof scope)",
|
|
38
|
+
"name": "createSortableScope - Connected Lists"
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
"id": "sortable-list",
|
|
42
|
+
"code": "import { createSortable } from '@vielzeug/dnd'\n\nconst listEl = document.createElement('ul')\nlistEl.id = 'sortable-list'\nlistEl.style.cssText = 'list-style: none; padding: 0; margin: 0; width: 200px;'\ndocument.body.appendChild(listEl)\n\nconst items = [\n { id: 'item-1', label: 'Item One' },\n { id: 'item-2', label: 'Item Two' },\n { id: 'item-3', label: 'Item Three' },\n { id: 'item-4', label: 'Item Four' },\n]\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.id ?? '',\n onReorder: ({ ids }) => {\n console.log('Reordered:', ids.join(' → '))\n render(ids)\n sortable.sync()\n },\n})\n\nfunction render(order) {\n listEl.innerHTML = ''\n order.forEach(id => {\n const item = items.find(i => i.id === id)\n const li = document.createElement('li')\n li.dataset.id = item.id\n li.textContent = item.label\n li.style.cssText = 'padding: 10px; margin: 4px 0; background: #f0f0f0; border-radius: 4px; cursor: grab;'\n listEl.appendChild(li)\n })\n}\n\nrender(items.map(i => i.id))\nsortable.sync()\n\nconsole.log('✓ Sortable list created at #sortable-list')",
|
|
43
|
+
"name": "createSortable - Drag to Reorder"
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"id": "sortable-revert",
|
|
47
|
+
"code": "import { applyReorder, createSortable } from '@vielzeug/dnd'\n\nconst app = document.createElement('div')\napp.style.cssText = 'display:flex;flex-direction:column;gap:12px;width:220px;'\ndocument.body.appendChild(app)\n\nconst listEl = document.createElement('ul')\nlistEl.style.cssText = 'list-style:none;padding:0;margin:0;display:flex;flex-direction:column;gap:6px;'\napp.appendChild(listEl)\n\nconst revertBtn = document.createElement('button')\nrevertBtn.type = 'button'\nrevertBtn.textContent = 'Revert last reorder'\nrevertBtn.style.cssText = 'padding:7px 14px;border:1px solid #d1d5db;border-radius:6px;background:#fff;cursor:pointer;font:inherit;font-size:13px;'\napp.appendChild(revertBtn)\n\nlet items = [\n { id: 'a', label: 'Alpha' },\n { id: 'b', label: 'Beta' },\n { id: 'c', label: 'Gamma' },\n { id: 'd', label: 'Delta' },\n]\n\nfunction render() {\n listEl.innerHTML = ''\n items.forEach(item => {\n const li = document.createElement('li')\n li.dataset.id = item.id\n li.style.cssText = 'padding:9px 14px;background:#fff;border:1px solid #e5e7eb;border-radius:6px;cursor:grab;font-size:14px;'\n li.textContent = item.label\n listEl.appendChild(li)\n })\n sortable?.sync()\n}\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.id ?? '',\n onReorder: ({ ids, setRevert }) => {\n const prev = items\n items = applyReorder(items, ids, i => i.id)\n render()\n console.log('Reordered:', items.map(i => i.label).join(' → '))\n setRevert(() => {\n items = prev\n render()\n console.log('Reverted to:', items.map(i => i.label).join(' → '))\n })\n },\n})\n\nrevertBtn.addEventListener('click', () => sortable.revert())\n\nrender()\nconsole.log('Drag to reorder, then click Revert to undo the last move')",
|
|
48
|
+
"name": "createSortable - Optimistic Revert"
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
"id": "sortable-with-handle",
|
|
52
|
+
"code": "import { createSortable } from '@vielzeug/dnd'\n\nconst listEl = document.createElement('ul')\nlistEl.style.cssText = 'list-style:none;padding:0;width:250px;'\ndocument.body.appendChild(listEl)\n\nconst tasks = [\n { id: 'task-a', title: 'Design UI' },\n { id: 'task-b', title: 'Write tests' },\n { id: 'task-c', title: 'Deploy to prod' },\n]\n\ntasks.forEach(task => {\n const li = document.createElement('li')\n li.dataset.id = task.id\n li.style.cssText = 'display:flex;align-items:center;gap:8px;padding:8px;margin:4px 0;background:#fff;border:1px solid #e5e5e5;border-radius:4px;'\n\n const handle = document.createElement('span')\n handle.className = 'drag-handle'\n handle.textContent = '⬣'\n handle.style.cssText = 'cursor:grab;color:#888;font-size:18px;'\n\n const label = document.createElement('span')\n label.textContent = task.title\n\n li.appendChild(handle)\n li.appendChild(label)\n listEl.appendChild(li)\n})\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.id ?? '',\n handle: '.drag-handle',\n onReorder: ({ ids }) => console.log('Reordered:', ids),\n})\n\nconsole.log('Handle-based sortable created. isDragging:', sortable.isDragging)",
|
|
53
|
+
"name": "createSortable - Drag Handle"
|
|
54
|
+
}
|
|
55
|
+
],
|
|
56
|
+
"typeSignatures": {
|
|
57
|
+
"DndError": "export { DndError, DndScopeError } from './errors';",
|
|
58
|
+
"DndScopeError": "export { DndError, DndScopeError } from './errors';",
|
|
59
|
+
"matchesAccept": "export function matchesAccept(file: File, accept: string[]): boolean {\n if (!accept.length) return true;\n\n return accept.some((pattern) => {\n const p = pattern.trim();\n\n if (p.startsWith('.')) return file.name.toLowerCase().endsWith(p.toLowerCase());\n\n if (p.endsWith('/*')) return file.type.startsWith(p.slice(0, -1));\n\n return file.type === p;\n });\n}",
|
|
60
|
+
"DropZoneOptions": "export interface DropZoneOptions {\n /**\n * Accepted file types. Each entry may be:\n * - A MIME type: 'image/png'\n * - A MIME wildcard: 'image/*'\n * - A file extension: '.pdf'\n *\n * When empty the zone accepts everything.\n */\n accept?: string[];\n /**\n * When `true`, all drag events are ignored and hover state does not change.\n *\n * Note: a disabled zone does not call `preventDefault` on drag or paste events,\n * so underlying elements (such as text editors) will still receive them.\n */\n disabled?: boolean;\n /**\n * The `dropEffect` to set on `dataTransfer` during `dragover`.\n * @default 'copy'\n */\n dropEffect?: DataTransfer['dropEffect'];\n /** The element to attach drag listeners to. */\n element: HTMLElement;\n /**\n * Maximum number of files accepted per drop. Files beyond this limit are\n * treated as rejected and forwarded to `onDropRejected`.\n *\n * When omitted there is no limit.\n */\n maxFiles?: number;\n /** Called when files are dropped or pasted (when `paste: true` and `onPaste` is omitted). Receives accepted files only. */\n onDrop?: (files: File[]) => void;\n /**\n * Called when dropped or pasted files are rejected by the `accept` filter, `maxFiles` limit, or `onValidate`.\n */\n onDropRejected?: (files: File[]) => void;\n /**\n * Called whenever hover state toggles.\n * Use this for drag-over styling.\n */\n onHoverChange?: (hovered: boolean) => void;\n /**\n * Called when files are pasted via the clipboard. Falls back to `onDrop` when omitted.\n * Only active when `paste: true`.\n */\n onPaste?: (files: File[]) => void;\n /**\n * Optional async file gating. Called after type/extension filtering, before `onDrop`.\n * Return (or resolve) `false` to move all type-accepted files to `onDropRejected`.\n *\n * Only receives type-accepted files (after `accept` and `maxFiles` filtering).\n * Files already rejected by the `accept` filter are forwarded to `onDropRejected`\n * unconditionally and are not passed to this function.\n *\n * While validation is in progress `zone.validating` is `true` and `onValidatingChange`\n * is called with `true`.\n *\n * @example\n * ```ts\n * onValidate: async (files, { signal }) => {\n * const ok = await checkServerQuota(files, { signal });\n * return ok;\n * }\n * ```\n */\n onValidate?: (files: File[], context: DropValidationContext) => boolean | Promise<boolean>;\n /**\n * Called whenever the async validation state changes.\n * Use this to drive loading spinners.\n *\n * @example\n * ```ts\n * onValidatingChange: (v) => { spinnerEl.hidden = !v; }\n * ```\n */\n onValidatingChange?: (validating: boolean) => void;\n /**\n * When `true`, a `paste` event listener is added to `window`. Pasted files run\n * through the same `accept`, `maxFiles`, and `onValidate` pipeline as dropped files.\n * @default false\n */\n paste?: boolean;\n}",
|
|
61
|
+
"DropValidationContext": "export interface DropValidationContext {\n /** Aborts when the zone is disposed. Pass this to validation requests. */\n readonly signal: AbortSignal;\n}",
|
|
62
|
+
"DropZone": "export interface DropZone extends Disposable {\n /** Whether the pointer is currently dragging over the zone. */\n readonly hovered: boolean;\n /** `true` while an `onValidate` promise is pending. */\n readonly validating: boolean;\n}",
|
|
63
|
+
"createDropZone": "export function createDropZone(options: DropZoneOptions): DropZone {\n const {\n accept = [],\n dropEffect = 'copy',\n element,\n maxFiles,\n onDrop,\n onDropRejected,\n onHoverChange,\n onValidatingChange,\n } = options;\n\n let dragCounter = 0;\n // Whether the *current* drag's payload passes the accept filter.\n // Determined on the first dragenter and held for the duration of the drag.\n let dragAccepted = false;\n let validating = false;\n const validationControllers = new Set<AbortController>();\n\n const setValidating = (next: boolean): void => {\n if (validating === next) return;\n\n validating = next;\n onValidatingChange?.(next);\n };\n\n const updateCounter = (next: number): void => {\n const wasHovered = dragCounter > 0 && dragAccepted;\n\n dragCounter = Math.max(0, next);\n\n // Reset acceptance state when the drag fully leaves so the next drag starts clean.\n if (dragCounter === 0) dragAccepted = false;\n\n const hovered = dragCounter > 0 && dragAccepted;\n\n if (hovered !== wasHovered) onHoverChange?.(hovered);\n };\n\n const resetCounter = (): void => {\n updateCounter(0);\n };\n\n const disposable = createDisposable(() => {\n for (const controller of validationControllers) controller.abort();\n\n validationControllers.clear();\n resetCounter();\n });\n\n // Settle the final accepted/rejected split and fire callbacks.\n const settle = (acceptedFiles: File[], rejectedFiles: File[]): void => {\n if (acceptedFiles.length > 0) onDrop?.(acceptedFiles);\n\n if (rejectedFiles.length > 0) onDropRejected?.(rejectedFiles);\n };\n\n // Settle for paste events (which may use onPaste instead of onDrop).\n const settleForPaste = (acceptedFiles: File[], rejectedFiles: File[]): void => {\n if (acceptedFiles.length > 0) {\n if (options.onPaste) {\n options.onPaste(acceptedFiles);\n } else {\n onDrop?.(acceptedFiles);\n }\n }\n\n if (rejectedFiles.length > 0) onDropRejected?.(rejectedFiles);\n };\n\n // Run accept/maxFiles filter, then async onValidate, then settle.\n const dispatchWithValidation = (rawFiles: File[], settleFn: (accepted: File[], rejected: File[]) => void): void => {\n const { accepted, rejected: rej } = applyFileFilters(rawFiles, accept, maxFiles);\n const onValidate = options.onValidate;\n const validationController = onValidate && accepted.length > 0 ? new AbortController() : null;\n\n if (validationController) {\n validationControllers.add(validationController);\n setValidating(true);\n }\n\n const finishValidation = (): void => {\n if (!validationController) return;\n\n validationControllers.delete(validationController);\n\n if (!disposable.disposed) setValidating(validationControllers.size > 0);\n };\n\n let validation: boolean | Promise<boolean>;\n\n try {\n validation =\n validationController && onValidate ? onValidate(accepted, { signal: validationController.signal }) : true;\n } catch (error) {\n validation = Promise.reject(error);\n }\n\n void Promise.resolve(validation)\n .then((valid) => {\n finishValidation();\n\n if (disposable.disposed) return;\n\n if (valid) {\n settleFn(accepted, rej);\n } else {\n // validation failed — all type-accepted files become rejected\n settleFn([], [...rej, ...accepted]);\n }\n })\n .catch(() => {\n finishValidation();\n\n if (disposable.disposed) return;\n\n settleFn([], [...rej, ...accepted]);\n });\n };\n\n const handleDragEnter = (e: DragEvent): void => {\n if (resolveDisabled(options.disabled)) return;\n\n e.preventDefault();\n\n // Evaluate the filter once per drag (on first entry) — the payload is\n // constant for the lifetime of a drag operation.\n if (dragCounter === 0) {\n const items = e.dataTransfer?.items;\n\n dragAccepted = !accept.length || !items?.length || itemsMatchAccept(items, accept);\n }\n\n if (!dragAccepted && e.dataTransfer) {\n e.dataTransfer.dropEffect = 'none';\n }\n\n // Always increment so every dragenter is paired with its dragleave,\n // regardless of acceptance. This prevents counter under-runs.\n updateCounter(dragCounter + 1);\n };\n\n const handleDragOver = (e: DragEvent): void => {\n if (resolveDisabled(options.disabled)) return;\n\n e.preventDefault();\n\n if (e.dataTransfer) e.dataTransfer.dropEffect = dragAccepted ? dropEffect : 'none';\n };\n\n const handleDragLeave = (_e: DragEvent): void => {\n // Always decrement to balance the paired dragenter — disabling after enter\n // must not leave the counter permanently incremented.\n updateCounter(dragCounter - 1);\n };\n\n const handleDrop = (e: DragEvent): void => {\n // Reset counter first (idempotent at 0) so hover never sticks even when disabled.\n resetCounter();\n\n if (resolveDisabled(options.disabled)) return;\n\n e.preventDefault();\n\n const raw = e.dataTransfer?.files;\n\n if (!raw) return;\n\n dispatchWithValidation(Array.from(raw), settle);\n };\n\n const handlePaste = (e: ClipboardEvent): void => {\n if (resolveDisabled(options.disabled)) return;\n\n const clipFiles = e.clipboardData?.files;\n\n if (!clipFiles?.length) return;\n\n e.preventDefault();\n dispatchWithValidation(Array.from(clipFiles), settleForPaste);\n };\n\n element.addEventListener('dragenter', handleDragEnter, { signal: disposable.disposalSignal });\n element.addEventListener('dragover', handleDragOver, { signal: disposable.disposalSignal });\n element.addEventListener('dragleave', handleDragLeave, { signal: disposable.disposalSignal });\n element.addEventListener('drop', handleDrop, { signal: disposable.disposalSignal });\n\n if (options.paste) window.addEventListener('paste', handlePaste, { signal: disposable.disposalSignal });\n\n // These global listeners catch drags that end outside the zone.\n // The window 'drop' also fires for in-zone drops, but resetCounter() is idempotent at counter=0.\n window.addEventListener('dragend', resetCounter, { signal: disposable.disposalSignal });\n window.addEventListener('drop', resetCounter, { signal: disposable.disposalSignal });\n\n return {\n get disposalSignal() {\n return disposable.disposalSignal;\n },\n dispose: disposable.dispose,\n get disposed() {\n return disposable.disposed;\n },\n get hovered() {\n return dragCounter > 0 && dragAccepted;\n },\n [Symbol.dispose]: disposable[Symbol.dispose],\n get validating() {\n return validating;\n },\n };\n}",
|
|
64
|
+
"SortableScope": "export interface SortableScope extends Disposable {\n /** `true` while any sortable in this scope is actively dragging. */\n readonly isDragging: boolean;\n /**\n * Calls the revert function registered for the most recent cross-container move.\n * A no-op when no move registered a revert function.\n */\n revert(): void;\n readonly [SCOPE_BRAND]: true;\n}",
|
|
65
|
+
"AutoScrollOptions": "export interface AutoScrollOptions {\n /** Scroll the sortable container while dragging near its edges. @default true */\n container?: boolean;\n /** Distance in pixels from an edge that triggers auto-scroll. @default 32 */\n edgeThreshold?: number;\n /** Pixels scrolled per dragover frame while near an edge. @default 18 */\n speed?: number;\n /** Scroll the viewport while dragging near the window edges. @default false */\n viewport?: boolean;\n}",
|
|
66
|
+
"ReorderEvent": "export interface ReorderEvent {\n /** The new ordered list of item keys after the reorder. */\n ids: string[];\n /**\n * Register a revert function that will be called when `sortable.revert()` is invoked.\n * Useful for rolling back optimistic UI updates on server error.\n * Only the most recent `setRevert` registration is retained — a new reorder overwrites it.\n *\n * @example\n * ```ts\n * onReorder: ({ ids, setRevert }) => {\n * const prev = order;\n * setOrder(ids);\n * setRevert(() => setOrder(prev));\n * },\n * ```\n */\n setRevert(fn: () => void): void;\n}",
|
|
67
|
+
"SortableMoveEvent": "export interface SortableMoveEvent {\n /** Stable identity of the moved item. */\n readonly itemId: string;\n /** Registers a rollback for the most recent scope move. */\n setRevert(fn: () => void): void;\n /** Source container before the move. */\n readonly source: HTMLElement;\n /** Ordered source item IDs after the move. */\n readonly sourceIds: string[];\n /** Target container after the move. */\n readonly target: HTMLElement;\n /** Ordered target item IDs after the move. */\n readonly targetIds: string[];\n}",
|
|
68
|
+
"SortableScopeOptions": "export interface SortableScopeOptions {\n /**\n * Called exactly once for every successful cross-container move.\n * Local reorders continue to use each sortable's `onReorder` callback.\n */\n onMove?: (event: SortableMoveEvent) => void;\n /**\n * Enables touch input for sortable items registered to this scope.\n * The controller ignores unrelated document draggables.\n */\n touch?: boolean | TouchInputOptions;\n}",
|
|
69
|
+
"SortableTouchOptions": "export type SortableTouchOptions = TouchInputOptions;",
|
|
70
|
+
"SortableOptions": "export interface SortableOptions {\n /** Auto-scrolls the container (and viewport) near edges while dragging. @default true */\n autoScroll?: boolean | AutoScrollOptions;\n /** Sorting axis used to compute insertion position. @default 'vertical' */\n axis?: 'vertical' | 'horizontal';\n /**\n * When `true`, drag interactions are ignored.\n *\n * Note: if `disabled` transitions to `true` while a drag is in progress the\n * drag is treated as a cancellation — the item snaps back to its original\n * position rather than committing the last placeholder location.\n */\n disabled?: boolean;\n /** Optional custom drag preview element. */\n dragImage?: HTMLElement | ((id: string, item: HTMLElement, event: DragEvent) => HTMLElement | null | undefined);\n /**\n * Hotspot offset `[x, y]` passed to `setDragImage`.\n * Controls which point of the preview image follows the cursor.\n * @default [0, 0]\n */\n dragImageOffset?: [number, number];\n /** Container element whose direct-child items are sortable. */\n element: HTMLElement;\n /**\n * Returns the identity key for a given item element.\n * This separates the \"what is this item?\" concern (yours) from the \"which children\n * are sortable?\" concern (ours — marked with `data-dnd-item`).\n *\n * @example\n * ```ts\n * getKey: (el) => el.dataset.taskId!\n * ```\n */\n getKey: (element: HTMLElement) => string;\n /**\n * Selector for the drag handle inside each item.\n * When omitted the whole item is the handle.\n */\n handle?: string;\n /**\n * Enables keyboard-based reordering using arrow keys plus Home/End.\n * @default true\n */\n keyboard?: boolean;\n /**\n * Called just before a successful drag commit with the before and after order snapshots.\n * Use this hook to set up FLIP animations — the source items are still in their\n * pre-commit positions at the time of the call.\n *\n * @example\n * ```ts\n * onBeforeReorder: (from, to) => {\n * // record element positions here, then animate after the next microtask\n * }\n * ```\n */\n onBeforeReorder?: (from: string[], to: string[]) => void;\n /** Called when a drag ends (whether dropped or cancelled). */\n onDragEnd?: (id: string, event: DragEvent) => void;\n /** Called when the user starts dragging an item. */\n onDragStart?: (id: string, event: DragEvent) => void;\n /**\n * Called with a {@link ReorderEvent} after a successful reorder, only when the order changed.\n *\n * @example\n * ```ts\n * onReorder: ({ ids, setRevert }) => {\n * const prev = order;\n * setOrder(ids);\n * setRevert(() => setOrder(prev));\n * },\n * ```\n */\n onReorder?: (event: ReorderEvent) => void;\n /** CSS class applied to the placeholder element. @default 'dnd-placeholder' */\n placeholderClass?: string;\n /** Shared scope for connected sortable containers. Containers only exchange items within the same scope. */\n scope?: SortableScope;\n}",
|
|
71
|
+
"Sortable": "export interface Sortable extends Disposable {\n readonly isDragging: boolean;\n /**\n * Calls the revert function registered via `setRevert` in the last `onReorder` invocation (if any) and clears it.\n * A no-op when no revert function was registered or has already been consumed.\n *\n * Works for both drag-based and keyboard-based reorders.\n * Note: only the most recent reorder can be reverted; a new reorder overwrites the stored function.\n *\n * @example\n * ```ts\n * onReorder: ({ ids, setRevert }) => {\n * const prev = order;\n * setOrder(ids);\n * setRevert(() => setOrder(prev));\n * },\n * // later, on server error:\n * sortable.revert();\n * ```\n */\n revert(): void;\n /**\n * Re-reads the container's children and reapplies `draggable`, ARIA roles,\n * and handle attributes. Call this after programmatically adding, removing,\n * or replacing items — e.g. after a framework render that replaces DOM nodes.\n *\n * Not needed when items are only reordered via drag or keyboard.\n */\n sync(): void;\n}",
|
|
72
|
+
"createSortableScope": "export function createSortableScope(options: SortableScopeOptions = {}): SortableScope {\n const state: SortableScopeState = {\n active: null,\n commitMove(event): void {\n options.onMove?.({\n ...event,\n setRevert(fn): void {\n state.lastRevert = fn;\n },\n });\n },\n disposables: new Set(),\n handles: new Set(),\n lastRevert: null,\n touch: null,\n };\n const disposable = createDisposable(() => {\n state.touch?.dispose();\n\n // Dispose all registered sortables (each dispose() call is idempotent)\n for (const disposeFn of state.disposables) {\n disposeFn();\n }\n });\n\n const scope = {\n get disposalSignal() {\n return disposable.disposalSignal;\n },\n dispose: disposable.dispose,\n get disposed() {\n return disposable.disposed;\n },\n get isDragging() {\n return state.active !== null;\n },\n revert() {\n state.lastRevert?.();\n state.lastRevert = null;\n },\n [SCOPE_BRAND]: true as const,\n [Symbol.dispose]: disposable[Symbol.dispose],\n } as SortableScope;\n\n sortableScopeStates.set(scope, state);\n\n if (options.touch) {\n state.touch = createScopeTouchController(options.touch === true ? {} : options.touch, (target) => {\n for (const handle of state.handles) {\n const dragTarget = handle.resolveTouchTarget(target);\n\n if (dragTarget) return dragTarget;\n }\n\n return null;\n });\n }\n\n return scope;\n}",
|
|
73
|
+
"createSortable": "export function createSortable(options: SortableOptions): Sortable {\n const {\n autoScroll = true,\n axis = 'vertical',\n element,\n getKey,\n handle,\n keyboard = true,\n placeholderClass = 'dnd-placeholder',\n scope = createSortableScope(),\n } = options;\n const autoScrollOptions = resolveAutoScrollOptions(autoScroll);\n const scopeState = getSortableScopeState(scope);\n\n if (handle !== undefined && handle.trim() === '') {\n warn(\n 'handle option is an empty string — no handle elements will be found. Provide a valid CSS selector or omit the option.',\n );\n }\n\n const getItems = (): HTMLElement[] =>\n Array.from(element.children).filter((c) => (c as HTMLElement).hasAttribute(ITEM_ATTR)) as HTMLElement[];\n\n const getOrderedIds = (): string[] => getItems().map((el) => getKey(el));\n const managedElements = new Map<HTMLElement, ManagedElementState>();\n const originalContainerRole = element.getAttribute('role');\n\n const rememberElement = (managedElement: HTMLElement): ManagedElementState => {\n const existing = managedElements.get(managedElement);\n\n if (existing) return existing;\n\n const state: ManagedElementState = {\n dataDndHandle: managedElement.getAttribute(HANDLE_ATTR),\n dataDndItem: managedElement.getAttribute(ITEM_ATTR),\n draggable: managedElement.getAttribute('draggable'),\n role: managedElement.getAttribute('role'),\n tabIndex: managedElement.getAttribute('tabindex'),\n touchAction: managedElement.style.touchAction,\n };\n\n managedElements.set(managedElement, state);\n\n return state;\n };\n\n const restoreAttribute = (managedElement: HTMLElement, name: string, value: string | null): void => {\n if (value === null) {\n managedElement.removeAttribute(name);\n } else {\n managedElement.setAttribute(name, value);\n }\n };\n\n const syncItems = (): void => {\n getItems().forEach((el) => {\n const itemState = rememberElement(el);\n\n if (itemState.role === null) el.setAttribute('role', 'listitem');\n\n if (itemState.tabIndex === null) el.tabIndex = 0;\n\n if (handle) {\n el.querySelectorAll<HTMLElement>(handle).forEach((handleEl) => {\n rememberElement(handleEl);\n handleEl.setAttribute(HANDLE_ATTR, '');\n handleEl.setAttribute('draggable', 'true');\n handleEl.style.touchAction = 'none';\n });\n } else {\n el.setAttribute('draggable', 'true');\n // A native mouse drag has no competing gesture to arbitrate; touch does. Without this,\n // a mobile browser can decide the very first bit of finger movement is a page\n // scroll/pan — a decision it makes independently of, and before, this library's own\n // touch-shim threshold/`preventDefault()` logic ever runs — and hand the rest of the\n // gesture to native scrolling. Once that happens the item never receives the\n // `dragover` sequence needed to update the drop target, so the session ends up\n // committing back to wherever it started: indistinguishable from the drop \"reverting\".\n // `touch-action: none` opts the element out of every default touch gesture from\n // `touchstart` onward, leaving the whole interaction to this library's own JS.\n el.style.touchAction = 'none';\n }\n });\n };\n\n const markItems = (): void => {\n const seenKeys = new Set<string>();\n\n // Mark all children that have a key as sortable items\n Array.from(element.children).forEach((child) => {\n const el = child as HTMLElement;\n\n try {\n const key = getKey(el);\n\n if (key) {\n rememberElement(el);\n\n if (seenKeys.has(key)) {\n warn(\n `getKey returned the duplicate key \"${key}\" for two sibling items — onReorder's ids and applyReorder may become inconsistent. Ensure getKey returns a unique value per item.`,\n );\n } else {\n seenKeys.add(key);\n }\n\n el.setAttribute(ITEM_ATTR, '');\n }\n } catch (err) {\n warn(\n `getKey threw for a child element — the item will not be sortable. Check your getKey implementation. ${String(err)}`,\n );\n }\n });\n\n syncItems();\n };\n\n const cleanupItems = (): void => {\n for (const [managedElement, state] of managedElements) {\n restoreAttribute(managedElement, HANDLE_ATTR, state.dataDndHandle);\n restoreAttribute(managedElement, ITEM_ATTR, state.dataDndItem);\n restoreAttribute(managedElement, 'draggable', state.draggable);\n restoreAttribute(managedElement, 'role', state.role);\n restoreAttribute(managedElement, 'tabindex', state.tabIndex);\n managedElement.style.touchAction = state.touchAction;\n }\n\n managedElements.clear();\n };\n\n const createPlaceholder = (source: HTMLElement): HTMLElement => {\n const p = document.createElement('div');\n\n p.className = placeholderClass;\n p.setAttribute('aria-hidden', 'true');\n\n if (axis === 'horizontal') {\n p.style.width = `${source.offsetWidth}px`;\n } else {\n p.style.height = `${source.offsetHeight}px`;\n }\n\n return p;\n };\n\n let lastRevert: (() => void) | null = null;\n\n const handle_: ContainerHandle = {\n commitReorder: (orderedIds) => {\n if (!options.onReorder) return;\n\n const event: ReorderEvent = {\n ids: orderedIds,\n setRevert(fn) {\n lastRevert = fn;\n },\n };\n\n options.onReorder(event);\n },\n element,\n getOrderedIds,\n isDisabled: () => resolveDisabled(options.disabled),\n notifyBeforeReorder: (from, to) => options.onBeforeReorder?.(from, to),\n notifyDragEnd: (id, event) => options.onDragEnd?.(id, event),\n notifyDragStart: (id, event) => options.onDragStart?.(id, event),\n resolveTouchTarget: (target) => {\n if (resolveDisabled(options.disabled) || !element.contains(target)) return null;\n\n const item = target.closest<HTMLElement>(`[${ITEM_ATTR}]`);\n\n if (!item || !element.contains(item)) return null;\n\n if (!handle) return item;\n\n const handleTarget = target.closest<HTMLElement>(handle);\n\n return handleTarget && item.contains(handleTarget) ? handleTarget : null;\n },\n };\n\n scopeState.handles.add(handle_);\n\n const handleDragStart = (e: DragEvent): void => {\n if (scopeState.active) return;\n\n if (handle_.isDisabled()) return;\n\n const target = e.target as HTMLElement;\n const item = target.closest<HTMLElement>(`[${ITEM_ATTR}]`);\n\n if (!item) return;\n\n if (handle && !target.closest(handle)) return;\n\n const originalParent = item.parentElement;\n\n if (!originalParent) return;\n\n const placeholder = createPlaceholder(item);\n const originalNextSibling = item.nextSibling;\n const activeId = getKey(item);\n\n // Snapshot only the source handle at drag start; targets are snapshotted lazily.\n const initialOrders = new Map<ContainerHandle, string[]>();\n\n initialOrders.set(handle_, handle_.getOrderedIds());\n item.setAttribute('data-dragging', '');\n originalParent.insertBefore(placeholder, originalNextSibling);\n\n const session: DragSession = {\n draggedEl: item,\n draggedId: activeId,\n hideFrame: null,\n initialOrders,\n originalDisplay: item.style.display,\n originalNextSibling,\n originalParent,\n placeholder,\n source: handle_,\n target: handle_,\n };\n\n if (!isTouchDragEvent(e) || e.__dndTouchPreview) scheduleHide(session);\n\n scopeState.active = session;\n\n if (e.dataTransfer) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', activeId);\n\n if (options.dragImage) {\n const preview =\n typeof options.dragImage === 'function' ? options.dragImage(activeId, item, e) : options.dragImage;\n const [offsetX, offsetY] = options.dragImageOffset ?? [0, 0];\n\n if (preview) e.dataTransfer.setDragImage(preview, offsetX, offsetY);\n }\n }\n\n handle_.notifyDragStart(session.draggedId, e);\n };\n\n const handleDragOver = (e: DragEvent): void => {\n const session = scopeState.active;\n\n if (!session) return;\n\n if (session.source.isDisabled() || handle_.isDisabled()) return;\n\n e.preventDefault();\n maybeAutoScroll(e, element, axis, autoScrollOptions);\n\n // Lazily snapshot this handle's order the first time it becomes a target.\n snapshotOrder(session, handle_);\n\n const { draggedEl, placeholder } = session;\n const target = (e.target as HTMLElement).closest<HTMLElement>(`[${ITEM_ATTR}]`);\n\n if (!target) {\n // Only append placeholder when it isn't already inside this container.\n // Moving it to the end on every over-empty-space event causes the\n // placeholder to oscillate between positions as the cursor moves.\n if (placeholder.parentElement !== element) {\n element.appendChild(placeholder);\n }\n\n session.target = handle_;\n\n return;\n }\n\n if (target === draggedEl || target === placeholder) return;\n\n const rect = target.getBoundingClientRect();\n const insertAfter =\n axis === 'vertical' ? e.clientY >= rect.top + rect.height / 2 : e.clientX >= rect.left + rect.width / 2;\n\n element.insertBefore(placeholder, insertAfter ? target.nextSibling : target);\n session.target = handle_;\n };\n\n const handleDrop = (e: DragEvent): void => {\n const session = scopeState.active;\n\n if (!session) return;\n\n if (session.source.isDisabled() || handle_.isDisabled()) return;\n\n e.preventDefault();\n // Record the drop target; the actual commit happens in handleDragEnd where\n // dataTransfer.dropEffect tells us whether the browser accepted the operation.\n session.target = handle_;\n };\n\n const handleDragEnd = (e: DragEvent): void => {\n if (scopeState.active?.source !== handle_) return;\n\n finishSession(scopeState, e, false);\n };\n\n const handleKeydown = (e: KeyboardEvent): void => {\n if (!keyboard || handle_.isDisabled()) return;\n\n const tagName = (e.target as HTMLElement | null)?.tagName;\n\n if (tagName === 'INPUT' || tagName === 'TEXTAREA' || tagName === 'SELECT') return;\n\n const item = (e.target as HTMLElement).closest<HTMLElement>(`[${ITEM_ATTR}]`);\n\n if (!item || !element.contains(item)) return;\n\n const prevOrder = getOrderedIds();\n const newOrder = applyKeyboardReorder(item, element, getItems, getOrderedIds, e.key, axis);\n\n // null means unrecognized key or boundary — let the browser handle it (e.g. page scroll)\n if (newOrder === null) return;\n\n e.preventDefault();\n handle_.notifyBeforeReorder(prevOrder, newOrder);\n handle_.commitReorder(newOrder);\n };\n\n markItems();\n\n const disposable = createDisposable(() => {\n scopeState.disposables.delete(disposable.dispose);\n\n if (scopeState.active && (scopeState.active.source === handle_ || scopeState.active.target === handle_)) {\n finishSession(scopeState, new Event('dragend') as DragEvent, true);\n }\n\n scopeState.handles.delete(handle_);\n restoreAttribute(element, 'role', originalContainerRole);\n cleanupItems();\n });\n\n if (originalContainerRole === null) element.setAttribute('role', 'list');\n\n element.addEventListener('dragstart', handleDragStart, { signal: disposable.disposalSignal });\n element.addEventListener('dragover', handleDragOver, { signal: disposable.disposalSignal });\n element.addEventListener('drop', handleDrop, { signal: disposable.disposalSignal });\n element.addEventListener('dragend', handleDragEnd, { signal: disposable.disposalSignal });\n element.addEventListener('keydown', handleKeydown, { signal: disposable.disposalSignal });\n\n // Register with scope so scope.dispose() can tear this down\n scopeState.disposables.add(disposable.dispose);\n\n return {\n get disposalSignal() {\n return disposable.disposalSignal;\n },\n dispose: disposable.dispose,\n get disposed() {\n return disposable.disposed;\n },\n get isDragging() {\n return scopeState.active?.source === handle_;\n },\n revert: () => {\n lastRevert?.();\n lastRevert = null;\n },\n [Symbol.dispose]: disposable[Symbol.dispose],\n sync: () => {\n markItems();\n },\n };\n}",
|
|
74
|
+
"applyReorder": "export function applyReorder<T>(items: T[], ids: string[], getKey: (item: T) => string): T[] {\n const byId = new Map(items.map((item) => [getKey(item), item] as const));\n const ordered: T[] = [];\n\n for (const id of ids) {\n if (!byId.has(id)) continue;\n\n const item = byId.get(id) as T;\n\n ordered.push(item);\n byId.delete(id);\n }\n\n for (const item of byId.values()) ordered.push(item);\n\n return ordered;\n}",
|
|
75
|
+
"Disposable": "export interface Disposable {\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n [Symbol.dispose](): void;\n}"
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiSource": "export * from './worker';\n",
|
|
3
|
+
"docs": {
|
|
4
|
+
"index": "---\ntitle: Familiar — Typed module-worker pools\ndescription: Typed ES module Worker pools with cancellation, priority scheduling, streaming, and test utilities.\npackage: familiar\ncategory: workers\nkeywords: [web-workers, module-workers, pool, concurrency, timeout, cancellation, streaming]\nrelated: [arsenal, ripple, herald]\nexports: [createWorker, createStreamWorker, batch, createTaskGroup, FamiliarError, FamiliarTimeoutError, FamiliarTaskError, FamiliarQueueFullError, FamiliarTerminatedError, FamiliarRuntimeError]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"familiar\" />\n\n## Why Familiar?\n\nRaw workers force every application to maintain its own message contract, lifecycle, cancellation, and pool scheduler. Familiar provides those boundaries while keeping worker code in normal typed ES modules.\n\n```ts\n// Before\nconst worker = new Worker(new URL('./sum.worker.ts', import.meta.url), { type: 'module' });\nworker.postMessage([1, 2, 3]);\n\n// After\nconst pool = createWorker<number[], number>(new URL('./sum.worker.ts', import.meta.url));\nawait pool.run([1, 2, 3]);\n```\n\n| Feature | Familiar | Raw Worker | Comlink |\n| --- | --- | --- | --- |\n| Bundle size | <PackageInfo package=\"familiar\" type=\"size\" /> | built-in | ~2 kB |\n| Module-worker contract | <ore-icon name=\"check\" size=\"16\"></ore-icon> | manual | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Pool scheduling | <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| AbortSignal cancellation | <ore-icon name=\"check\" size=\"16\"></ore-icon> | manual | manual |\n| Versioned protocol | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | implementation-specific |\n| Zero 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 Familiar when** worker jobs need bounded concurrency, typed errors, cancellation, or queue policy.\n\n**Consider raw Worker when** one isolated worker and custom messaging are enough.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/familiar\n```\n\n```sh [npm]\nnpm install @vielzeug/familiar\n```\n\n```sh [yarn]\nyarn add @vielzeug/familiar\n```\n\n:::\n\n## Quick Start\n\nRegister task logic inside a worker module.\n\n```ts\n// double.worker.ts\nimport { exposeTask } from '@vielzeug/familiar/protocol';\n\nexposeTask((value: number) => value * 2);\n```\n\nCreate pool from module URL and dispose it after use.\n\n```ts\nimport { createWorker } from '@vielzeug/familiar';\n\nconst worker = createWorker<number, number>(new URL('./double.worker.ts', import.meta.url));\n\ntry {\n console.log(await worker.run(21));\n} finally {\n worker.dispose();\n}\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createWorker()` — versioned task protocol over ES module workers\n- `createStreamWorker()` — stream-only worker capability\n- `run()` — priority scheduling, transferables, timeout, and cancellation\n- `batch()` — ordered task composition\n- `createTaskGroup()` — shared cancellation and settlement tracking\n- `stats` — active, queued, completed, and failed counters\n- `createTestWorker()` — faithful in-process task-pool testing\n- `dispose()` and `drain()` — immediate or draining teardown, with `using` support\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\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Arsenal](/arsenal/) — async helpers for application coordination.\n- [Ripple](/ripple/) — expose worker results through reactive state.\n- [Herald](/herald/) — publish application events after worker jobs settle.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: Familiar — API Reference\ndescription: API reference for module-worker pools and worker-side protocol registration.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `createWorker()` | Create single-result module-worker pool | Sync | Worker must call `exposeTask()` |\n| `createStreamWorker()` | Create stream-only module-worker pool | Sync | Worker must call `exposeStream()` |\n| `batch()` | Yield ordered task-pool results | Async iterator | Stops remaining work on first failure |\n| `createTaskGroup()` | Coordinate related task-pool jobs | Sync | Call `abort()` to stop group work |\n| `createTestWorker()` | Create an in-process task-pool test double | Sync | Task modules are not executed |\n| `exposeTask()` | Register worker task handler | Sync | Worker-only import |\n| `exposeStream()` | Register worker stream handler | Sync | Worker-only import |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/familiar` | Pool factories, helpers, types, errors |\n| `@vielzeug/familiar/protocol` | Versioned worker protocol and registration helpers |\n| `@vielzeug/familiar/testing` | Task-pool testing adapter |\n\n## Pool Factories\n\n### `createWorker()`\n\n```ts\nfunction createWorker<TInput, TOutput>(url: URL | string, options?: WorkerOptions): WorkerPool<TInput, TOutput>;\n```\n\nCreates a task pool for a worker module registered with `exposeTask()`.\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| `url` | `URL \\| string` | Module-worker URL, usually `new URL('./task.worker.ts', import.meta.url)` |\n| `options` | `WorkerOptions` | Pool concurrency, queue, timeout, and worker-error policy |\n\n**Returns:** `WorkerPool<TInput, TOutput>`.\n\n**Example:**\n\n```ts\nimport { createWorker } from '@vielzeug/familiar';\n\nconst pool = createWorker<number, number>(new URL('./double.worker.ts', import.meta.url));\n\ntry {\n console.log(await pool.run(21));\n} finally {\n pool.dispose();\n}\n```\n\n### `createStreamWorker()`\n\n```ts\nfunction createStreamWorker<TInput, TChunk>(url: URL | string, options?: WorkerOptions): StreamWorkerPool<TInput, TChunk>;\n```\n\nCreates a stream-only pool for a worker module registered with `exposeStream()`.\n\n**Returns:** `StreamWorkerPool<TInput, TChunk>`.\n\n---\n\n### `batch()`\n\n```ts\nfunction batch<TInput, TOutput>(\n pool: WorkerPool<TInput, TOutput>,\n inputs: readonly TInput[],\n options?: BatchOptions,\n): AsyncIterable<TOutput>;\n```\n\nYields results in submission order. A failure or cancellation aborts remaining batch work.\n\n**Returns:** `AsyncIterable<TOutput>`.\n\n---\n\n### `createTaskGroup()`\n\n```ts\nfunction createTaskGroup<TInput, TOutput>(\n pool: WorkerPool<TInput, TOutput>,\n name?: string,\n options?: TaskGroupOptions,\n): TaskGroup<TInput, TOutput>;\n```\n\nCreates group-scoped cancellation and settlement tracking for one task pool.\n\n**Returns:** `TaskGroup<TInput, TOutput>`.\n\n## Testing\n\n### `createTestWorker()`\n\n```ts\nfunction createTestWorker<TInput, TOutput>(\n handler: (input: TInput) => TOutput | Promise<TOutput>,\n options?: TestWorkerOptions,\n): TestWorkerHandle<TInput, TOutput>;\n```\n\nCreates an in-process task-pool double. It structured-clones values, records settlement, and matches task-pool timeout and cancellation behavior without loading a worker module.\n\n**Returns:** `TestWorkerHandle<TInput, TOutput>`.\n\n## Worker Protocol\n\n### `exposeTask()`\n\n```ts\nfunction exposeTask<TInput, TOutput>(handler: TaskHandler<TInput, TOutput>): void;\n```\n\nRegisters one single-result handler in a module worker.\n\n### `exposeStream()`\n\n```ts\nfunction exposeStream<TInput, TChunk>(handler: StreamHandler<TInput, TChunk>): void;\n```\n\nRegisters one chunk-producing handler in a module worker.\n\n### `PROTOCOL_VERSION`\n\n```ts\nconst PROTOCOL_VERSION: 1;\n```\n\nVersion included in every host request and worker response.\n\n## Types\n\n### `WorkerOptions`\n\n```ts\ntype WorkerOptions = {\n concurrency?: number | 'auto';\n maxQueue?: number;\n onFull?: 'reject' | 'wait';\n timeout?: number;\n onSlotError?: (error: FamiliarRuntimeError) => void;\n};\n```\n\n### `RunOptions`\n\n```ts\ntype RunOptions = {\n priority?: number;\n signal?: AbortSignal;\n timeout?: number;\n transferables?: Transferable[];\n};\n```\n\n`signal` cancels capacity waits, queued work, and executing work. Executing cancellation terminates and replaces its worker slot.\n\n### `WorkerPool`\n\n```ts\ninterface WorkerPool<TInput, TOutput> {\n [Symbol.asyncDispose](): Promise<void>;\n [Symbol.dispose](): void;\n run(input: TInput, options?: RunOptions): Promise<TOutput>;\n prime(): Promise<void>;\n drain(options?: DrainOptions): Promise<void>;\n dispose(): void;\n readonly stats: WorkerStats;\n readonly status: WorkerStatus;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n}\n```\n\n### `StreamWorkerPool`\n\n```ts\ninterface StreamWorkerPool<TInput, TChunk> {\n [Symbol.asyncDispose](): Promise<void>;\n [Symbol.dispose](): void;\n runStream(input: TInput, options?: RunOptions): AsyncIterable<TChunk>;\n prime(): Promise<void>;\n drain(options?: DrainOptions): Promise<void>;\n dispose(): void;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n readonly stats: WorkerStats;\n readonly status: WorkerStatus;\n}\n```\n\n### `WorkerStats`\n\n```ts\ntype WorkerStats = {\n readonly active: number;\n readonly completed: number;\n readonly failed: number;\n readonly queued: number;\n};\n```\n\n### `RunningStream`\n\n```ts\ntype RunningStream<TChunk> = {\n done: Promise<void>;\n iterable: AsyncIterable<TChunk>;\n};\n```\n\n### `WorkerStatus`\n\n```ts\ntype WorkerStatus = 'idle' | 'running' | 'terminated';\n```\n\n### `BatchOptions`\n\n```ts\ntype BatchOptions = RunOptions;\n```\n\n### `DrainOptions`\n\n```ts\ntype DrainOptions = {\n timeout?: number;\n};\n```\n\n### `TaskGroup`\n\n```ts\ntype TaskGroup<TInput, TOutput> = {\n abort(reason?: unknown): void;\n drain(): Promise<PromiseSettledResult<TOutput>[]>;\n readonly name: string | undefined;\n readonly pending: number;\n run(input: TInput, options?: Omit<RunOptions, 'signal'>): Promise<TOutput>;\n readonly size: number;\n};\n```\n\n### `TaskGroupOptions`\n\n```ts\ntype TaskGroupOptions = {\n signal?: AbortSignal;\n};\n```\n\n### `TestWorkerOptions`\n\n```ts\ntype TestWorkerOptions = Omit<WorkerOptions, 'concurrency' | 'onSlotError'> & {\n concurrency?: number;\n};\n```\n\n### `TestWorkerCall`\n\n```ts\ntype TestWorkerCall<TInput, TOutput> =\n | { input: TInput; status: 'fulfilled'; value: TOutput }\n | { input: TInput; reason: unknown; status: 'rejected' };\n```\n\n### `TestWorkerHandle`\n\n```ts\ntype TestWorkerHandle<TInput, TOutput> = WorkerPool<TInput, TOutput> & {\n readonly calls: ReadonlyArray<TestWorkerCall<TInput, TOutput>>;\n};\n```\n\n### `SerializedError`\n\n```ts\ntype SerializedError = {\n message: string;\n name: string;\n stack?: string;\n};\n```\n\n### `WorkerRequest`\n\n```ts\ntype WorkerRequest<TInput> =\n | { id: number; input: TInput; kind: 'run'; version: 1 }\n | { id: number; input: TInput; kind: 'stream'; version: 1 };\n```\n\n### `WorkerResponse`\n\n```ts\ntype WorkerResponse<TOutput> =\n | { id: number; kind: 'chunk'; value: TOutput; version: 1 }\n | { error: SerializedError; id: number; kind: 'error'; version: 1 }\n | { id: number; kind: 'result'; value: TOutput; version: 1 };\n```\n\n### `TaskHandler` and `StreamHandler`\n\n```ts\ntype TaskHandler<TInput, TOutput> = (input: TInput) => TOutput | Promise<TOutput>;\ntype StreamHandler<TInput, TChunk> = (input: TInput) => AsyncIterable<TChunk> | Promise<AsyncIterable<TChunk>>;\n```\n\n## Errors\n\n| Error | Trigger | Notable property |\n| --- | --- | --- |\n| `FamiliarError` | Base class for all Familiar errors | `FamiliarError.is(error)` |\n| `FamiliarInvalidOptionsError` | Invalid factory or test options | — |\n| `FamiliarQueueFullError` | Queue limit reached with `onFull: 'reject'` | `maxQueue` |\n| `FamiliarTaskError` | Worker handler throws or payload cannot clone | `cause` |\n| `FamiliarTimeoutError` | Task or drain deadline expires | `timeoutMs` |\n| `FamiliarTerminatedError` | Pool is disposed or draining | — |\n| `FamiliarRuntimeError` | Worker API or worker process fails | `cause` |\n",
|
|
6
|
+
"usage": "---\ntitle: Familiar — Usage Guide\ndescription: Run task and stream module workers with bounded concurrency, cancellation, and test parity.\n---\n\n[[toc]]\n\n## Basic Usage\n\nPut task logic in a worker module. Imports and helpers stay normal module code.\n\n```ts\n// normalize.worker.ts\nimport { exposeTask } from '@vielzeug/familiar/protocol';\n\nimport { normalize } from './normalize';\n\nexposeTask((text: string) => normalize(text));\n```\n\nCreate one long-lived pool at its owner boundary.\n\n```ts\nimport { createWorker } from '@vielzeug/familiar';\n\nconst pool = createWorker<string, string>(new URL('./normalize.worker.ts', import.meta.url), {\n concurrency: 2,\n timeout: 2_000,\n});\n\ntry {\n const normalized = await pool.run(' Familiar ');\n console.log(normalized);\n} finally {\n pool.dispose();\n}\n```\n\n## Cancellation and Timeouts\n\nPass one signal to stop capacity waits, queued work, or active work. Cancelling active work terminates and lazily replaces its slot.\n\n```ts\nconst controller = new AbortController();\nconst result = pool.run('input', { signal: controller.signal, timeout: 500 });\n\ncontroller.abort();\nawait result.catch((error) => console.log(error.name)); // AbortError\n```\n\n## Queue Policy and Priority\n\nUse `maxQueue` to bound waiting work. Higher priorities dispatch first once a slot opens.\n\n```ts\nconst pool = createWorker<Job, Result>(new URL('./job.worker.ts', import.meta.url), {\n concurrency: 2,\n maxQueue: 100,\n onFull: 'wait',\n});\n\nawait pool.run(criticalJob, { priority: 10 });\n```\n\n## Batch and Groups\n\nCompose task pools with free helpers instead of carrying unrelated methods on every pool.\n\n```ts\nimport { batch, createTaskGroup } from '@vielzeug/familiar';\n\nfor await (const value of batch(pool, inputs)) {\n console.log(value);\n}\n\nconst group = createTaskGroup(pool, 'import');\nconst tasks = rows.map((row) => group.run(row));\nawait group.drain();\nawait Promise.all(tasks);\n```\n\n## Streaming\n\nStream workers have their own capability and registration helper.\n\n```ts\n// tokenize.worker.ts\nimport { exposeStream } from '@vielzeug/familiar/protocol';\n\nexposeStream(async function* (text: string) {\n for (const token of text.split(/\\s+/)) yield token;\n});\n```\n\n```ts\nimport { createStreamWorker } from '@vielzeug/familiar';\n\nconst pool = createStreamWorker<string, string>(new URL('./tokenize.worker.ts', import.meta.url));\nfor await (const token of pool.runStream('typed module workers')) {\n console.log(token);\n}\npool.dispose();\n```\n\n## Testing\n\nUse `createTestWorker()` when testing consumer code that depends on a task pool. It clones input/output, wraps task failures, and honors cancellation and timeout behavior.\n\n```ts\nimport { createTestWorker } from '@vielzeug/familiar/testing';\n\nconst pool = createTestWorker((value: number) => value * 2);\nawait expect(pool.run(21)).resolves.toBe(42);\nexpect(pool.calls).toEqual([{ input: 21, status: 'fulfilled', value: 42 }]);\npool.dispose();\n```\n\nTest worker-module business logic directly when possible. `createTestWorker()` does not run module files or support stream pools.\n\n## Framework Integration\n\nCreate a pool once per component lifetime. Abort obsolete requests during effect cleanup and dispose the pool on unmount.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useMemo } from 'react';\nimport { createWorker } from '@vielzeug/familiar';\n\nconst pool = useMemo(() => createWorker(new URL('./sort.worker.ts', import.meta.url)), []);\n\nuseEffect(() => () => pool.dispose(), [pool]);\n```\n\n```ts [Vue]\nimport { onUnmounted } from 'vue';\nimport { createWorker } from '@vielzeug/familiar';\n\nconst pool = createWorker(new URL('./sort.worker.ts', import.meta.url));\n\nonUnmounted(() => pool.dispose());\n```\n\n```ts [Svelte]\nimport { onDestroy } from 'svelte';\nimport { createWorker } from '@vielzeug/familiar';\n\nconst pool = createWorker(new URL('./sort.worker.ts', import.meta.url));\n\nonDestroy(() => pool.dispose());\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nUse `@vielzeug/arsenal` async helpers in application orchestration. Keep worker module protocol registration in `@vielzeug/familiar/protocol`.\n\n## Best Practices\n\n- Put every task handler in its own module-worker boundary.\n- Reuse pools for repeated work; dispose owner-scoped pools.\n- Abort work made obsolete by navigation or newer input.\n- Transfer large binary buffers instead of cloning them.\n- Set explicit timeouts for work with a bounded latency budget.\n- Keep worker handlers deterministic and data-only.\n- Test module logic directly; test pool consumers with `createTestWorker()`.\n",
|
|
7
|
+
"examples": "---\ntitle: Familiar — Examples\ndescription: Module-worker recipes for familiar.\n---\n\n## Examples\n\n- [Fibonacci With Pool And Timeout](./examples/fibonacci-with-pool-and-timeout.md)\n- [Data Transformation Pipeline](./examples/data-transformation-pipeline.md)\n- [Image Processing](./examples/image-processing.md)\n- [Using Transferables](./examples/using-transferables.md)\n- [Cancellable Batch](./examples/cancellable-batch.md)\n- [Priority Queue](./examples/priority-queue.md)\n- [Streaming With Stream Worker](./examples/streaming-with-runstream.md)\n- [Module Worker](./examples/module-worker.md)\n- [Typed Error Handling](./examples/typed-error-handling.md)\n- [React Integration](./examples/react-integration.md)\n- [Testing With createTestWorker](./examples/testing-with-createtestworker.md)\n"
|
|
8
|
+
},
|
|
9
|
+
"examples": [
|
|
10
|
+
{
|
|
11
|
+
"id": "error-contracts",
|
|
12
|
+
"code": "import { FamiliarTimeoutError } from '@vielzeug/familiar'\n\nconst error = new FamiliarTimeoutError(500)\nconsole.log(error.name)\nconsole.log(error.timeoutMs)",
|
|
13
|
+
"name": "Familiar Error Contracts"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"typeSignatures": {
|
|
17
|
+
"batch": "export { batch, createTaskGroup } from './_pool';",
|
|
18
|
+
"createTaskGroup": "export { batch, createTaskGroup } from './_pool';",
|
|
19
|
+
"FamiliarError": "export {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';",
|
|
20
|
+
"FamiliarInvalidOptionsError": "export {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';",
|
|
21
|
+
"FamiliarQueueFullError": "export {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';",
|
|
22
|
+
"FamiliarRuntimeError": "export {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';",
|
|
23
|
+
"FamiliarTaskError": "export {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';",
|
|
24
|
+
"FamiliarTerminatedError": "export {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';",
|
|
25
|
+
"FamiliarTimeoutError": "export {\n FamiliarError,\n FamiliarInvalidOptionsError,\n FamiliarQueueFullError,\n FamiliarRuntimeError,\n FamiliarTaskError,\n FamiliarTerminatedError,\n FamiliarTimeoutError,\n} from './errors';",
|
|
26
|
+
"BatchOptions": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
27
|
+
"DrainOptions": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
28
|
+
"RunOptions": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
29
|
+
"StreamWorkerPool": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
30
|
+
"TaskGroup": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
31
|
+
"TaskGroupOptions": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
32
|
+
"WorkerOptions": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
33
|
+
"WorkerPool": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
34
|
+
"WorkerStats": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
35
|
+
"WorkerStatus": "export type {\n BatchOptions,\n DrainOptions,\n RunOptions,\n StreamWorkerPool,\n TaskGroup,\n TaskGroupOptions,\n WorkerOptions,\n WorkerPool,\n WorkerStats,\n WorkerStatus,\n} from './types';",
|
|
36
|
+
"RunningStream": "export type RunningStream<TChunk> = {\n done: Promise<void>;\n iterable: AsyncIterable<TChunk>;\n};",
|
|
37
|
+
"createWorker": "export function createWorker<TInput, TOutput>(\n url: URL | string,\n options: WorkerOptions = {},\n): WorkerPool<TInput, TOutput> {\n const resolved = resolveOptions(options);\n\n return createPool(slots<TInput, TOutput>(url, resolved), {\n concurrency: resolved.concurrency,\n defaultTimeout: resolved.timeout,\n maxQueue: resolved.maxQueue,\n onFull: resolved.onFull,\n });\n}",
|
|
38
|
+
"createStreamWorker": "export function createStreamWorker<TInput, TChunk>(\n url: URL | string,\n options: WorkerOptions = {},\n): StreamWorkerPool<TInput, TChunk> {\n const resolved = resolveOptions(options);\n\n return createStreamPool(slots<TInput, TChunk>(url, resolved), {\n concurrency: resolved.concurrency,\n defaultTimeout: resolved.timeout,\n maxQueue: resolved.maxQueue,\n onFull: resolved.onFull,\n });\n}"
|
|
39
|
+
}
|
|
40
|
+
}
|