@vielzeug/codex 26.11.24 → 26.11.26

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.
Files changed (97) hide show
  1. package/README.md +5 -4
  2. package/data/snapshot.json +1 -0
  3. package/dist/catalog.d.ts +35 -39
  4. package/dist/catalog.js +112 -139
  5. package/dist/catalog.js.map +1 -1
  6. package/dist/cli.js +25 -16
  7. package/dist/cli.js.map +1 -1
  8. package/dist/http.js +1 -1
  9. package/dist/http.js.map +1 -1
  10. package/dist/index.d.ts +5 -7
  11. package/dist/index.js +4 -6
  12. package/dist/index.js.map +1 -1
  13. package/dist/server.d.ts +9 -7
  14. package/dist/server.js +14 -6
  15. package/dist/server.js.map +1 -1
  16. package/dist/snapshot.d.ts +8 -22
  17. package/dist/snapshot.js +41 -176
  18. package/dist/snapshot.js.map +1 -1
  19. package/dist/tools/index.d.ts +1 -1
  20. package/dist/tools/index.js.map +1 -1
  21. package/dist/tools/packages.js +49 -82
  22. package/dist/tools/packages.js.map +1 -1
  23. package/dist/tools/refine.d.ts +1 -2
  24. package/dist/tools/refine.js +90 -82
  25. package/dist/tools/refine.js.map +1 -1
  26. package/dist/tools/schema.d.ts +2 -1
  27. package/dist/tools/schema.js +9 -5
  28. package/dist/tools/schema.js.map +1 -1
  29. package/dist/tools/shared.d.ts +2 -2
  30. package/dist/types.d.ts +77 -64
  31. package/dist/types.js +6 -2
  32. package/dist/types.js.map +1 -1
  33. package/package.json +2 -2
  34. package/skills/vielzeug/SKILL.md +18 -20
  35. package/data/catalog.json +0 -2539
  36. package/data/llms-full.txt +0 -40978
  37. package/data/llms.txt +0 -60
  38. package/data/manifest.json +0 -4
  39. package/data/packages/archive.json +0 -87
  40. package/data/packages/arsenal.json +0 -270
  41. package/data/packages/assay.json +0 -52
  42. package/data/packages/atlas.json +0 -81
  43. package/data/packages/bard.json +0 -38
  44. package/data/packages/beacon.json +0 -51
  45. package/data/packages/clockwork.json +0 -69
  46. package/data/packages/codex.json +0 -37
  47. package/data/packages/coins.json +0 -99
  48. package/data/packages/conduit.json +0 -67
  49. package/data/packages/courier.json +0 -66
  50. package/data/packages/dnd.json +0 -60
  51. package/data/packages/familiar.json +0 -38
  52. package/data/packages/flux.json +0 -97
  53. package/data/packages/focus.json +0 -51
  54. package/data/packages/forge.json +0 -65
  55. package/data/packages/gesture.json +0 -65
  56. package/data/packages/herald.json +0 -80
  57. package/data/packages/illusionist.json +0 -132
  58. package/data/packages/ink.json +0 -41
  59. package/data/packages/keymap.json +0 -55
  60. package/data/packages/ledger.json +0 -60
  61. package/data/packages/lingua.json +0 -68
  62. package/data/packages/mesh.json +0 -52
  63. package/data/packages/necromancer.json +0 -55
  64. package/data/packages/orbit.json +0 -100
  65. package/data/packages/ore.json +0 -78
  66. package/data/packages/palette.json +0 -42
  67. package/data/packages/patchwork.json +0 -55
  68. package/data/packages/postmaster.json +0 -49
  69. package/data/packages/prism.json +0 -99
  70. package/data/packages/pulse.json +0 -71
  71. package/data/packages/refine.json +0 -36
  72. package/data/packages/ripple.json +0 -84
  73. package/data/packages/rune.json +0 -78
  74. package/data/packages/sandbox.json +0 -26
  75. package/data/packages/scout.json +0 -66
  76. package/data/packages/scribe.json +0 -57
  77. package/data/packages/scroll.json +0 -110
  78. package/data/packages/sentinel.json +0 -46
  79. package/data/packages/sigil.json +0 -52
  80. package/data/packages/sourcerer.json +0 -86
  81. package/data/packages/spell.json +0 -126
  82. package/data/packages/stage.json +0 -26
  83. package/data/packages/tabula.json +0 -39
  84. package/data/packages/tandem.json +0 -31
  85. package/data/packages/tavern.json +0 -34
  86. package/data/packages/tempo.json +0 -68
  87. package/data/packages/vault.json +0 -81
  88. package/data/packages/ward.json +0 -77
  89. package/data/packages/wayfinder.json +0 -126
  90. package/data/packages/wire.json +0 -51
  91. package/data/refine.json +0 -17277
  92. package/dist/consumer.d.ts +0 -17
  93. package/dist/consumer.js +0 -114
  94. package/dist/consumer.js.map +0 -1
  95. package/dist/port.d.ts +0 -2
  96. package/dist/port.js +0 -12
  97. package/dist/port.js.map +0 -1
@@ -1,100 +0,0 @@
1
- {
2
- "apiSource": "// Auto-update\nexport type { AutoUpdateOptions } from './auto-update';\nexport { autoUpdate } from './auto-update';\n// Core engine\nexport { computePosition } from './core';\n// Errors\nexport { OrbitConfigError, OrbitError } from './errors';\n// High-level API\nexport type { Positioner, PositionerOptions, PositionStrategy } from './float';\nexport { createPositioner } from './float';\n// Inline middleware\nexport type { InlineOptions } from './inline';\nexport { inline } from './inline';\n// Middleware\nexport type { ArrowOptions } from './middleware/arrow';\nexport { arrow } from './middleware/arrow';\nexport type { AutoPlacementOptions } from './middleware/auto-placement';\nexport { autoPlacement } from './middleware/auto-placement';\nexport type { FlipOptions } from './middleware/flip';\nexport { flip } from './middleware/flip';\nexport type { HideOptions } from './middleware/hide';\nexport { hide } from './middleware/hide';\nexport type { OffsetConfig, OffsetValue } from './middleware/offset';\nexport { offset } from './middleware/offset';\nexport type { LimitShiftOptions, ShiftLimiter, ShiftOptions } from './middleware/shift';\nexport { limitShift, shift } from './middleware/shift';\nexport type { SizeOptions } from './middleware/size';\nexport { size } from './middleware/size';\n// Overflow helpers\nexport { detectOverflow, getBoundaryRect, getClippingAncestorRect } from './overflow';\n// Preset types (functions live on the @vielzeug/orbit/presets sub-path)\nexport type { PositioningPreset, PresetOptions } from './presets';\n// Types\nexport type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';\n// Public utilities\nexport { getAlignment, getSide } from './utils';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Orbit: Floating UI positioning'\ndescription: Floating positioning with lifecycle-owned geometry and middleware.\npackage: orbit\ncategory: ui\nkeywords: [positioning, tooltip, popover, dropdown, middleware, floating-ui]\nexports: [autoUpdate, computePosition, createPositioner]\nrelated: [ore, refine, prism]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"orbit\" />\n\n## Why Orbit?\n\nFloating UI needs one owner for CSS coordinates, clipping boundaries, updates, and cleanup. Orbit provides a lifecycle positioner for normal UI and a pure computation API for advanced integrations.\n\n```ts\n// Before\nconst { x, y } = computeSomehow(trigger, panel);\npanel.style.left = `${x}px`;\npanel.style.top = `${y}px`;\n\n// After\nconst positioner = createPositioner(trigger, panel);\n```\n\n| Feature | Manual DOM positioning | Orbit |\n| ------------------- | ---------------------- | ------------------------------------------- |\n| Bundle size | 0 B | <PackageInfo package=\"orbit\" type=\"size\" /> |\n| Root dependencies | Application-defined | `@vielzeug/arsenal` |\n| Clipping boundary | Manual geometry | `clippingAncestors` default |\n| Coordinate strategy | Consumer logic | `fixed` / `absolute` |\n| Cleanup | Manual listeners | `dispose()` |\n\n<div class=\"decision-callout\">\n\n**Use Orbit when** floating UI needs robust placement, collision handling, or reactive updates.\n\n**Consider direct CSS when** placement is static and never depends on element geometry.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/orbit\n```\n\n```sh [npm]\nnpm install @vielzeug/orbit\n```\n\n```sh [yarn]\nyarn add @vielzeug/orbit\n```\n\n:::\n\n## Quick Start\n\nCreate a positioner only after its reference and floating elements mount; positioning starts immediately.\n\n```ts\nimport { createPositioner, flip, offset, shift } from '@vielzeug/orbit';\n\nconst positioner = createPositioner(trigger, tooltip, {\n middleware: [offset(8), flip(), shift({ padding: 6 })],\n placement: 'top',\n});\n\npositioner.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createPositioner()`: Lifecycle-owned floating positioning\n- `computePosition()`: Low-level calculation for advanced integrations\n- `autoUpdate()`: Scroll, viewport, resize, and animation-frame updates\n- Middleware: Offset, flip, shift, size, hide, arrow, inline, auto-placement\n- `strategy`: Explicit `fixed` or `absolute` coordinate behavior\n- `/reactive`: Optional Ripple position readable\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Refine](/refine/): Accessible components using floating UI behavior.\n- [Ore](/ore/): Lifecycle ownership for custom-element positioning.\n- [Prism](/prism/): Chart tooltips positioned from virtual references.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Orbit: API Reference'\ndescription: API reference for @vielzeug/orbit positioners, computation, updates, middleware, and optional reactive integration.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ---------------------------- | ------------------------------------ | -------------- | -------------------------------------- |\n| `createPositioner()` | Lifecycle-owned floating positioning | Sync | Starts immediately; create after mount |\n| `computePosition()` | Low-level geometry computation | Sync | Caller owns CSS application |\n| `autoUpdate()` | Listen for geometry changes | Sync | Call returned cleanup |\n| `createReactivePositioner()` | Optional Ripple position readable | Sync | Requires `@vielzeug/ripple` |\n| Middleware factories | Adjust placement and size | Sync | Order is explicit |\n\n## Package Entry Points\n\n| Import | Purpose |\n| -------------------------- | -------------------------------------------------------- |\n| `@vielzeug/orbit` | Positioner, computation, updates, middleware, and types. |\n| `@vielzeug/orbit/reactive` | Optional Ripple position adapter. |\n| `@vielzeug/orbit/presets` | Preset placement and middleware options. |\n| `@vielzeug/orbit/devtools` | Development overlay. |\n\n## Core Functions\n\n### `createPositioner()`\n\n```ts\nfunction createPositioner(reference: ReferenceElement, floating: HTMLElement, options?: PositionerOptions): Positioner;\n```\n\nCreates an active positioner and applies its initial position before returning.\n\n| Parameter | Type | Description |\n| ----------- | ------------------- | ------------------------------------------------------------------ |\n| `reference` | `ReferenceElement` | DOM or virtual anchor. |\n| `floating` | `HTMLElement` | Positioned element. |\n| `options` | `PositionerOptions` | Strategy, clipping, middleware, updates, and application callback. |\n\n**Returns:** `Positioner`.\n\n```ts\nimport { createPositioner } from '@vielzeug/orbit';\n\nconst positioner = createPositioner(trigger, tooltip);\npositioner.dispose();\n```\n\n| Member | Return | Contract |\n| --------------- | ----------------------- | ----------------------------------------- |\n| `update()` | `void` | Recomputes and applies position. |\n| `getPosition()` | `ComputePositionResult` | Latest applied result. |\n| `dispose()` | `void` | Stops updates and aborts disposal signal. |\n\n### `computePosition()`\n\n```ts\nfunction computePosition(\n reference: ReferenceElement,\n floating: HTMLElement,\n options?: ComputePositionOptions,\n): ComputePositionResult;\n```\n\nCalculates position without applying DOM styles or creating listeners.\n\n**Returns:** `ComputePositionResult`.\n\n### `autoUpdate()`\n\n```ts\nfunction autoUpdate(\n reference: ReferenceElement,\n floating: HTMLElement,\n update: () => void,\n options?: AutoUpdateOptions,\n): () => void;\n```\n\nCalls `update` immediately, then on relevant scroll, viewport, resize, and optional animation-frame changes.\n\n**Returns:** cleanup callback.\n\n## Middleware\n\n```ts\ntype Middleware = (state: MiddlewareState) => MiddlewareResult | undefined;\n```\n\nBuilt-in factories: `arrow`, `autoPlacement`, `flip`, `hide`, `inline`, `offset`, `shift`, `limitShift`, and `size`.\n\n```ts\nconst middleware = [offset(8), flip(), shift({ padding: 6 }), size()];\n```\n\n`middlewareData` is `MiddlewareData`; narrow custom data at the consuming boundary.\n\n## Reactive Adapter\n\n```ts\nfunction createReactivePositioner(\n reference: ReferenceElement,\n floating: HTMLElement,\n options?: Omit<PositionerOptions, 'apply'>,\n): ReactivePositioner;\n```\n\n`ReactivePositioner.position` is `Readable<ComputePositionResult>`. Imported from `@vielzeug/orbit/reactive`.\n\n## Types\n\n```ts\ntype Side = 'top' | 'bottom' | 'left' | 'right';\ntype Alignment = 'start' | 'end';\ntype Placement = Side | `${Side}-${Alignment}`;\n\ninterface Rect {\n height: number;\n width: number;\n x: number;\n y: number;\n}\n\ninterface VirtualReference {\n getBoundingClientRect: () => DOMRect | Rect;\n getClientRects?: () => DOMRectList | DOMRect[];\n}\n\ntype ReferenceElement = Element | VirtualReference;\n\ninterface SideObject {\n bottom: number;\n left: number;\n right: number;\n top: number;\n}\n\ntype Padding = number | Partial<SideObject>;\n\ninterface ArrowData {\n centerOffset: number;\n constrained: boolean;\n x?: number;\n y?: number;\n}\n\ninterface FlipData {\n skippedPlacements: Placement[];\n}\n\ninterface ShiftData {\n x: number;\n y: number;\n}\n\ninterface HideData {\n escaped?: boolean;\n escapedOffsets?: SideObject;\n referenceHidden?: boolean;\n referenceHiddenOffsets?: SideObject;\n}\n\ninterface SizeData {\n availableHeight: number;\n availableWidth: number;\n}\n\ninterface MiddlewareData {\n arrow?: ArrowData;\n flip?: FlipData;\n hide?: HideData;\n shift?: ShiftData;\n size?: SizeData;\n [key: string]: unknown;\n}\n\ninterface MiddlewareState {\n boundary?: Element | Rect;\n elements: { floating: HTMLElement; reference: ReferenceElement };\n initialPlacement: Placement;\n middlewareData: MiddlewareData;\n padding?: Padding;\n placement: Placement;\n rects: { floating: Rect; reference: Rect };\n x: number;\n y: number;\n}\n\ntype MiddlewareReset = {\n placement?: Placement;\n rects?: MiddlewareState['rects'];\n remeasure?: boolean;\n};\n\ninterface MiddlewareResult {\n data?: MiddlewareData;\n placement?: Placement;\n reset?: MiddlewareReset;\n x?: number;\n y?: number;\n}\n\ntype Middleware = (state: MiddlewareState) => MiddlewareResult | undefined;\n\ninterface ComputePositionResult {\n middlewareData: MiddlewareData;\n placement: Placement;\n x: number;\n y: number;\n}\n\ninterface ComputePositionOptions {\n boundary?: Element | Rect;\n containingBlock?: Element | null;\n middleware?: readonly Middleware[];\n padding?: Padding;\n placement?: Placement;\n}\n\ninterface DetectOverflowOptions {\n boundary?: Element | Rect;\n padding?: Padding;\n}\n\ntype PositionStrategy = 'absolute' | 'fixed';\n\ninterface PositionerOptions extends Omit<ComputePositionOptions, 'boundary' | 'containingBlock'> {\n apply?: (result: ComputePositionResult) => void;\n autoUpdate?: AutoUpdateOptions | false;\n boundary?: ComputePositionOptions['boundary'] | 'clippingAncestors';\n strategy?: PositionStrategy;\n}\n\ninterface Positioner {\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n getPosition(): ComputePositionResult;\n update(): void;\n [Symbol.dispose](): void;\n}\n\ninterface AutoUpdateOptions {\n animationFrame?: boolean;\n observeAncestors?: boolean;\n observeFloating?: boolean;\n observeVisualViewport?: boolean;\n pauseWhenHidden?: boolean;\n throttle?: number;\n}\n\ninterface ReactivePositioner extends Positioner {\n readonly position: Readable<ComputePositionResult>;\n}\n\ninterface ArrowOptions {\n element: HTMLElement;\n padding?: Padding;\n}\n\ninterface AutoPlacementOptions extends DetectOverflowOptions {\n alignment?: Alignment | null;\n allowedPlacements?: Placement[];\n}\n\ninterface FlipOptions extends DetectOverflowOptions {\n fallbackPlacements?: Placement[];\n}\n\ninterface HideOptions extends DetectOverflowOptions {\n strategy?: 'referenceHidden' | 'escaped' | 'both';\n}\n\ntype OffsetConfig = {\n crossAxis?: number;\n mainAxis?: number;\n};\n\ntype OffsetValue = number | OffsetConfig | ((state: MiddlewareState) => number | OffsetConfig);\n\ntype ShiftLimiter = (\n state: MiddlewareState,\n correction: { crossAxis: number; mainAxis: number },\n) => { crossAxis: number; mainAxis: number };\n\ninterface LimitShiftOptions {\n offset?: number | ((state: MiddlewareState) => number);\n}\n\ninterface ShiftOptions extends DetectOverflowOptions {\n crossAxis?: boolean;\n limiter?: ShiftLimiter;\n}\n\ninterface InlineOptions {\n padding?: Padding;\n x?: number;\n y?: number;\n}\n\ntype SizeOptions = DetectOverflowOptions;\n\ninterface PositioningPreset {\n middleware: Middleware[];\n placement: Placement;\n}\n\ninterface PresetOptions {\n offset?: number;\n padding?: number;\n placement?: Placement;\n}\n```\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| ------------------ | -------------------------------------- | -------------------------------------------- |\n| `OrbitConfigError` | Invalid middleware reset configuration | Extends `OrbitError` |\n| `OrbitError` | Base Orbit error | `instanceof OrbitError` narrows Orbit errors |\n",
6
- "usage": "---\ntitle: 'Orbit: Usage Guide'\ndescription: Position floating UI with lifecycle ownership, explicit coordinate strategy, middleware, and optional reactive state.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate a positioner after both elements mount, then dispose it with their owner.\n\n```ts\nimport { createPositioner, flip, offset, shift } from '@vielzeug/orbit';\n\nconst positioner = createPositioner(trigger, tooltip, {\n middleware: [offset(8), flip(), shift({ padding: 6 })],\n placement: 'top',\n});\n\npositioner.dispose();\n```\n\n`createPositioner()` applies the initial position before returning and owns clipping-boundary resolution, updates, CSS strategy, and cleanup.\n\n## Coordinate Strategy\n\nUse `fixed` for viewport-positioned overlays. Use `absolute` when the floating element should position within its offset parent.\n\n```ts\nconst positioner = createPositioner(trigger, dropdown, {\n placement: 'bottom-start',\n strategy: 'absolute',\n});\n```\n\nOrbit resolves clipping ancestors by default. Pass an explicit `boundary` when your application owns a different visible region.\n\n## Middleware\n\nPass middleware in the exact order it should execute.\n\n```ts\nconst positioner = createPositioner(trigger, panel, {\n middleware: [offset(8), flip(), shift({ padding: 8 }), size(), arrow({ element: arrowElement })],\n});\n```\n\nUse either `flip()` or `autoPlacement()` for one positioner. Custom middleware writes data into `result.middlewareData`.\n\n## Virtual References\n\nUse a virtual reference for cursor-anchored UI.\n\n```ts\nconst reference = {\n getBoundingClientRect: () => ({ height: 0, width: 0, x: event.clientX, y: event.clientY }),\n};\n\nconst positioner = createPositioner(reference, menu, { placement: 'bottom-start' });\n```\n\n## Manual Positioning\n\nUse `computePosition()` only when your application owns CSS application and lifecycle itself.\n\n```ts\nimport { computePosition, offset } from '@vielzeug/orbit';\n\nconst result = computePosition(reference, floating, { middleware: [offset(8)] });\nfloating.style.left = `${result.x}px`;\nfloating.style.top = `${result.y}px`;\n```\n\n## Reactive Adapter\n\nInstall Ripple and import the optional adapter only when your UI needs a reactive position value.\n\n```ts\nimport { createReactivePositioner } from '@vielzeug/orbit/reactive';\nimport { effect } from '@vielzeug/ripple';\n\nconst positioner = createReactivePositioner(trigger, tooltip);\n\neffect(() => {\n const position = positioner.position.value;\n\n tooltip.style.left = `${position.x}px`;\n tooltip.style.top = `${position.y}px`;\n});\n```\n\n## Client Lifecycle\n\nOrbit root imports are server-safe. Invoke geometry APIs only from a client mount lifecycle, where DOM elements exist.\n\n```ts\nonMounted(() => {\n const positioner = createPositioner(trigger, panel);\n onCleanup(() => positioner.dispose());\n});\n```\n\n## Framework Integration\n\nCreate and dispose positioners with component lifecycle.\n\n::: code-group\n\n```tsx [React]\nuseEffect(() => {\n const positioner = createPositioner(trigger, panel);\n\n return () => positioner.dispose();\n}, [trigger, panel]);\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nonMounted(() => {\n const positioner = createPositioner(trigger.value!, panel.value!);\n onUnmounted(() => positioner.dispose());\n});\n</script>\n```\n\n```ts [Svelte]\nonMount(() => {\n const positioner = createPositioner(trigger, panel);\n\n return () => positioner.dispose();\n});\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### Orbit + Prism\n\nUse `strategy: 'absolute'` for a tooltip rendered inside a chart container.\n\n```ts\nconst positioner = createPositioner(cursorReference, tooltip, {\n autoUpdate: false,\n strategy: 'absolute',\n});\n\npositioner.dispose();\n```\n\n## Best Practices\n\n- **Create** a positioner after both DOM elements mount; it starts immediately.\n- **Dispose** it with its UI owner.\n- **Choose** `fixed` or `absolute` intentionally.\n- **Keep** middleware order explicit.\n- **Use** `computePosition()` only for advanced platform-managed paths.\n- **Install** Ripple only when importing `/reactive`.\n- **Invoke** geometry APIs only on the client.\n",
7
- "examples": "---\ntitle: 'Orbit: Examples'\ndescription: Worked examples for @vielzeug/orbit.\n---\n\n## Examples\n\n- [Context Menu](./examples/context-menu.md)\n- [Custom Middleware](./examples/custom-middleware.md)\n- [Dropdown Select](./examples/dropdown-select.md)\n- [Popover with Arrow](./examples/popover-with-arrow.md)\n- [Reactive Adapter](./examples/reactive-adapter.md)\n- [Tooltip](./examples/tooltip.md)\n- [Using Presets](./examples/using-presets.md)\n- [With Ore Component](./examples/with-ore-component.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "auto-update",
12
- "code": "import { autoUpdate, computePosition, flip, offset, shift } from '@vielzeug/orbit'\n\nconst button = document.createElement('button')\nbutton.textContent = 'Reference'\nbutton.style.cssText = 'position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); padding: 8px 16px;'\ndocument.body.appendChild(button)\n\nconst dropdown = document.createElement('div')\ndropdown.textContent = 'Dropdown'\n// position: fixed with left: 0; top: 0 so left/top writes are absolute viewport coords\ndropdown.style.cssText = 'position: fixed; left: 0; top: 0; background: #fff; border: 1px solid #e5e5e5; border-radius: 6px; padding: 12px 16px; box-shadow: 0 4px 12px rgba(0,0,0,.1); z-index: 1000;'\ndocument.body.appendChild(dropdown)\n\nconst middleware = [offset(4), flip(), shift({ padding: 8 })]\n\nfunction update() {\n const { x, y, placement } = computePosition(button, dropdown, {\n placement: 'bottom-start',\n middleware,\n })\n dropdown.style.left = x + 'px'\n dropdown.style.top = y + 'px'\n dropdown.dataset.placement = placement\n console.log('Positioned:', placement)\n}\n\n// autoUpdate calls update immediately then re-calls on scroll/resize/mutation\nconst cleanup = autoUpdate(button, dropdown, update)\n\nconsole.log('autoUpdate running: try resizing the window')\nconsole.log('cleanup type (call to stop):', typeof cleanup)",
13
- "name": "autoUpdate - Track on Scroll/Resize"
14
- },
15
- {
16
- "id": "inline-middleware",
17
- "code": "import { computePosition, flip, inline, shift } from '@vielzeug/orbit'\n\n// inline() corrects the reference rect for multi-line inline elements.\n// It picks the client rect closest to the cursor (or floating element).\nconst span = document.createElement('span')\nspan.textContent = 'Hover to reveal tooltip: this is a long inline element that may wrap'\nspan.style.cssText = 'line-height: 1.8; cursor: pointer; background: #f0f0f0; padding: 2px 4px; border-radius: 3px;'\ndocument.body.appendChild(span)\n\nconst tooltip = document.createElement('div')\ntooltip.textContent = 'inline() picks the nearest client rect'\ntooltip.style.cssText = 'position: fixed; left: 0; top: 0; background: #1a1a2e; color: #e0e0ff; padding: 6px 10px; border-radius: 5px; font-size: 12px; pointer-events: none; z-index: 1000;'\ntooltip.hidden = true\ndocument.body.appendChild(tooltip)\n\nlet cursorX = 0\nlet cursorY = 0\n\nspan.addEventListener('mousemove', (e) => {\n cursorX = e.clientX\n cursorY = e.clientY\n tooltip.hidden = false\n\n const { x, y } = computePosition(span, tooltip, {\n placement: 'top',\n middleware: [inline({ x: cursorX, y: cursorY }), flip(), shift({ padding: 4 })],\n })\n tooltip.style.left = x + 'px'\n tooltip.style.top = y + 'px'\n})\n\nspan.addEventListener('mouseleave', () => { tooltip.hidden = true })\n\nconsole.log('Hover over the span to see inline() in action')",
18
- "name": "inline - Multi-line Inline Reference"
19
- },
20
- {
21
- "id": "position-basic",
22
- "code": "import { computePosition } from '@vielzeug/orbit'\n\n// Create reference and floating elements\nconst button = document.createElement('button')\nbutton.textContent = 'Anchor'\nbutton.style.cssText = 'padding: 8px 16px; margin: 50px;'\ndocument.body.appendChild(button)\n\nconst tooltip = document.createElement('div')\ntooltip.textContent = 'Tooltip'\ntooltip.style.cssText = 'position: fixed; background: #333; color: #fff; padding: 8px 12px; border-radius: 4px; font-size: 12px; z-index: 1000;'\ndocument.body.appendChild(tooltip)\n\n// computePosition is sync and returns x/y/placement/middlewareData\nfunction updatePosition() {\n const { x, y, placement } = computePosition(button, tooltip, {\n placement: 'top',\n })\n tooltip.style.left = x + 'px'\n tooltip.style.top = y + 'px'\n console.log(`Positioned at ${placement}: (${Math.round(x)}, ${Math.round(y)})`)\n}\n\nbutton.addEventListener('click', updatePosition)\nupdatePosition()\nconsole.log('Tooltip positioned relative to button')",
23
- "name": "computePosition - Basic"
24
- },
25
- {
26
- "id": "position-float",
27
- "code": "import { createPositioner, offset, flip, shift } from '@vielzeug/orbit'\n\nconst button = document.createElement('button')\nbutton.textContent = 'Hover me'\nbutton.style.cssText = 'margin: 100px; padding: 8px 16px;'\ndocument.body.appendChild(button)\n\nconst tooltip = document.createElement('div')\ntooltip.textContent = 'Tooltip with middleware'\ntooltip.style.cssText = 'position: fixed; background: #1e293b; color: #fff; padding: 8px 12px; border-radius: 6px; font-size: 13px; pointer-events: none; display: none;'\ndocument.body.appendChild(tooltip)\n\nlet positioner = null\n\nfunction show() {\n tooltip.style.display = 'block'\n positioner?.dispose()\n positioner = createPositioner(button, tooltip, {\n middleware: [offset(8), flip(), shift({ padding: 8 })],\n placement: 'top',\n })\n console.log('Placement:', positioner.getPosition().placement)\n}\n\nfunction hide() {\n tooltip.style.display = 'none'\n positioner?.dispose()\n positioner = null\n}\n\nbutton.addEventListener('mouseenter', show)\nbutton.addEventListener('mouseleave', hide)\n\nconsole.log('Hover the button to position the tooltip')",
28
- "name": "createPositioner - With Middleware"
29
- },
30
- {
31
- "id": "presets",
32
- "code": "import { createPositioner } from '@vielzeug/orbit'\nimport { tooltip, dropdown, popover, contextMenu } from '@vielzeug/orbit/presets'\n\n// Presets are pre-configured middleware stacks for common UI patterns.\n// Each factory returns { placement, middleware }: spread into createPositioner().\n\n// --- tooltip() ---\nconst tooltipPreset = tooltip()\nconsole.log('tooltip placement:', tooltipPreset.placement)\nconsole.log('tooltip middleware count:', tooltipPreset.middleware.length)\n\n// Customise placement and offset:\nconst topTooltip = tooltip({ placement: 'top', offset: 12 })\nconsole.log('custom tooltip placement:', topTooltip.placement)\n\n// --- dropdown() ---\nconst dropdownPreset = dropdown()\nconsole.log('dropdown placement:', dropdownPreset.placement)\n\nconst wideDropdown = dropdown({ offset: 8, padding: 6 })\nconsole.log('wide dropdown middleware count:', wideDropdown.middleware.length)\n\n// --- popover() ---\nconst popoverPreset = popover()\nconsole.log('popover placement:', popoverPreset.placement)\n\n// --- contextMenu() ---\nconst menuPreset = contextMenu()\nconsole.log('contextMenu placement:', menuPreset.placement)\n\nconst menuTopStart = contextMenu({ placement: 'top-start' })\nconsole.log('contextMenu custom placement:', menuTopStart.placement)\n\n// --- Spread a preset into createPositioner() ---\nconst trigger = document.createElement('button')\ntrigger.textContent = 'Hover me'\ntrigger.style.cssText = 'margin: 80px; padding: 8px 16px;'\ndocument.body.appendChild(trigger)\n\nconst tip = document.createElement('div')\ntip.textContent = 'tooltip()'\ntip.style.cssText = 'position: fixed; background: #1e293b; color: #fff; padding: 6px 10px; border-radius: 6px; font-size: 13px; display: none;'\ndocument.body.appendChild(tip)\n\nlet positioner = null\n\ntrigger.addEventListener('mouseenter', () => {\n tip.style.display = 'block'\n positioner = createPositioner(trigger, tip, tooltip())\n})\ntrigger.addEventListener('mouseleave', () => {\n tip.style.display = 'none'\n positioner?.dispose()\n positioner = null\n})\n\nconsole.log('Hover the button to see tooltip() in action')",
33
- "name": "presets - Ready-made Middleware Stacks"
34
- },
35
- {
36
- "id": "size-middleware",
37
- "code": "import { createPositioner, offset, flip, size } from '@vielzeug/orbit'\n\nconst button = document.createElement('button')\nbutton.textContent = 'Open dropdown'\nbutton.style.cssText = 'margin:50px;padding:8px 16px;'\ndocument.body.appendChild(button)\n\nconst dropdown = document.createElement('div')\ndropdown.style.cssText = 'position:fixed;left:0;top:0;background:#fff;border:1px solid #e5e5e5;border-radius:6px;overflow-y:auto;box-shadow:0 4px 12px rgba(0,0,0,.1);'\n// Populate dropdown with many items\nfor (let i = 1; i <= 20; i++) {\n const item = document.createElement('div')\n item.textContent = 'Option ' + i\n item.style.cssText = 'padding:8px 16px;cursor:pointer;'\n dropdown.appendChild(item)\n}\ndocument.body.appendChild(dropdown)\n\n// size() writes availableHeight/availableWidth to middlewareData.size.\n// Read it in the positioner apply callback to constrain the floating element.\nconst positioner = createPositioner(button, dropdown, {\n placement: 'bottom-start',\n middleware: [offset(4), flip(), size({ padding: 8 })],\n apply(result) {\n const sizeData = result.middlewareData.size\n if (sizeData) {\n dropdown.style.maxHeight = Math.min(sizeData.availableHeight, 300) + 'px'\n console.log('Available height:', sizeData.availableHeight)\n }\n dropdown.style.left = result.x + 'px'\n dropdown.style.top = result.y + 'px'\n console.log('Resolved placement:', result.placement)\n },\n})\n\nconsole.log('size() constrains dropdown height to available space')",
38
- "name": "size() - Constrain Height"
39
- }
40
- ],
41
- "typeSignatures": {
42
- "AutoUpdateOptions": "export type { AutoUpdateOptions } from './auto-update';",
43
- "autoUpdate": "export { autoUpdate } from './auto-update';",
44
- "computePosition": "export { computePosition } from './core';",
45
- "OrbitConfigError": "export { OrbitConfigError, OrbitError } from './errors';",
46
- "OrbitError": "export { OrbitConfigError, OrbitError } from './errors';",
47
- "Positioner": "export type { Positioner, PositionerOptions, PositionStrategy } from './float';",
48
- "PositionerOptions": "export type { Positioner, PositionerOptions, PositionStrategy } from './float';",
49
- "PositionStrategy": "export type { Positioner, PositionerOptions, PositionStrategy } from './float';",
50
- "createPositioner": "export { createPositioner } from './float';",
51
- "InlineOptions": "export type { InlineOptions } from './inline';",
52
- "inline": "export { inline } from './inline';",
53
- "ArrowOptions": "export type { ArrowOptions } from './middleware/arrow';",
54
- "arrow": "export { arrow } from './middleware/arrow';",
55
- "AutoPlacementOptions": "export type { AutoPlacementOptions } from './middleware/auto-placement';",
56
- "autoPlacement": "export { autoPlacement } from './middleware/auto-placement';",
57
- "FlipOptions": "export type { FlipOptions } from './middleware/flip';",
58
- "flip": "export { flip } from './middleware/flip';",
59
- "HideOptions": "export type { HideOptions } from './middleware/hide';",
60
- "hide": "export { hide } from './middleware/hide';",
61
- "OffsetConfig": "export type { OffsetConfig, OffsetValue } from './middleware/offset';",
62
- "OffsetValue": "export type { OffsetConfig, OffsetValue } from './middleware/offset';",
63
- "offset": "export { offset } from './middleware/offset';",
64
- "LimitShiftOptions": "export type { LimitShiftOptions, ShiftLimiter, ShiftOptions } from './middleware/shift';",
65
- "ShiftLimiter": "export type { LimitShiftOptions, ShiftLimiter, ShiftOptions } from './middleware/shift';",
66
- "ShiftOptions": "export type { LimitShiftOptions, ShiftLimiter, ShiftOptions } from './middleware/shift';",
67
- "limitShift": "export { limitShift, shift } from './middleware/shift';",
68
- "shift": "export { limitShift, shift } from './middleware/shift';",
69
- "SizeOptions": "export type { SizeOptions } from './middleware/size';",
70
- "size": "export { size } from './middleware/size';",
71
- "detectOverflow": "export { detectOverflow, getBoundaryRect, getClippingAncestorRect } from './overflow';",
72
- "getBoundaryRect": "export { detectOverflow, getBoundaryRect, getClippingAncestorRect } from './overflow';",
73
- "getClippingAncestorRect": "export { detectOverflow, getBoundaryRect, getClippingAncestorRect } from './overflow';",
74
- "PositioningPreset": "export type { PositioningPreset, PresetOptions } from './presets';",
75
- "PresetOptions": "export type { PositioningPreset, PresetOptions } from './presets';",
76
- "Alignment": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
77
- "ArrowData": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
78
- "ComputePositionOptions": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
79
- "ComputePositionResult": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
80
- "DetectOverflowOptions": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
81
- "FlipData": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
82
- "HideData": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
83
- "Middleware": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
84
- "MiddlewareData": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
85
- "MiddlewareReset": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
86
- "MiddlewareResult": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
87
- "MiddlewareState": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
88
- "Padding": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
89
- "Placement": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
90
- "Rect": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
91
- "ReferenceElement": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
92
- "ShiftData": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
93
- "Side": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
94
- "SideObject": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
95
- "SizeData": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
96
- "VirtualReference": "export type {\n Alignment,\n ArrowData,\n ComputePositionOptions,\n ComputePositionResult,\n DetectOverflowOptions,\n FlipData,\n HideData,\n Middleware,\n MiddlewareData,\n MiddlewareReset,\n MiddlewareResult,\n MiddlewareState,\n Padding,\n Placement,\n Rect,\n ReferenceElement,\n ShiftData,\n Side,\n SideObject,\n SizeData,\n VirtualReference,\n} from './types';",
97
- "getAlignment": "export { getAlignment, getSide } from './utils';",
98
- "getSide": "export { getAlignment, getSide } from './utils';"
99
- }
100
- }
@@ -1,78 +0,0 @@
1
- {
2
- "apiSource": "export type { ComponentDefinition } from './component-types';\nexport { createContext, type InjectionKey, inject, injectStrict, provide } from './context';\nexport { define } from './define';\n// Near-universal template directives: used in most non-trivial components (lists,\n// conditionals, and class/style maps. Kept in the main entry alongside\n// `html`/`define` rather than a separate sub-path: tree-shaking already means an unused export\n// costs nothing in a bundled consumer, so splitting these off only adds an extra import line\n// for functionality most components need on day one. `unsafeHtml()` and `model()` remain here\n// too: their explicit names make their specialized behavior clear without a second import path.\nexport { classMap } from './directives/classMap';\nexport { each } from './directives/each';\nexport { type ModelOptions, model } from './directives/model';\nexport { styleMap } from './directives/styleMap';\nexport { unsafeHtml } from './directives/unsafe-html';\nexport { when } from './directives/when';\nexport { OreApiError, OreError, type OreErrorPhase, OreInternalError, OreLifecycleError } from './errors';\nexport { type FormFieldHandle, type FormFieldOptions, type FormFieldValidity, useField } from './forms/field';\nexport {\n type AttributeBindings,\n type BindOptions,\n bind,\n type HostBindConfig,\n type HostBindingValue,\n} from './host-bind';\nexport type { InferProps, PropDef, PropInputDefs, PropsDef } from './props';\nexport { prop } from './props';\n// Lifecycle hooks: plain functions, called during setup() or a composable it invokes.\nexport {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';\nexport { type ComponentSlots, useSlots } from './slots';\nexport { html } from './template/instantiator';\nexport { type HTMLResult, type Ref, type RefCallback, ref } from './template/result';\nexport { type CSSResult, css } from './utils/css';\nexport type { MaybeReactive } from './utils/dom';\nexport { type EmitFn, useEmit } from './utils/emit';\n\nexport { createId } from './utils/id';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Ore: Web component authoring with signals'\ndescription: Functional custom-element authoring with typed props, reactive templates, lifecycle helpers, and testing utilities.\npackage: ore\ncategory: ui-primitives\nkeywords: [web-components, custom-elements, reactive, templates, signals, lifecycle]\nrelated: [ripple, refine, orbit]\nexports:\n [\n define,\n prop,\n html,\n css,\n ref,\n createContext,\n inject,\n injectStrict,\n provide,\n onMounted,\n onCleanup,\n onEvent,\n onElement,\n onFormReset,\n watchEffect,\n useEmit,\n useSlots,\n getHost,\n bind,\n each,\n when,\n classMap,\n styleMap,\n live,\n model,\n unsafeHtml,\n useField,\n createId,\n OreError,\n OreApiError,\n OreInternalError,\n OreLifecycleError,\n AttributeBindings,\n BindOptions,\n MaybeReactive,\n ]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"ore\" />\n\n## Why Ore?\n\nOre keeps custom elements functional and signal-driven while giving you direct control over templates, lifecycle hooks, host bindings, and form-associated behavior.\n\n```ts\n// Before: vanilla custom element boilerplate\nclass MyCounter extends HTMLElement {\n #count = 0;\n connectedCallback() {\n this.attachShadow({ mode: 'open' });\n this.#render();\n }\n #render() {\n this.shadowRoot!.innerHTML = `<button>${this.#count}</button>`;\n this.shadowRoot!.querySelector('button')!.onclick = () => {\n this.#count++;\n this.#render();\n };\n }\n}\ncustomElements.define('my-counter', MyCounter);\n\n// After: Ore\nimport { signal } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('my-counter', {\n setup() {\n const count = signal(0);\n return html`<button @click=${() => count.value++}>${count}</button>`;\n },\n});\n```\n\n| Feature | Ore | Lit | Stencil |\n| -------------------------- | -------------------------------------------- | ------------------------------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"ore\" type=\"size\" /> | ~12 kB | ~60 kB+ toolchain |\n| Signal-first runtime | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> (separate signals package) | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Functional component setup | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Typed prop helpers | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Host binding helpers | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial | Partial |\n| Form-associated helpers | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual | Partial |\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 Ore when** you want typed, signal-driven custom elements with minimal runtime overhead and no framework lock-in.\n\n**Consider Lit when** you need a mature ecosystem with wide community adoption and don't need signal-based reactivity.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/ore @vielzeug/ripple\n```\n\n```sh [npm]\nnpm install @vielzeug/ore @vielzeug/ripple\n```\n\n```sh [yarn]\nyarn add @vielzeug/ore @vielzeug/ripple\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\nimport { bind, css, define, html, onMounted, prop } from '@vielzeug/ore';\n\ndefine('my-counter', {\n props: {\n label: prop.string('Count'),\n step: prop.number(1),\n },\n styles: [\n css`\n :host {\n display: inline-grid;\n gap: 0.5rem;\n }\n `,\n ],\n setup(props) {\n const count = signal(0);\n const doubled = computed(() => count.value * 2);\n\n bind({ class: { 'is-positive': () => count.value > 0 } });\n\n onMounted(() => console.log('mounted'));\n\n return html`\n <button @click=${() => (count.value += props.step.value)}>${props.label}: ${count}</button>\n <p>Doubled: ${doubled}</p>\n `;\n },\n});\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- Signal-first runtime with `signal`, `computed`, `watch`, `batch` from `@vielzeug/ripple`: import them directly\n- Functional component authoring via `define(tag, { props, setup, styles, formAssociated })`\n- Props via `prop.*` helpers (`prop.string`, `prop.number`, `prop.bool`, `prop.oneOf`, `prop.json`, `prop.data`) or raw `PropDef` objects\n- `setup(props)` takes only props and returns an `HTMLResult` directly: `return html\\`...\\``\n- Lifecycle hooks: `onMounted`, `onCleanup`, `onEvent`, `onElement`, `watchEffect`: plain functions imported from `@vielzeug/ore`, called directly from `setup()` or any composable it calls\n- Directives: `each` (transactional keyed list reconciliation), `classMap`, `styleMap`, `when`, `live`, `model`, `unsafeHtml`\n- Host bindings via `bind({ attr, class, style, on })`: pass `{ target: el }` to bind any off-host element\n- Reactive ARIA sync via explicit `aria-*` keys in `bind({ attr }, { target })`, with automatic cleanup on disconnect\n- Context via `provide(key, value)` / `inject(key)`; typed emit/slots via `useEmit<Emits>()` / `useSlots<SlotNames>()`\n- Form-associated `useField()` and observer helpers are root exports\n- Testing utilities (`@vielzeug/ore/testing`): `mount`, `renderHook`, `flush`, `cleanup`\n- Generic testing utilities (scoped queries, named event dispatchers, and async waits) are exported by `@vielzeug/assay`\n\n</div>\n\n## Package Entry Points\n\n| Import | Purpose |\n| ----------------------- | ----------------------------------------------------------------------------- |\n| `@vielzeug/ore` | All browser runtime APIs: components, directives, `useField`, and observers |\n| `@vielzeug/ore/testing` | Ore-specific mounting, lifecycle flushing, hooks, cleanup, and form internals |\n| `@vielzeug/assay` | Generic DOM events, scoped queries, and async waiting |\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Refine](../refine/index.md) for prebuilt accessible components powered by Ore.\n- [Ripple](../ripple/index.md) for reactive state used inside Ore components.\n- [Forge](../forge/index.md) for typed form state that integrates with Ore.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Ore: API Reference'\ndescription: Complete API reference for @vielzeug/ore and @vielzeug/ore/testing.\n---\n\n[[toc]]\n\n## API Overview\n\nAll browser-runtime symbols below are imported from `@vielzeug/ore`. Lifecycle/context/binding functions (`onMounted`, `onCleanup`, `onEvent`, `onElement`, `watchEffect`, `bind`, `provide`, `useEmit`, `useSlots`, `getHost`) resolve the active component through an implicit \"current component\" context: they work when called synchronously during `setup()`, or from any composable function `setup()` calls (transitively), but throw if called outside that window. The one exception is `bind()` with an explicit `options.target`: it also works outside setup (for example from an event handler), where only its returned disposer stops it.\n\n> `watchEffect` is not named `watch`: `@vielzeug/ripple` already exports a `watch(source, callback)` with different semantics (explicit source + old/new value pair), and the two are frequently imported in the same file.\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ----------------------- | --------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------ |\n| `define()` | Create and register a custom element | Sync | Tag must contain a hyphen; call before first use |\n| `html` | Tagged template literal returning HTMLResult | Sync | Expressions must be signals, functions, or primitives |\n| `prop.*` | Typed prop helpers (string, bool, number, …) | Sync | Prop values are signals: read `.value` |\n| `provide()`/`inject()` | Context API for parent-to-descendant sharing | Setup only | Must be called synchronously during `setup()` |\n| `ref()` | Reactive reference to a DOM element | Sync | Value is null until after first mount |\n| `createContext()` | Create a unique typed injection key | Sync | Context is scoped to the component tree |\n| `each()` | Keyed list rendering with DOM diffing | Sync | Duplicate keys report `ore:error`; plain `T[]` is a one-time static render |\n| `when()` | Conditional branch rendering | Sync | Getter-fn computed disposed on cleanup; static bool skips subscription |\n| `model(signal)` | Two-way form-control binding (value/checked + write-back) | Sync | Plain `value`/`checked` attribute only; pass `get` to keep numeric signals numeric |\n| `onMounted(fn)` | DOM-ready callback | Setup only | Must be called synchronously during `setup()` |\n| `onCleanup(fn)` | Register teardown | Setup only | Called on disconnect, one microtask later, unless the element reconnects (a same-turn move) |\n| `onEvent(target, …)` | Scoped event listener with auto-cleanup | Setup only | No-ops on null target; removed on disconnect |\n| `useField(options)` | Wire signal to form `ElementInternals` | Setup only | Requires `formAssociated: true` on the component definition |\n| `onFormReset(fn)` | Run work when the ancestor `<form>` resets | Setup only | Fires every reset (not one-shot); only for `formAssociated: true` components |\n| `useEmit<Emits>()` | Typed `emit()` bound to the current host | Setup only | Call once per component; returns `dispatchEvent`'s boolean (`false` if a listener called `preventDefault()`) |\n| `useSlots<SlotNames>()` | Reactive slot presence/element signals | Setup only | Safe to call more than once: the underlying registry is created once |\n| `getHost()` | The current component's host element | Setup only | Prefer a higher-level helper (`bind`, …) when one exists |\n\n## Package Entry Points\n\n| Import | Purpose |\n| ----------------------- | ----------------------------------------------------------------------------- |\n| `@vielzeug/ore` | All browser runtime APIs, including directives, fields, and lifecycle helpers |\n| `@vielzeug/ore/testing` | Ore-specific mounting, lifecycle, hook, cleanup, and form test support |\n| `@vielzeug/assay` | Generic DOM events, scoped queries, and async waiting |\n\n## Core Component API\n\n### `define(tag, definition)`\n\n```ts\ndefine<Props>(tag: string, definition: ComponentDefinition<Props>): CustomElementConstructor;\n```\n\nReturns the registered class (for `instanceof` or subclassing); registration itself is the only global side effect.\n\nOmit `Props` to infer prop types from `props`. Pass it explicitly when a public props type already exists: every key it\ndeclares must then have a definition in `props`.\n\nThe `setup()` function receives only typed prop signals:\n\n```ts\nsetup(props) {\n return html`<div>${props.label}</div>`;\n}\n```\n\nEverything else: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, html, onMounted, useEmit, useSlots } from '@vielzeug/ore';\n\ndefine('my-card', {\n setup(_props) {\n const emit = useEmit<{ close: undefined }>();\n const slots = useSlots<'header' | 'footer'>();\n\n onMounted(() => console.log('mounted'));\n\n // emit() returns dispatchEvent's boolean: false if a listener called preventDefault()\n const notCancelled = emit('close');\n\n // Render the <slot> unconditionally: has() observes rendered slots, so gating the slot itself on has() never shows it.\n return html`<header ?hidden=${() => !slots.has('header').value}><slot name=\"header\"></slot></header>`;\n },\n});\n```\n\n`useEmit<Emits>()` and `useSlots<SlotNames>()` are factory hooks: call them once per setup run to get a typed\n`emit`/`slots` bound to the current host. `useSlots()` is safe to call more than once within that setup run.\n\n### ComponentDefinition\n\n```ts\ntype ComponentDefinition<Props> = {\n formAssociated?: boolean;\n props?: PropsDef<Props>;\n setup: (props: InferProps<PropsDef<Props>>) => HTMLResult | null;\n shadow?: Partial<ShadowRootInit> | false; // false = light DOM (no shadow root)\n styles?: (string | CSSStyleSheet | CSSResult)[];\n};\n```\n\n## Runtime Helpers\n\n`onMounted`, `onCleanup`, `onEvent`, `onElement`, and `watchEffect` are plain functions imported from `@vielzeug/ore`. Call them directly during `setup()`.\n\n```ts\nimport { html, onCleanup, onEvent, onMounted } from '@vielzeug/ore';\n\nsetup(props) {\n onMounted(() => {\n // DOM is ready; return a function for mount-scoped cleanup\n return () => { /* cleanup on unmount */ };\n });\n\n onCleanup(() => { /* called on disconnect */ });\n\n onEvent(window, 'keydown', (e) => { /* auto-removed on disconnect */ });\n\n return html`...`;\n}\n```\n\nBecause these resolve the active component through an implicit context (rather than a value threaded through parameters), composable helper functions can call them directly too: no need to pass hooks in as options:\n\n```ts\nimport { onCleanup } from '@vielzeug/ore';\n\nfunction useMyHelper() {\n onCleanup(() => { /* teardown */ });\n}\n\n// In setup:\nsetup(_props) {\n useMyHelper();\n return html`...`;\n}\n```\n\n## Props API\n\n| Helper | Signature | Notes |\n| ------------------------------------ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `prop.string(defaultValue?)` | `PropDef<string>` | Reflects by default |\n| `prop.bool(defaultValue?)` | `PropDef<boolean>` | Any non-null attribute value other than `\"false\"` parses as `true`; `\"false\"` or absent attribute is `false` |\n| `prop.number(defaultValue?)` | `PropDef<number>` | Returns default (not NaN) and warns in dev when attribute is not a valid number |\n| `prop.oneOf(allowed, defaultValue?)` | `PropDef<T>` | Restricts to a fixed set of string or number members; `parse` falls back to `defaultValue` (or `undefined` when omitted) for anything outside the set. Numeric members match the attribute parsed as a number |\n| `prop.json(defaultValue)` | `PropDef<T>` | JSON.parse from attribute; `reflect: false` |\n| `prop.data<T>(defaultValue?)` | `PropDef<T>` | JS-only: never reads/writes an attribute; use for objects, arrays, callbacks, or any non-serialisable value |\n\n> **Choosing the right prop helper:**\n>\n> - **`prop.oneOf`**: the honest way to type a union-valued prop: the restriction is enforced at runtime (`parse` falls back for anything outside the set), not just in a type parameter a raw attribute value could violate. Pass an `as const` array of the allowed string or number members.\n> - **`prop.json`**: value can be declared in HTML (`<my-el config='{\"x\":1}'>`); attribute string is `JSON.parse`d.\n> - **`prop.data`**: value is always set from JavaScript (objects, arrays, callbacks, class instances); the attribute is never read. Use this for both data and function props.\n\nWhen you need custom parsing or `reflect: false`, use a raw `PropDef` object. Any `{ default, parse, reflect? }` object is a valid prop definition; `reflect` defaults to `false` for raw objects (the `prop.*` helpers reflect, except `prop.json` and `prop.data`). `define()` reports every invalid definition in one `OreApiError`:\n\n```ts\nprops: {\n items: { default: [], parse: () => [], reflect: false },\n}\n```\n\nUse `prop.data` for props that hold JS-only values (including callbacks) that cannot be serialised through an HTML attribute:\n\n```ts\ndefine('data-grid', {\n props: {\n getRowKey: prop.data<(row: unknown) => string>(),\n columns: prop.data<DataGridColumn[]>([]),\n onSort: prop.data<(key: string) => void>(),\n },\n setup(props) {\n // Set from JS: grid.getRowKey = (row) => row.id\n return html`...`;\n },\n});\n```\n\n## Template and Directives\n\n### `html`\n\nTagged template literal that returns an `HTMLResult`. Supports text interpolation, ordinary attributes (`attr=`),\nboolean attributes (`?attr=`), explicit property bindings (`.prop=`), events (`@event=` with optional\n`.stop`/`.prevent`/`.once`/`.capture` modifiers), refs (`ref=`), and nested templates.\n\nAn `HTMLResult` is opaque and single-use: each one owns the DOM nodes and bindings for one rendering. Rendering the\nsame result twice (mounting it again, interpolating it twice, or returning a cached result from a reactive getter)\nthrows `OreApiError`. Call the template function again when you need another copy.\n\n`.prop=${value}` always writes the element property (never an attribute): the explicit channel for structured\nvalues (arrays, objects, callbacks). Prototype-polluting names (`__proto__`, `constructor`, `prototype`) and\nraw-HTML-parsing names (`innerHTML`, `outerHTML`, `srcdoc`) are rejected at compile time: render sanitized\nHTML through the `unsafeHtml()` directive instead of a property binding.\n\n`@event.stop`, `.prevent`, `.once`, and `.capture` are shorthand for the matching listener behavior\n(`stopPropagation`/`preventDefault` applied before the handler runs; `once`/`capture` passed as listener\noptions). An unknown modifier throws at compile time.\n\n### `css`\n\nTagged template literal that returns a `CSSResult` for use in `styles`.\n\n### Directives\n\n| Directive | Purpose |\n| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `each(source, key, render, fallback?)` | Keyed reactive list; render receives `Readable<T>` and `Readable<number>`; plain `T[]` is a one-time static snapshot |\n| `when(condition, truthy, falsy?)` | Conditional rendering |\n| `classMap(record)` | Reactive class string from object map |\n| `styleMap(record)` | Reactive inline style string from object map |\n| `model(signal, options?)` | Two-way form-control binding: writes the signal to `value`/`checked` and writes user input back on the control's change event |\n| `unsafeHtml(value)` | HTML rendering sink; sanitize untrusted values before calling |\n\n`each()` treats number and string keys as distinct. A reconciliation failure (a duplicate key, or a render function that throws) reports `ore:error` and preserves the last valid list: entries created during the failed pass are rolled back, so the previous list stays exactly on screen.\n\n### `model(signal, options?)`\n\nTwo-way binding for a form control: `value=${model(signal)}`. It writes the signal to the control's `value`/`checked` property on every change and writes user input back into the signal on the control's change event (`'change'` for checkboxes, radios, and `<select>`; `'input'` otherwise). While the control holds an in-progress edit the signal has not received yet, stale writes to the signal are skipped.\n\n```ts\nconst text = signal('');\nconst agree = signal(false);\nconst count = signal(0);\n\nhtml`\n <input value=${model(text)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n <input type=\"number\" value=${model(count, { get: (el) => Number(el.value) })} />\n`;\n```\n\n`options` overrides the defaults for non-native controls: `event` sets the write-back event name and `get` reads the current value out of the element (default `el.checked` for checkboxes/radios, `el.value` otherwise). Because a native text input's `value` is always a string, pass a `get` like `(el) => Number(el.value)` to keep a numeric signal numeric. `model()` can only drive a plain `value`/`checked` attribute binding; using it on a boolean (`?checked=`) or other attribute throws.\n\n### `unsafeHtml`\n\n`unsafeHtml()` is an explicit HTML injection sink. It has no global sanitizer: sanitize untrusted\ncontent before passing it to the directive, so the trust boundary remains at the call site.\n\n```ts\nimport { unsafeHtml } from '@vielzeug/ore';\n\nconst safeArticle = sanitize(userSuppliedArticle);\n\nreturn html`<article>${unsafeHtml(safeArticle)}</article>`;\n```\n\n## Host Bindings\n\n`bind(config, options?)` is a plain function imported from `@vielzeug/ore`:\n\n```ts\nbind({\n attr: { role: 'button', 'aria-expanded': () => String(open.value) },\n class: { 'is-open': open },\n style: { '--height': () => height.value + 'px' },\n on: { click: handleClick },\n});\n```\n\n`bind()` auto-registers cleanup with the component scope: no manual `onCleanup` needed. Returns a cleanup function for early teardown.\n\n### Off-host bindings\n\nPass `{ target: el }` as a second argument to bind to any element other than the host:\n\n```ts\nbind({ attr: { 'aria-expanded': () => String(isOpen.value) } }, { target: triggerEl });\n```\n\nEvent listener options (`once`, `capture`, `passive`) are also accepted in the second argument. Cleanup is auto-registered with the component scope when called during setup.\n\n### Reactive ARIA attributes\n\nUse explicit `aria-*` keys in `bind({ attr }, { target })`:\n\n```ts\nconst stopAria = bind(\n {\n attr: {\n 'aria-controls': panelId,\n 'aria-expanded': () => isOpen.value,\n 'aria-haspopup': 'listbox',\n },\n },\n { target: triggerEl },\n);\n```\n\nStatic values are applied once. Getters and signals create reactive effects. Calling `stopAria()` stops updates. Values of `null`, `undefined`, or `false` remove the attribute.\n\n## Slots\n\n- `slots.has(name?)`: `Readable<boolean>`: whether the named (or default) slot has assigned content\n- `slots.elements(name?)`: `Readable<Element[]>`: the assigned elements for the slot\n\nSlot signals update reactively when assigned content changes, including when slots are inserted dynamically (via `when()` or `each()`) after mount.\n\nPresence is measured through the `<slot>` elements the component has rendered: content assigned to a slot that isn't rendered reports `false`. Always render the `<slot>` and use `has()` to hide or style its wrapper; ``when(slots.has('x'), () => html`<slot name=\"x\">`)`` never shows the slot.\n\n## Context API\n\n- `createContext<T>(description)`: Create a unique typed injection key; the description is diagnostic only\n- `provide(key, value)`: Provide a value to descendants\n- `inject(key)`: Resolve from nearest ancestor; returns `undefined` if not found\n- `inject(key, fallback)`: Resolve with a fallback value\n- `injectStrict(key)`: Resolve or throw if absent\n\n`provide()` and `inject()` must be called synchronously during `setup()`. Calling them outside a setup context throws\n`'Lifecycle hooks must be called during component setup'`. Context resolution walks the ancestor chain including shadow\nDOM boundaries. `inject()` resolves and caches its result once per consumer: provide a `Readable` (signal/computed)\nrather than a raw value if descendants need to observe later changes; re-calling `provide()` with a new raw value\nafterward is not seen by consumers that already resolved it (a dev-mode warning fires when a key is provided twice on\nthe same element). `provide()` registers cleanup automatically: context keys are removed from the registry when the\nproviding component disconnects, so reconnecting the same element runs `setup()` fresh without spurious \"overwriting\"\nwarnings or stale keys leaking to descendants.\n\n## Utilities\n\n- `ref<T>()`: Create a `Signal<T | null>` element reference. Set to the element via `ref=` in templates.\n- `createId(prefix = 'id')`: Generate a collision-resistant ID with a semantic prefix, a per-runtime tag, and a monotonic counter (for example, `'field-a3k21'`).\n\n## Form-Associated API\n\nImport from `@vielzeug/ore`.\n\n### `useField(options)`\n\nWire a form-associated element to `ElementInternals`. Requires `formAssociated: true` on the component definition. The `disabled` state tracking via `internals.states` (CustomStateSet) is skipped with a dev warning if the API is unavailable in the current environment.\n\n```ts\ntype FormFieldValidity = { flags: ValidityStateFlags; message: string };\n\ntype FormFieldOptions<T> = {\n disabled?: Readable<boolean>;\n /**\n * When true, a null/undefined value is submitted as '' instead of null,\n * keeping the field's key present in FormData even when the value is absent.\n * Only applies to the default toFormValue; ignored if toFormValue is provided.\n * @default false\n */\n emptyStringForNull?: boolean;\n /** Called when the ancestor <form> resets (see onFormReset): restore local field state here. */\n onReset?: () => void;\n toFormValue?: (value: T) => File | FormData | string | null;\n /**\n * Recomputed reactively and passed straight to internals.setValidity().\n * null (or omitted) = always valid. Flags and message travel together because\n * the platform's setValidity() contract couples them (flags without a\n * non-empty message throw); a single { flags, message } | null input makes a\n * desynced pair unrepresentable.\n */\n validity?: Readable<FormFieldValidity | null>;\n value: Signal<T> | Readable<T>;\n};\n\ntype FormFieldHandle = {\n checkValidity(): boolean;\n readonly internals: ElementInternals;\n reportValidity(): boolean;\n /** Set (non-empty message) or clear (empty string) a custom validity error. */\n setCustomValidity(message: string): void;\n};\n```\n\nPass a single `validity` signal to make `required`-style constraints participate in native constraint validation\nthrough `checkValidity()` and `reportValidity()`. The `{ flags, message }` pair is the one validity input: the old\nsplit `validity` + `validationMessage` options are gone, since they could drift apart into a state the platform\nrejects.\n\n```ts\nconst isBlank = (v: string) => v.trim() === '';\n\nuseField({\n validity: computed(() =>\n required.value && isBlank(value.value)\n ? { flags: { valueMissing: true }, message: 'This field is required.' }\n : null,\n ),\n value,\n});\n```\n\n## Testing APIs\n\nImport from `@vielzeug/ore/testing`.\n\n| API | Purpose |\n| ----------------------------- | ------------------------------------------------------------------------------------------------- |\n| `mount(setup, options?)` | Mount a component and return a test fixture |\n| `cleanup()` | Remove all mounted elements and reset test state |\n| `install(afterEach)` | Register auto-cleanup after each test |\n| `flush(options?)` | Drain reactive updates and animation frames |\n| `renderHook(setup, options?)` | Run a composable in a generated host component; overload accepts `propDefs` first for typed props |\n| `OreTimeoutError` | Error thrown when `flush()` cannot settle tracked Ore work |\n\n> **Test isolation:** `cleanup()` removes mounted elements and resets Ore's cross-test caches and counters. Call it in `afterEach`, or use `install(afterEach)`.\n\nImport `within`, named dispatchers such as `fireClick`, and waits such as `waitUntil` or `waitForEvent` from\n`@vielzeug/assay`.\n\n> **Form-associated component testing:** jsdom implements none of the `ElementInternals` form-association API.\n> `@vielzeug/assay` exports `installFormInternalsPolyfill()` for this: it polyfills\n> `setFormValue`/`setValidity`/`checkValidity`/`reportValidity`/`validationMessage`/`validity`/`states`, mixes\n> `checkValidity`/`reportValidity`/`validity`/`validationMessage` onto the host element itself (real browsers do\n> this for any `formAssociated: true` element), makes `FormData` collect a form-associated element's set value, and\n> makes `<form>.reset()` invoke `formResetCallback()`. Every patch is a guarded no-op when its target already\n> exists, and the function returns an `uninstall()` that restores every patched global. Call it directly from a\n> test setup (alongside `install(afterEach)`) only when the suite tests form-associated components: the patches\n> are global, so suites without them shouldn't carry them. A downstream package (e.g. a component library built\n> on `ore`) should rely on it instead of hand-rolling its own copy.\n\n#### `Fixture` interface\n\n```ts\ninterface Fixture<T extends HTMLElement = HTMLElement> {\n [Symbol.dispose](): void; // Delegates to dispose(): enables `using` declarations\n element: T;\n readonly disposed: boolean; // true after dispose() has been called\n readonly shadow: ShadowRoot | null;\n get<E extends Element>(selector: string): E;\n query<E extends Element>(selector: string): E | null;\n queryAll<E extends Element>(selector: string): E[];\n getByText<E extends Element>(text: string, selector?: string): E;\n queryByText<E extends Element>(text: string, selector?: string): E | null;\n queryAllByText<E extends Element>(text: string, selector?: string): E[];\n getByTestId<E extends Element>(testId: string): E;\n queryByTestId<E extends Element>(testId: string): E | null;\n queryAllByTestId<E extends Element>(testId: string): E[];\n attr(name: string, value: string | number | boolean): Promise<void>;\n attrs(record: Record<string, string | number | boolean>): Promise<void>;\n flush(options?: FlushOptions): Promise<void>;\n act(fn: () => unknown): Promise<void>;\n dispose(): void; // Removes the component from the DOM: idempotent\n}\n```\n\n#### `renderHook`\n\nUseful for testing composable lifecycle hooks (`onMounted`, `watchEffect`, `inject`, etc.) without a template. The setup runs inside a real, generated host component (exposed as `element`), so every hook behaves exactly as it does in `define()`. Pass `{ formAssociated: true }` for composables that call `useField()` or `onFormReset()`. Like `mount().dispose()`, `dispose()` removes the host and its cleanups run one microtask later:\n\n```ts\n// Without props\nconst { result, flush, dispose } = await renderHook(() => {\n const count = signal(0);\n onMounted(() => {\n count.value = 1;\n });\n return count;\n});\nexpect(result.value).toBe(1);\n\n// With typed props (prop-defs overload)\nconst { result } = await renderHook({ label: prop.string('hello'), count: prop.number(0) }, (props) => props.label);\nexpect(result.value).toBe('hello');\n```\n\n## Ripple Primitives\n\nOre does **not** re-export reactive primitives. Import them directly from `@vielzeug/ripple`:\n\n```ts\nimport { batch, computed, signal, watch } from '@vielzeug/ripple';\n```\n\nSee the [Ripple documentation](/ripple/) for the full API.\n\n## Lifecycle Events\n\n| Event | When |\n| ----------- | --------------------------------------------------------------------------------- |\n| `ore:error` | When a lifecycle callback fails: bubbles, composed; detail is `OreLifecycleError` |\n\n## Types\n\n```ts\ntype PropDef<T> = {\n readonly default: T;\n readonly parse: (value: string | null) => T;\n reflect?: boolean;\n};\n\ntype PropsDef<T extends Record<string, unknown>> = {\n [K in keyof T]-?: PropDef<T[K]>;\n};\n\ntype PropInputDefs = Record<string, PropDef<unknown>>;\n\n/**\n * Infer reactive props type from a PropInputDefs map.\n * Each entry becomes Readable<T> keyed by prop name.\n */\ntype InferProps<D extends PropInputDefs> = {\n readonly [K in keyof D]-?: Readable<InferPropValue<D[K]>>;\n};\n\n// Runtime hooks: all plain functions imported from '@vielzeug/ore', not fields on an object.\ntype OnMountedCallback = () => Cleanup | undefined;\ntype OnFormResetCallback = () => void;\n\ndeclare function onMounted(fn: OnMountedCallback): void; // DOM-ready callback; runs after each connection's render\ndeclare function onCleanup(fn: Cleanup): void; // Register teardown; called on disconnect\ndeclare function onElement<T extends HTMLElement>(\n ref: Readable<T | null>,\n callback: (el: T) => Cleanup | undefined,\n): () => void;\ndeclare function onEvent<K extends keyof HTMLElementEventMap>(\n target: EventTarget | null | undefined,\n event: K,\n listener: (e: HTMLElementEventMap[K]) => void,\n options?: AddEventListenerOptions,\n): void;\ndeclare function onEvent(\n target: EventTarget | null | undefined,\n event: string,\n listener: EventListener,\n options?: AddEventListenerOptions,\n): void;\ndeclare function onFormReset(fn: OnFormResetCallback): void; // Runs on every ancestor <form> reset; formAssociated only\ndeclare function watchEffect(fn: () => Cleanup | undefined): () => void; // Component-owned reactive effect; disposed on disconnect, throws outside setup\ndeclare function bind(config: HostBindConfig, options?: BindOptions): () => void; // Bindings for host or any target element\ndeclare function provide<T>(key: InjectionKey<T>, value: T): void; // Register a context value on the host element\ndeclare function inject<T>(key: InjectionKey<T>): T | undefined;\ndeclare function inject<T>(key: InjectionKey<T>, fallback: T): T;\ndeclare function getHost(): HTMLElement; // The current component's host element\ndeclare function useEmit<Emits extends Record<string, unknown> = Record<string, never>>(): EmitFn<Emits>;\ndeclare function useSlots<SlotNames extends string = string>(): ComponentSlots<SlotNames>;\n\ntype ComponentDefinition<Props extends Record<string, unknown> = Record<never, never>> = {\n formAssociated?: boolean;\n props?: PropsDef<Props>;\n setup: (props: InferProps<PropsDef<Props>>) => HTMLResult | null;\n shadow?: Partial<ShadowRootInit> | false; // false = light DOM\n styles?: (string | CSSStyleSheet | CSSResult)[];\n};\n\ntype MaybeReactive<T> = T | Readable<T> | (() => T); // Plain value, signal, or getter: accepted by when(), each(), classMap(), and bind()\n\ntype HostBindingValue = MaybeReactive<string | number | boolean | null | undefined>;\n\ntype AttributeBindings = Record<string, HostBindingValue>;\n\ntype HostBindConfig = {\n attr?: AttributeBindings;\n class?: (() => Record<string, boolean>) | Record<string, Readable<boolean> | (() => boolean) | boolean>;\n on?: Record<string, ((event: Event) => void) | undefined>;\n style?: Record<string, HostBindingValue>;\n};\n\ntype BindOptions = AddEventListenerOptions & {\n target?: Element;\n};\n\ntype ComponentSlots<S extends string = string> = {\n elements(name?: S): Readable<Element[]>;\n has(name?: S): Readable<boolean>;\n};\n\ntype Ref<T extends Element> = Signal<T | null>;\n\ntype RefCallback<T extends Element> = (el: T | null) => void;\n\ntype InjectionKey<T> = symbol & { readonly __ore_injection_key?: T };\n\ninterface HTMLResult {} // Opaque, single-use: render it once (return, interpolate, or return from a directive callback)\n\ntype CSSResult = {\n content: string;\n toString(): string;\n};\n\ntype ModelOptions<T = unknown> = {\n /** Write-back event (default: 'change' for checkbox/radio/select, 'input' otherwise). */\n event?: string;\n /** Value reader (default: el.checked for checkbox/radio, el.value otherwise). */\n get?: (el: HTMLElement) => T;\n};\n\ntype EmitFn<T extends Record<string, unknown>> = {\n <K extends KeysWithoutDetail<T>>(event: K): boolean;\n <K extends Exclude<keyof T, KeysWithoutDetail<T>>>(event: K, detail: T[K]): boolean;\n};\n// KeysWithoutDetail is an internal helper type, not exported.\n\ntype FormFieldValidity = { flags: ValidityStateFlags; message: string };\n\ntype FormFieldOptions<T = unknown> = {\n disabled?: Readable<boolean>;\n emptyStringForNull?: boolean;\n onReset?: () => void;\n toFormValue?: (value: T) => File | FormData | string | null;\n validity?: Readable<FormFieldValidity | null>;\n value: Signal<T> | Readable<T>;\n};\n\ntype FormFieldHandle = {\n checkValidity: () => boolean;\n readonly internals: ElementInternals;\n reportValidity: () => boolean;\n setCustomValidity: (message: string) => void;\n};\n\n/** Phase in which a OreError occurred. */\ntype OreErrorPhase = 'each-reconcile' | 'form-reset' | 'mounted' | 'setup';\n```\n\n## Errors\n\n`OreError` is the base class for every Ore error class: `err instanceof OreError` catches all of them.\n\n- **`OreApiError`**: thrown when the `ore` API itself is misused: calling `define()` with a duplicate tag, calling a lifecycle hook (`inject`, `onMounted`, `onCleanup`, `onEvent`, …) outside of `setup()`, or passing an invalid prop definition to `define()`.\n- **`OreInternalError`**: thrown when an Ore invariant fails, indicating a package bug rather than invalid application code.\n- **`OreLifecycleError`**: reported in the `ore:error` event when component `setup()`, a mounted callback, a form-reset callback, or `each()` reconciliation fails. Extends `OreError` with:\n - `component: string`: the element's local name\n - `phase: OreErrorPhase`: `'setup'` | `'mounted'` | `'form-reset'` | `'each-reconcile'`\n - `cause: Error`: the original error thrown by `setup()`\n- **`OreTimeoutError`**: thrown by `flush()` (from `@vielzeug/ore/testing`) when pending Ore work does not settle before its timeout.\n\nLifecycle failures dispatch a bubbling, composed `ore:error` event whose `detail` is the `OreLifecycleError`. Setup\nfailures still rethrow their original error; mounted and form-reset callback failures are reported through the same\nevent so their remaining callbacks can continue.\n",
6
- "usage": "---\ntitle: 'Ore: Usage Guide'\ndescription: Practical Ore usage patterns for components, props, templates, slots, context, forms, Sentinel integration, and tests.\n---\n\n[[toc]]\n\n## Basic Usage\n\n`define(tag, definition)` creates and registers a custom element. Call it from the module or browser bootstrap responsible for registration.\n\nYour `setup()` function receives typed prop signals and returns an `HTMLResult` directly. Its state belongs to the\ncurrent connection: disconnect disposes it, and reconnecting the same element runs setup again.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('status-chip', {\n setup() {\n const online = signal(true);\n\n return html`\n <button @click=${() => (online.value = !online.value)}>${() => (online.value ? 'Online' : 'Offline')}</button>\n `;\n },\n});\n```\n\nEverything besides `props`: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, getHost, html, bind, useEmit, useSlots } from '@vielzeug/ore';\n\ndefine('my-widget', {\n setup(_props) {\n const el = getHost(); // the host HTMLElement\n const emit = useEmit<{ close: undefined }>(); // typed event emitter\n const slots = useSlots<'header'>(); // reactive slot observation\n\n bind({ attr: { role: 'group' } }); // host binding helper (attr, class, style, on)\n\n return html`<slot></slot>`;\n },\n});\n```\n\n## signals and effects\n\nOre does not re-export ripple primitives: import them directly from `@vielzeug/ripple`.\n\n```ts\nimport { batch, computed, effect, signal, watch } from '@vielzeug/ripple';\n\nconst count = signal(0);\nconst doubled = computed(() => count.value * 2);\n\neffect(() => {\n console.log('doubled =', doubled.value);\n});\n\nwatch(count, (next, prev) => {\n console.log('count changed', prev, '->', next);\n});\n\nbatch(() => {\n count.value = 1;\n count.value = 2;\n});\n```\n\n## onMounted and lifecycle\n\nUse `onMounted()` for DOM-dependent initialization that must run after the template is mounted. Use `onElement(ref, cb)` for work tied to a specific DOM node. `onEvent()` attaches a listener that is automatically removed on disconnect.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, onElement, onEvent, onMounted, ref, useSlots } from '@vielzeug/ore';\n\ndefine('deferred-init', {\n setup(_props) {\n const tabIndex = signal(0);\n const inputRef = ref<HTMLInputElement>();\n const slots = useSlots<'items'>();\n\n onMounted(() => {\n const items = slots.elements('items').value;\n console.log('Found', items.length, 'items');\n });\n\n onElement(inputRef, (input) => {\n input.focus();\n });\n\n onEvent(window, 'keydown', (e: KeyboardEvent) => {\n if (e.key === 'Escape') tabIndex.value = 0;\n });\n\n return html`<div><slot name=\"items\"></slot><input ref=${inputRef} /></div>`;\n },\n});\n```\n\n## prop definitions\n\nUse `prop.*` helpers for common cases, or raw `PropDef` objects for custom parsing or `reflect: false`.\n\n```ts\nimport { define, html, prop } from '@vielzeug/ore';\n\ndefine('x-button', {\n props: {\n label: prop.string('Button'),\n disabled: prop.bool(false),\n variant: prop.oneOf(['primary', 'secondary'] as const, 'primary'),\n count: prop.number(0),\n },\n setup(props) {\n return html`\n <button ?disabled=${props.disabled} data-variant=${props.variant}>${props.label} (${props.count})</button>\n `;\n },\n});\n```\n\n## template bindings\n\n`html` supports text, attributes, booleans, properties, events, refs, and nested templates. Event bindings accept\n`.stop`, `.prevent`, `.once`, and `.capture`: the first two apply before the handler runs, while the latter two use\nnative listener options. Unknown modifiers throw while Ore compiles the template.\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\nimport { define, html, model, ref } from '@vielzeug/ore';\n\ndefine('profile-name', {\n setup() {\n const name = signal('Alice');\n const inputRef = ref<HTMLInputElement>();\n\n return html`\n <label title=${computed(() => 'Current: ' + name.value)}>Name</label>\n <input\n ref=${inputRef}\n value=${model(name)}\n aria-label=${() => 'Current name ' + name.value} />\n <p>Hello ${name}</p>\n `;\n },\n});\n```\n\n## directives\n\nOre exports `each`, `classMap`, `styleMap`, `when`, `live`, `model`, and `unsafeHtml` from `@vielzeug/ore`.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { classMap, define, each, html, styleMap, when } from '@vielzeug/ore';\n\ndefine('task-list', {\n setup() {\n const tasks = signal([{ id: 1, text: 'Write tests' }]);\n const active = signal(true);\n\n return html`\n <ul\n class=\"${classMap({ ready: () => tasks.value.length > 0 })}\"\n style=${styleMap({ opacity: () => (active.value ? 1 : 0.5) })}>\n ${when(\n () => active.value,\n () => html`<li>Active</li>`,\n () => html`<li>Paused</li>`,\n )}\n ${each(\n tasks,\n (task) => task.id,\n (task) => html`<li>${() => task.value.text}</li>`,\n )}\n </ul>\n `;\n },\n});\n```\n\n### each() API\n\n`each(source, key, render, fallback?)` takes positional arguments:\n\n- **source**: signal, getter, or plain array\n- **key**: function returning a unique string or number per item; number and string keys remain distinct\n- **render**: receives reactive `item` and `index` signals\n- **fallback**: optional, rendered when the list is empty\n\n```ts\neach(\n items,\n (item) => item.id,\n (item, index) => html`<li>#${index}: ${() => item.value.label}</li>`,\n () => html`<li>No items</li>`,\n);\n```\n\nEach reactive reconciliation is transactional. Ore creates missing entries before committing updates or removing stale\nentries; if a render callback throws, entries created during that pass are rolled back and the last successful list\nremains on screen. Ore reports the failure through `ore:error` with phase `each-reconcile`.\n\nReused items keep their DOM nodes in place: when the surviving items stay in the same relative order (prepend, append,\ninterleaved inserts, or replacing list contents), `each()` never moves a reused node, so CSS transitions, animations,\nfocus, and nested component state survive the update untouched. Only genuine reorders move nodes, and a moved item\ntravels with everything its inner directives rendered. New items are built detached and inserted exactly once at their\nfinal position, so each item's custom elements connect a single time per render.\n\n## model: two-way form bindings\n\nUse `model(signal)` for a controlled input: it writes the signal to the control's `value`/`checked` property and\nwrites user input back on the control's change event (`'change'` for checkboxes, radios, and selects; `'input'`\notherwise).\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, model } from '@vielzeug/ore';\n\ndefine('live-search', {\n setup() {\n const query = signal('');\n const agree = signal(false);\n\n return html`\n <input value=${model(query)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n `;\n },\n});\n```\n\nA native text input's `value` is always a string, so pass a `get` reader to keep a numeric signal numeric, and an\n`event` name for custom controls that emit their own change event:\n\n```ts\nconst count = signal(0);\n\nhtml`\n <input type=\"number\" value=${model(count, { get: (el) => Number(el.value) })} />\n <my-picker value=${model(pick, { event: 'pick-change', get: (el) => (el as MyPicker).selection })} />\n`;\n```\n\n`model()` also guards in-progress edits: while the control holds a value the signal has not received yet, a stale\napp-state write to the signal is skipped instead of clobbering what the user is typing.\n\n## host bindings\n\n`bind()` wires reactive attrs, classes, styles, and events to the host element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html } from '@vielzeug/ore';\n\ndefine('x-toggle', {\n setup(_props) {\n const open = signal(false);\n\n bind({\n attr: { 'aria-expanded': () => String(open.value), role: 'button', tabindex: 0 },\n class: { 'is-open': open },\n on: { click: () => (open.value = !open.value) },\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nThe `bind` config supports `attr`, `class`, `style`, and `on` sections.\n\n## ARIA bindings\n\nUse explicit `aria-*` keys in `bind({ attr: config }, { target })` to reactively sync ARIA attributes to any element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onMounted } from '@vielzeug/ore';\n\ndefine('x-disclosure', {\n setup(_props) {\n const open = signal(false);\n const panelId = 'disclosure-panel';\n\n bind({\n attr: { role: 'button', tabindex: 0 },\n on: { click: () => (open.value = !open.value) },\n });\n\n onMounted(() => {\n const trigger = document.querySelector('#trigger') as HTMLElement;\n if (trigger) {\n // bind() registers cleanup automatically when called inside setup\n bind(\n {\n attr: {\n 'aria-controls': panelId,\n 'aria-expanded': () => String(open.value),\n 'aria-haspopup': 'region',\n },\n },\n { target: trigger },\n );\n }\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nStatic values are applied once. Getter functions create reactive effects. Setting a value to `null`, `undefined`, or `false` removes the attribute.\n\n`bind()` always returns a cleanup function. Use it to stop syncing early when a trigger element can be swapped out:\n\n```ts\nonMounted(() => {\n const trigger = document.querySelector('#trigger') as HTMLElement;\n const stopAria = bind({ attr: { 'aria-expanded': () => String(open.value) } }, { target: trigger });\n\n // Stop syncing when the trigger is replaced\n onCleanup(stopAria);\n});\n```\n\n### Binding a non-host element with `bind()`\n\nPass `{ target: el }` as a second argument to bind attributes, classes, styles, or events to any element:\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onMounted, ref } from '@vielzeug/ore';\n\ndefine('button-wrapper', {\n setup(_props) {\n const visible = signal(false);\n const btnRef = ref<HTMLButtonElement>();\n\n onMounted(() => {\n const btn = btnRef.value;\n if (!btn) return;\n\n bind(\n {\n attr: { 'aria-pressed': () => String(visible.value) },\n on: { click: () => (visible.value = !visible.value) },\n },\n { target: btn },\n );\n });\n\n return html`<button ref=${btnRef}>Toggle</button>`;\n },\n});\n```\n\n## slots and emits\n\n```ts\nimport { define, html, useEmit, useSlots } from '@vielzeug/ore';\n\ndefine('card-with-footer', {\n setup(_props) {\n const slots = useSlots<'header' | 'footer'>();\n const emit = useEmit<{ action: undefined }>();\n\n return html`\n <div class=\"card\">\n <slot name=\"header\"></slot>\n <slot></slot>\n <footer ?hidden=${() => !slots.has('footer').value}><slot name=\"footer\"></slot></footer>\n </div>\n <button @click=${() => emit('action')}>Go</button>\n `;\n },\n});\n```\n\nPass a `SlotNames` type parameter to `useSlots<SlotNames>()` to get typed `slots.has()` and `slots.elements()` calls.\n\nKeep the `<slot>` rendered and toggle its wrapper with `slots.has()`: presence is read from rendered slots, so a `<slot>` inside `when(slots.has(...))` would never appear.\n\n## context provide/inject\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { createContext, define, html, injectStrict, provide } from '@vielzeug/ore';\n\nconst COUNT_CTX = createContext<ReturnType<typeof signal<number>>>('count');\n\ndefine('count-provider', {\n setup(_props) {\n const count = signal(0);\n provide(COUNT_CTX, count);\n\n return html`<button @click=${() => count.value++}><slot></slot></button>`;\n },\n});\n\ndefine('count-consumer', {\n setup() {\n const count = injectStrict(COUNT_CTX);\n\n return html`<p>Count: ${count}</p>`;\n },\n});\n```\n\n`provide()` registers cleanup automatically: context keys are removed from the registry when the providing component disconnects. On reconnect, `setup()` runs fresh and `provide()` re-registers without spurious \"overwriting\" warnings. Provide a `Readable` (signal/computed) rather than a raw value if descendants need to observe later changes: `inject()` resolves and caches the value once per consumer connection.\n\n## form-associated elements\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, prop } from '@vielzeug/ore';\nimport { useField } from '@vielzeug/ore';\n\ndefine('rating-input', {\n formAssociated: true,\n setup() {\n const value = signal(0);\n const field = useField({ value });\n\n return html`\n <button @click=${() => (value.value = 1)}>1</button>\n <button @click=${() => (value.value = 2)}>2</button>\n <button @click=${() => (value.value = 3)}>3</button>\n <button @click=${() => field.reportValidity()}>Validate</button>\n <p>Current: ${value}</p>\n `;\n },\n});\n```\n\n## Sentinel Observers\n\nUse `@vielzeug/sentinel` for subscribable browser and DOM observations. Create element-dependent Sentinels inside `onMounted()` and dispose them with the component.\n\n```ts\nimport { define, html, onCleanup, onMounted, ref, watchEffect } from '@vielzeug/ore';\nimport { fromSubscribable } from '@vielzeug/ripple';\nimport { createElementSize, SentinelUnavailableError } from '@vielzeug/sentinel';\n\ndefine('x-observed', {\n setup(_props) {\n const boxRef = ref<HTMLDivElement>();\n\n onMounted(() => {\n const element = boxRef.value;\n if (!element) return;\n\n try {\n const size = createElementSize(element);\n const sizeState = fromSubscribable(size, { signal: size.disposalSignal });\n\n watchEffect(() => {\n console.log(sizeState.value?.width);\n });\n\n onCleanup(() => size.dispose());\n } catch (error) {\n if (!(error instanceof SentinelUnavailableError)) throw error;\n }\n });\n\n return html`<div ref=${boxRef}>Observe me</div>`;\n },\n});\n```\n\n## testing utilities\n\nImport from `@vielzeug/ore/testing`.\n\n```ts\nimport { afterEach, describe, expect, it } from 'vitest';\nimport { signal } from '@vielzeug/ripple';\nimport { fireClick } from '@vielzeug/assay';\nimport { html } from '@vielzeug/ore';\nimport { cleanup, mount } from '@vielzeug/ore/testing';\n\ndescribe('my-counter', () => {\n afterEach(cleanup);\n\n it('increments on click', async () => {\n let count!: ReturnType<typeof signal<number>>;\n const { query, act } = await mount(() => {\n count = signal(0);\n return html`<button @click=${() => count.value++}>${count}</button>`;\n });\n\n expect(query('button')?.textContent).toBe('0');\n\n await act(() => fireClick(query('button')!));\n\n expect(query('button')?.textContent).toBe('1');\n });\n});\n```\n\n## Framework Integration\n\nOre components are standard custom elements and work natively in any framework.\n\n::: code-group\n\n```tsx [React]\n// React 19+ supports custom elements natively.\nimport './x-toggle'; // wherever define('x-toggle', { ... }) is called\n\nfunction App() {\n return <x-toggle aria-label=\"Open menu\" />;\n}\n```\n\n```ts [Vue 3]\n<script setup lang=\"ts\">\nimport './x-toggle'; // wherever define('x-toggle', { ... }) is called\nimport { ref } from 'vue';\n\nconst open = ref(false);\n</script>\n\n<template>\n <x-toggle :aria-label=\"'Open menu'\" @click=\"open = !open\" />\n</template>\n```\n\n```svelte [Svelte]\n<script>\n import './x-toggle'; // wherever define('x-toggle', { ... }) is called\n\n function handleClick() {\n console.log('toggled');\n }\n</script>\n\n<x-toggle aria-label=\"Open menu\" on:click={handleClick} />\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Ripple\n\nImport ripple primitives directly from `@vielzeug/ripple` for standalone reactive state outside components.\n\n```ts\nimport { signal, computed } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\n// Shared state created outside any component\nconst theme = signal<'light' | 'dark'>('light');\nconst isDark = computed(() => theme.value === 'dark');\n\ndefine('theme-toggle', {\n setup() {\n return html`\n <button @click=${() => (theme.value = isDark.value ? 'light' : 'dark')}>\n ${() =>\n isDark.value ? '<ore-icon name=\"sun\" size=\"16\"></ore-icon>' : '<ore-icon name=\"moon\" size=\"16\"></ore-icon>'}\n </button>\n `;\n },\n});\n```\n\n### With Forge\n\nUse `@vielzeug/forge` for typed form state. `useField()` remains intentionally narrow: it connects a form-associated\ncustom element to native `ElementInternals` without imposing submission, validation, or dirty-state policy.\n\n```ts\nimport { createForm } from '@vielzeug/forge';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('signup-form', {\n setup(_props) {\n const form = createForm({ initialValues: { email: '' } });\n\n return html`\n <form\n @submit=${(event: SubmitEvent) => {\n event.preventDefault();\n void form.submit(async (values) => {\n console.log(values);\n });\n }}>\n <slot></slot>\n </form>\n `;\n },\n});\n```\n\n## Best Practices\n\n- Setup returns `html\\`...\\`` directly: not a function wrapping the template.\n- Use `watchEffect()` for reactive subscriptions tied to component lifetime: it auto-registers cleanup on disconnect.\n- Use `onElement(ref, cb)` instead of `onMounted` when the work is tied to a single DOM node.\n- Bind host attributes and classes via `bind()` rather than mutating the element directly.\n- Provide context at the nearest ancestor: avoid global context singletons.\n- Call `onCleanup()` for every resource allocated in `setup()` (WebSockets, intervals, external subscriptions).\n- Use `model(signal)` for form inputs: it writes both ways and never clobbers an in-progress user edit.\n- Extract composable helper functions freely: `onMounted`/`onCleanup`/`bind`/... resolve the active component through implicit context, so they work from any function called (transitively) during `setup()`, with no need to pass them in as parameters.\n- Test component mounting and lifecycle with `@vielzeug/ore/testing`; import generic DOM events, queries, and waits\n from `@vielzeug/assay`.\n",
7
- "examples": "---\ntitle: 'Ore: Examples'\ndescription: Practical examples and recipes for ore.\n---\n\n## Examples\n\n- [Counter Component](./examples/counter-component.md)\n- [Typed Props And Emits](./examples/typed-props-and-emits.md)\n- [Observers In onMounted()](./examples/observers-in-onmount.md)\n- [Search List With Directives](./examples/search-list-with-directives.md)\n- [Context Provider And Consumer](./examples/context-provider-and-consumer.md)\n- [Prop Helpers And Raw PropDef](./examples/propsof-builder-api.md)\n- [Form Associated Rating Input](./examples/form-associated-rating-input.md)\n- [Test Example With @vielzeug/ore/testing](./examples/test-example-at-vielzeug-ore-testing.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "counter-chip",
12
- "code": "import { define, html } from '@vielzeug/ore'\nimport { signal } from '@vielzeug/ripple'\n\n// define() registers a custom element: setup() returns a template whose\n// bindings track signals. No classes, no lifecycle boilerplate.\ndefine('counter-chip', {\n setup() {\n const count = signal(0)\n\n return html`\n <button style=\"padding: 8px 16px; border-radius: 8px; border: 1px solid currentColor; background: transparent; color: inherit; cursor: pointer; font: inherit\"\n @click=${() => count.value++}>\n clicked ${() => count.value} ×\n </button>\n `\n },\n})\n\nconst chip = document.createElement('counter-chip')\ndocument.body.appendChild(chip)\n\nconsole.log('mounted a <counter-chip> — click it, watch this log:')\nchip.addEventListener('click', () => console.log('chip clicked'))",
13
- "name": "Counter chip"
14
- },
15
- {
16
- "id": "todo-list",
17
- "code": "import { define, each, html, when } from '@vielzeug/ore'\nimport { signal } from '@vielzeug/ripple'\n\n// each() renders lists, when() toggles blocks: both reactive against signals.\nconst todos = signal([\n { done: true, id: 1, text: 'Read the ore overview' },\n { done: false, id: 2, text: 'Build a component with define()' },\n { done: false, id: 3, text: 'Ship it' },\n])\n\ndefine('todo-list', {\n setup() {\n const toggle = (id: number) => {\n todos.value = todos.value.map((t) => (t.id === id ? { ...t, done: !t.done } : t))\n }\n\n return html`\n <ol style=\"padding-left: 1.25rem; margin: 0 0 0.5rem\">\n ${each(\n todos,\n (todo) => todo.id,\n (todo) => html`\n <li style=${() => (todo.value.done ? 'opacity: 0.5; text-decoration: line-through; cursor: pointer' : 'cursor: pointer')}\n @click=${() => toggle(todo.value.id)}>\n ${() => todo.value.text}\n </li>`,\n () => html`<li>Nothing to do</li>`,\n )}\n </ol>\n <p>${when(\n () => todos.value.every((t) => t.done),\n () => html`<strong>All done 🎉</strong>`,\n () => html`<span>${() => todos.value.filter((t) => !t.done).length} remaining — click an item to toggle</span>`,\n )}</p>\n `\n },\n})\n\ndocument.body.appendChild(document.createElement('todo-list'))",
18
- "name": "Todo list"
19
- }
20
- ],
21
- "typeSignatures": {
22
- "ComponentDefinition": "export type { ComponentDefinition } from './component-types';",
23
- "createContext": "export { createContext, type InjectionKey, inject, injectStrict, provide } from './context';",
24
- "InjectionKey": "export { createContext, type InjectionKey, inject, injectStrict, provide } from './context';",
25
- "inject": "export { createContext, type InjectionKey, inject, injectStrict, provide } from './context';",
26
- "injectStrict": "export { createContext, type InjectionKey, inject, injectStrict, provide } from './context';",
27
- "provide": "export { createContext, type InjectionKey, inject, injectStrict, provide } from './context';",
28
- "define": "export { define } from './define';",
29
- "classMap": "export { classMap } from './directives/classMap';",
30
- "each": "export { each } from './directives/each';",
31
- "ModelOptions": "export { type ModelOptions, model } from './directives/model';",
32
- "model": "export { type ModelOptions, model } from './directives/model';",
33
- "styleMap": "export { styleMap } from './directives/styleMap';",
34
- "unsafeHtml": "export { unsafeHtml } from './directives/unsafe-html';",
35
- "when": "export { when } from './directives/when';",
36
- "OreApiError": "export { OreApiError, OreError, type OreErrorPhase, OreInternalError, OreLifecycleError } from './errors';",
37
- "OreError": "export { OreApiError, OreError, type OreErrorPhase, OreInternalError, OreLifecycleError } from './errors';",
38
- "OreErrorPhase": "export { OreApiError, OreError, type OreErrorPhase, OreInternalError, OreLifecycleError } from './errors';",
39
- "OreInternalError": "export { OreApiError, OreError, type OreErrorPhase, OreInternalError, OreLifecycleError } from './errors';",
40
- "OreLifecycleError": "export { OreApiError, OreError, type OreErrorPhase, OreInternalError, OreLifecycleError } from './errors';",
41
- "FormFieldHandle": "export { type FormFieldHandle, type FormFieldOptions, type FormFieldValidity, useField } from './forms/field';",
42
- "FormFieldOptions": "export { type FormFieldHandle, type FormFieldOptions, type FormFieldValidity, useField } from './forms/field';",
43
- "FormFieldValidity": "export { type FormFieldHandle, type FormFieldOptions, type FormFieldValidity, useField } from './forms/field';",
44
- "useField": "export { type FormFieldHandle, type FormFieldOptions, type FormFieldValidity, useField } from './forms/field';",
45
- "AttributeBindings": "export {\n type AttributeBindings,\n type BindOptions,\n bind,\n type HostBindConfig,\n type HostBindingValue,\n} from './host-bind';",
46
- "BindOptions": "export {\n type AttributeBindings,\n type BindOptions,\n bind,\n type HostBindConfig,\n type HostBindingValue,\n} from './host-bind';",
47
- "bind": "export {\n type AttributeBindings,\n type BindOptions,\n bind,\n type HostBindConfig,\n type HostBindingValue,\n} from './host-bind';",
48
- "HostBindConfig": "export {\n type AttributeBindings,\n type BindOptions,\n bind,\n type HostBindConfig,\n type HostBindingValue,\n} from './host-bind';",
49
- "HostBindingValue": "export {\n type AttributeBindings,\n type BindOptions,\n bind,\n type HostBindConfig,\n type HostBindingValue,\n} from './host-bind';",
50
- "InferProps": "export type { InferProps, PropDef, PropInputDefs, PropsDef } from './props';",
51
- "PropDef": "export type { InferProps, PropDef, PropInputDefs, PropsDef } from './props';",
52
- "PropInputDefs": "export type { InferProps, PropDef, PropInputDefs, PropsDef } from './props';",
53
- "PropsDef": "export type { InferProps, PropDef, PropInputDefs, PropsDef } from './props';",
54
- "prop": "export { prop } from './props';",
55
- "getHost": "export {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';",
56
- "OnFormResetCallback": "export {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';",
57
- "OnMountedCallback": "export {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';",
58
- "onCleanup": "export {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';",
59
- "onElement": "export {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';",
60
- "onEvent": "export {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';",
61
- "onFormReset": "export {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';",
62
- "onMounted": "export {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';",
63
- "watchEffect": "export {\n getHost,\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n onElement,\n onEvent,\n onFormReset,\n onMounted,\n watchEffect,\n} from './runtime';",
64
- "ComponentSlots": "export { type ComponentSlots, useSlots } from './slots';",
65
- "useSlots": "export { type ComponentSlots, useSlots } from './slots';",
66
- "html": "export { html } from './template/instantiator';",
67
- "HTMLResult": "export { type HTMLResult, type Ref, type RefCallback, ref } from './template/result';",
68
- "Ref": "export { type HTMLResult, type Ref, type RefCallback, ref } from './template/result';",
69
- "RefCallback": "export { type HTMLResult, type Ref, type RefCallback, ref } from './template/result';",
70
- "ref": "export { type HTMLResult, type Ref, type RefCallback, ref } from './template/result';",
71
- "CSSResult": "export { type CSSResult, css } from './utils/css';",
72
- "css": "export { type CSSResult, css } from './utils/css';",
73
- "MaybeReactive": "export type { MaybeReactive } from './utils/dom';",
74
- "EmitFn": "export { type EmitFn, useEmit } from './utils/emit';",
75
- "useEmit": "export { type EmitFn, useEmit } from './utils/emit';",
76
- "createId": "export { createId } from './utils/id';"
77
- }
78
- }
@@ -1,42 +0,0 @@
1
- {
2
- "apiSource": "// Public root surface of @vielzeug/palette. Every public export goes through this file.\n\nexport { contrastRatio, readableOn, relativeLuminance } from './contrast.js';\nexport { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';\nexport { PaletteConfigError, PaletteError, PaletteParseError } from './errors.js';\nexport { toHex, toHslString, toOklchString, toRgbString } from './format.js';\nexport { mix, ramp } from './mix.js';\nexport { parseColor } from './parse.js';\nexport type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';\n",
3
- "docs": {
4
- "index": "---\ntitle: 'Palette: Color math for design tools'\ndescription: 'Color parsing, conversion, mixing, and contrast for design tools'\npackage: palette\ncategory: utilities\nkeywords: [color, color parsing, oklch, oklab, hsl, contrast, wcag, mix, ramp, luminance]\nexports:\n [\n parseColor,\n toHex,\n toRgbString,\n toHslString,\n toOklchString,\n srgbToOklch,\n oklchToSrgb,\n isDisplayable,\n srgbToHsl,\n hslToSrgb,\n mix,\n contrastRatio,\n relativeLuminance,\n readableOn,\n ramp,\n PaletteParseError,\n PaletteConfigError,\n ]\nrelated: [arsenal, refine]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"palette\" />\n\n## Why Palette?\n\nDesign tools need color math that is correct where it matters — perceptual OKLab mixing, WCAG contrast, lossless extended-range conversions — without pulling in a color library that assumes a DOM, a canvas, or a particular color model.\n\n```ts\n// Before\nconst mid = { r: (a.r + b.r) / 2, g: (a.g + b.g) / 2, b: (a.b + b.b) / 2 }; // gamma-space average, looks wrong\nconst ratio = /* hand-rolled luminance, usually forgets the sRGB transfer function */;\n\n// After\nimport { contrastRatio, mix, parseColor, ramp } from '@vielzeug/palette';\n\nconst mid = mix(parseColor('#000000'), parseColor('#ffffff'), 0.5); // perceptual OKLab midpoint\nconst ratio = contrastRatio(parseColor('#767676'), parseColor('#ffffff')); // 4.54\nconst shades = ramp(parseColor('#3366cc'), { steps: 9 }); // OKLCH lightness ramp\n```\n\n| Feature | Palette | Ad-hoc color helpers |\n| --------------------------------------- | --------------------------------------------- | -------------------- |\n| Bundle size | <PackageInfo package=\"palette\" type=\"size\" /> | n/a |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a |\n| CSS Color 4 `oklab()`/`oklch()` parsing | Built in | Manual |\n| CSS named colors | Built in | Manual |\n| OKLab mixing with premultiplied alpha | Built in, matches `color-mix(in oklab)` | Manual |\n| WCAG 2.x contrast | Built in | Manual |\n| Perceptual ramps | OKLCH lightness, gamut-fitted | Manual |\n\n<div class=\"decision-callout\">\n\n**Use Palette when** an application needs headless color parsing, conversion, mixing, or contrast checks with no DOM or rendering assumptions.\n\n**Consider a rendering-layer color API when** the work is applying colors to a surface rather than computing them.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/palette\n```\n\n```sh [npm]\nnpm install @vielzeug/palette\n```\n\n```sh [yarn]\nyarn add @vielzeug/palette\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { mix, parseColor, ramp, readableOn, toHex } from '@vielzeug/palette';\n\nconst brand = parseColor('#3366cc');\nconst surface = parseColor('rgb(248 250 252)');\n\nconst ink = readableOn(surface, [parseColor('#0f172a'), parseColor('#334155')]);\nconst midpoint = mix(brand, surface, 0.5); // OKLab interpolation, like color-mix(in oklab)\nconst shades = ramp(brand, { steps: 9 }); // OKLCH lightness ramp\n\nconsole.log(toHex(ink ?? brand), toHex(midpoint), shades.map(toHex));\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `parseColor()`: `#rgb`/`#rgba`/`#rrggbb`/`#rrggbbaa`, `rgb()`/`hsl()` comma and space syntax, CSS Color 4 `oklab()`/`oklch()`, and CSS named colors\n- `toHex()`, `toRgbString()`, `toHslString()`, `toOklchString()`: formatting with documented clamping at the display boundary\n- `srgbToOklch()` / `oklchToSrgb()`, `srgbToHsl()` / `hslToSrgb()`: lossless round-trippable conversions via the standard Björn Ottosson OKLab matrices\n- `isDisplayable()`: gamut test for any `Rgba` against sRGB\n- `mix()`: OKLab interpolation with premultiplied alpha, matching CSS `color-mix(in oklab)`\n- `contrastRatio()` and `relativeLuminance()`: WCAG 2.x ratios on clamped sRGB\n- `readableOn()`: picks the first candidate meeting the AA/AAA threshold, with large-text thresholds\n- `ramp()`: deterministic OKLCH lightness ramps that keep hue and stay inside the gamut\n- Typed errors: `PaletteParseError` and `PaletteConfigError` share the `PaletteError` base\n- Pure functions only: no DOM, no disposal contract, zero dependencies\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Arsenal](/arsenal/): general-purpose utilities that complement headless color math.\n- [Refine](/refine/): components styled with design tokens that tools like this generate and check.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Palette: API Reference'\ndescription: API reference for color parsing, conversion, mixing, and contrast.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------------- | -------------------------------------------- | --------- | ------------------------------------------------------- |\n| `parseColor()` | Parse a CSS color string into `Rgba` | Sync | `color()` is out of scope; named colors are supported |\n| `toHex()` | Format as `#rrggbb`/`#rrggbbaa` | Sync | Alpha is written when translucent unless `alpha: false` |\n| `toRgbString()` | Format as CSS `rgb()` space syntax | Sync | Channels are clamped to 0–255 |\n| `toHslString()` | Format as CSS `hsl()` space syntax | Sync | Channels are clamped before conversion |\n| `toOklchString()` | Format as CSS `oklch()` syntax | Sync | Writes true channels, even out of gamut |\n| `srgbToOklch()` | Convert sRGB to OKLCH | Sync | Round-trip drifts up to ±1 per channel |\n| `oklchToSrgb()` | Convert OKLCH to sRGB | Sync | Out-of-gamut channels stay unclamped, they do not throw |\n| `isDisplayable()` | Test an `Rgba` against the sRGB gamut | Sync | Allows a small rounding tolerance |\n| `srgbToHsl()` | Convert sRGB to HSL | Sync | `h` is 0–360, `s`/`l` are 0–100 |\n| `hslToSrgb()` | Convert HSL to sRGB | Sync | Hue wraps; channels beyond the gamut stay unclamped |\n| `mix()` | OKLab interpolation with premultiplied alpha | Sync | `t` outside `[0, 1]` throws `PaletteConfigError` |\n| `relativeLuminance()` | WCAG 2.x relative luminance | Sync | Computed on channels clamped to 0–255 |\n| `contrastRatio()` | WCAG 2.x contrast ratio (1–21) | Sync | Ignores alpha by design |\n| `readableOn()` | First candidate meeting a WCAG threshold | Sync | Returns `null` when nothing passes |\n| `ramp()` | OKLCH lightness ramp of a base color | Sync | `steps` must be an integer ≥ 2 |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------- | --------------------------- |\n| `@vielzeug/palette` | Complete public Palette API |\n\n## Parsing\n\n### `parseColor()`\n\n```ts\nfunction parseColor(input: string): Rgba;\n```\n\nParses `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`; `rgb()`/`rgba()` and `hsl()`/`hsla()` in comma and space syntax with optional `/ alpha`; `oklab()`/`oklch()` with alpha per CSS Color 4; and the CSS named colors (case-insensitive, including `transparent`). Percentage `oklab` `a`/`b` and `oklch` `c` map to ±0.4; percentage `rgb` channels map to 0–255. Alpha accepts a number or percentage and clamps to 0–1. Out-of-range channels are kept exactly — nothing clips. Throws `PaletteParseError` including the offending input.\n\n## Formatting\n\n### `toHex()`\n\n```ts\nfunction toHex(color: Rgba, options?: FormatOptions): string;\n```\n\nFormats as `#rrggbb`, or `#rrggbbaa` when the color is translucent or `options.alpha` is `true`. Channels clamp to 0–255 and alpha to 0–1.\n\n### `toRgbString()`\n\n```ts\nfunction toRgbString(color: Rgba, options?: FormatOptions): string;\n```\n\nFormats as `rgb(r g b)` or `rgb(r g b / a)` space syntax. Same clamping as `toHex()`.\n\n### `toHslString()`\n\n```ts\nfunction toHslString(color: Rgba, options?: FormatOptions): string;\n```\n\nFormats as `hsl(h s% l%)` or `hsl(h s% l% / a)`. Channels clamp before conversion.\n\n### `toOklchString()`\n\n```ts\nfunction toOklchString(color: Rgba, options?: FormatOptions): string;\n```\n\nFormats as `oklch(l% c h)` or `oklch(l% c h / a)` on the color's true channels — an out-of-gamut color keeps its exact OKLCH values rather than the clamped ones.\n\n## Conversion\n\n### `srgbToOklch()` / `oklchToSrgb()`\n\n```ts\nfunction srgbToOklch(color: Rgba): Oklch;\nfunction oklchToSrgb(color: Oklch): Rgba;\n```\n\nStandard sRGB → linear → OKLab → OKLCH pipeline (Björn Ottosson's matrices with the sRGB transfer function, sign-extended to negative channels per CSS Color 4). The pipeline is lossless: `oklchToSrgb()` leaves out-of-gamut channels outside 0–255 instead of clipping, so `srgbToOklch()` recovers the original OKLCH values.\n\n### `isDisplayable()`\n\n```ts\nfunction isDisplayable(color: Rgba): boolean;\n```\n\nTrue when every linear-light channel of `color` falls inside `[0, 1]` (within a `0.00015` rounding tolerance, matching CSS Color 4 implementations). Works on any `Rgba` — parsed, converted, or mixed — so it detects out-of-gamut colors before a formatter clamps them.\n\n### `srgbToHsl()` / `hslToSrgb()`\n\n```ts\nfunction srgbToHsl(color: Rgba): Hsla;\nfunction hslToSrgb(color: Hsla): Rgba;\n```\n\n`h` is degrees in `[0, 360)`, `s` and `l` are percentages 0–100. `hslToSrgb()` wraps hue and leaves channels outside 0–255 unclamped (an `l` beyond 100% produces values beyond 255).\n\n## Mixing\n\n### `mix()`\n\n```ts\nfunction mix(a: Rgba, b: Rgba, t: number): Rgba;\n```\n\nInterpolates in OKLab with premultiplied alpha, matching CSS `color-mix(in oklab, ...)`. `t` is 0 for `a`, 1 for `b`; outside `[0, 1]` throws `PaletteConfigError`. A fully transparent endpoint contributes no color: mixing red with `rgba(0 0 0 / 0)` yields red at half alpha, not a darkened blend.\n\n## Contrast\n\n### `relativeLuminance()`\n\n```ts\nfunction relativeLuminance(color: Rgba): number;\n```\n\nWCAG 2.x relative luminance on channels clamped to 0–255.\n\n### `contrastRatio()`\n\n```ts\nfunction contrastRatio(a: Rgba, b: Rgba): number;\n```\n\nWCAG 2.x contrast ratio: 1 for identical colors, 21 for black on white. Symmetric in its arguments.\n\n### `readableOn()`\n\n```ts\nfunction readableOn(background: Rgba, candidates: readonly Rgba[], options?: ReadableOnOptions): Rgba | null;\n```\n\nReturns the first candidate whose contrast against `background` reaches the threshold: 4.5 (`level: 'AA'`, default) or 7 (`'AAA'`), or 3 / 4.5 with `large: true`. Returns `null` when no candidate passes.\n\n## Ramps\n\n### `ramp()`\n\n```ts\nfunction ramp(base: Rgba, options: RampOptions): Rgba[];\n```\n\nBuilds `steps` swatches dark to light by interpolating OKLab lightness between `minLightness` (default 0.15) and `maxLightness` (default 0.95) while keeping the base color's hue. Where a swatch would fall outside the sRGB gamut, its chroma is reduced (binary search at fixed lightness and hue) until it fits — so every swatch is displayable and the hue stays stable instead of shifting under clamping. Deterministic. Throws `PaletteConfigError` for non-integer or sub-2 `steps`, bounds outside `[0, 1]`, or `minLightness > maxLightness`.\n\n## Types\n\n### `Rgba`\n\n```ts\ntype Rgba = Readonly<{ r: number; g: number; b: number; a: number }>;\n```\n\nExtended-range sRGB: `r`/`g`/`b` are 0–255 for displayable colors but may fall outside that range when a color came from an out-of-gamut OKLCH/HSL value or out-of-range channels — the conversion pipeline never clips. `a` is always 0–1. Use `isDisplayable()` to test the gamut and the formatters (which clamp) for display-safe output.\n\n### `Hsla`\n\n```ts\ntype Hsla = Readonly<{ h: number; s: number; l: number; a: number }>;\n```\n\n`h` is degrees 0–360, `s` and `l` are percentages 0–100, `a` is 0–1.\n\n### `Oklch`\n\n```ts\ntype Oklch = Readonly<{ l: number; c: number; h: number; a: number }>;\n```\n\n`l` is lightness 0–1, `c` is chroma, `h` is hue in degrees, `a` is alpha 0–1. OKLab is the internal waypoint between sRGB and OKLCH and is not part of the public surface.\n\n### `FormatOptions`\n\n```ts\ntype FormatOptions = Readonly<{ alpha?: boolean }>;\n```\n\nWhen `alpha` is `true` the alpha channel is always written; otherwise it is written only when the color is translucent.\n\n### `ReadableOnOptions`\n\n```ts\ntype ReadableOnOptions = Readonly<{ level?: 'AA' | 'AAA'; large?: boolean }>;\n```\n\n### `RampOptions`\n\n```ts\ntype RampOptions = Readonly<{ steps: number; minLightness?: number; maxLightness?: number }>;\n```\n\n## Errors\n\n| Error | Thrown by | Meaning |\n| -------------------- | ----------------- | ----------------------------------------------------------------------------------- |\n| `PaletteParseError` | `parseColor()` | Input did not match the supported grammar; the message includes the offending input |\n| `PaletteConfigError` | `mix()`, `ramp()` | Invalid options or positions |\n\nBoth extend `PaletteError`, so `catch (error) { if (error instanceof PaletteError) ... }` narrows both.\n",
6
- "usage": "---\ntitle: 'Palette: Usage Guide'\ndescription: Parse, convert, mix, and check colors with headless color math.\n---\n\n[[toc]]\n\n## Basic Usage\n\n```ts\nimport { parseColor, toHex } from '@vielzeug/palette';\n\nconst brand = parseColor('#3366cc'); // { r: 51, g: 102, b: 204, a: 1 }\nconsole.log(toHex(brand)); // \"#3366cc\"\n```\n\n`parseColor()` accepts hex (3, 4, 6, and 8 digits), `rgb()`/`rgba()` and `hsl()`/`hsla()` in both comma and space syntax, CSS Color 4 `oklab()`/`oklch()`, and the CSS named colors (case-insensitive, including `transparent`). Anything else throws `PaletteParseError` with the offending input in the message. The `color()` notation is out of scope.\n\n## Parse CSS Colors\n\n```ts\nimport { parseColor } from '@vielzeug/palette';\n\nparseColor('#f09'); // #rgb: digits are duplicated\nparseColor('#f098'); // #rgba\nparseColor('rgb(1, 2, 3)'); // comma syntax\nparseColor('rgba(1, 2, 3, 0.5)'); // legacy comma alpha\nparseColor('rgb(1 2 3 / 0.5)'); // space syntax with slash alpha\nparseColor('rgb(50% 25% 0%)'); // percentages map to 0–255\nparseColor('hsl(120, 100%, 50%)'); // hue wraps: -120 and 480 are valid\nparseColor('oklab(0.5 -0.1 0.1 / 0.5)'); // CSS Color 4\nparseColor('oklch(50% 0.1 240deg)'); // percent lightness, deg hue\nparseColor('RebeccaPurple'); // named colors, any case\nparseColor('transparent'); // { r: 0, g: 0, b: 0, a: 0 }\n```\n\nPercentage `oklab` `a`/`b` and `oklch` `c` map to the CSS Color 4 range of ±0.4. Alpha accepts a number or a percentage and is clamped to 0–1. Out-of-range channels (`rgb(300 0 0)`) are kept exactly — parsing never clips.\n\n## Convert Between Color Spaces\n\n```ts\nimport { hslToSrgb, oklchToSrgb, parseColor, srgbToHsl, srgbToOklch } from '@vielzeug/palette';\n\nconst red = parseColor('#ff0000');\nconst oklch = srgbToOklch(red); // { l: 0.628, c: 0.2577, h: 29.23, a: 1 }\nconst hsl = srgbToHsl(red); // { h: 0, s: 100, l: 50, a: 1 }\n\nconst back = oklchToSrgb(oklch); // round-trips within ±1 per channel\n```\n\nConversions use the standard sRGB → linear → OKLab → OKLCH pipeline (Björn Ottosson's matrices, sRGB transfer function sign-extended per CSS Color 4). The pipeline is lossless: `oklchToSrgb()` leaves out-of-gamut channels outside 0–255, so `srgbToOklch()` recovers the original values, and `isDisplayable()` tells you whether a color fits the screen.\n\n## Format Colors\n\n```ts\nimport { parseColor, toHex, toHslString, toOklchString, toRgbString } from '@vielzeug/palette';\n\nconst translucent = parseColor('rgb(222 173 190 / 0.5)');\ntoHex(translucent); // \"#deadbe80\" — alpha is written when the color is translucent\ntoHex(translucent, { alpha: false }); // \"#deadbe\" — never write alpha...\ntoHex(parseColor('#deadbeef'), { alpha: true }); // \"#deadbeff\" — ...or always write it\ntoRgbString(translucent); // \"rgb(222 173 190 / 0.5)\"\ntoHslString(parseColor('#ff0000')); // \"hsl(0 100% 50%)\"\ntoOklchString(parseColor('#ff0000')); // \"oklch(62.8% 0.2577 29.23)\"\n```\n\n`toHex()`, `toRgbString()`, and `toHslString()` clamp out-of-gamut channels to 0–255 and alpha to 0–1 before writing, so their output is always display-safe. A color produced by `parseColor('rgb(300 0 0)')` keeps its out-of-range channel until formatted, where it clamps to `255`. `toOklchString()` writes the color's true OKLCH values — an out-of-gamut color round-trips through `parseColor()` exactly.\n\n## Mix in OKLab\n\n```ts\nimport { mix, parseColor, toHex } from '@vielzeug/palette';\n\nconst mid = mix(parseColor('#000000'), parseColor('#ffffff'), 0.5);\ntoHex(mid); // \"#636363\" — the perceptual midpoint, not #808080\n\nconst hover = mix(parseColor('#ff0000'), parseColor('rgb(0 0 0 / 0)'), 0.5);\ntoHex(hover); // \"#ff000080\" — transparent endpoints don't darken\n```\n\n`mix()` interpolates in OKLab with premultiplied alpha, matching CSS `color-mix(in oklab, ...)`: midpoints are perceptually even, and a transparent endpoint contributes no color instead of pulling the blend toward black. A `t` outside `[0, 1]` throws `PaletteConfigError`.\n\n## Check Contrast\n\n```ts\nimport { contrastRatio, parseColor, readableOn } from '@vielzeug/palette';\n\ncontrastRatio(parseColor('#000000'), parseColor('#ffffff')); // 21\ncontrastRatio(parseColor('#767676'), parseColor('#ffffff')); // ≈ 4.54 (AA boundary)\n\nconst ink = readableOn(parseColor('#f8fafc'), [parseColor('#94a3b8'), parseColor('#0f172a')]);\n// → #0f172a: the first candidate that reaches the threshold\n```\n\n`contrastRatio()` uses WCAG 2.x relative luminance on channels clamped to 0–255. `readableOn()` picks the first candidate meeting 4.5 (AA) or 7 (AAA), or 3 / 4.5 with `{ large: true }`, and returns `null` when nothing passes.\n\n## Build Lightness Ramps\n\n```ts\nimport { parseColor, ramp, toHex } from '@vielzeug/palette';\n\nconst shades = ramp(parseColor('#3366cc'), { steps: 9 });\nconsole.log(shades.map(toHex)); // nine swatches, dark to light\n```\n\n`ramp()` interpolates OKLab lightness between `minLightness` (default 0.15) and `maxLightness` (default 0.95) at the base color's hue. Where a swatch would leave the sRGB gamut, its chroma is reduced until it fits — every swatch is displayable and the hue never shifts under clamping. The result is deterministic and runs dark to light. Invalid `steps` or lightness bounds throw `PaletteConfigError`.\n\n## Errors\n\nAll failures are `PaletteError` subclasses: `PaletteParseError` for malformed input and `PaletteConfigError` for invalid options. Catch the base class to handle both.\n\n## Best Practices\n\n- Parse once at the boundary, keep `Rgba` values, and format at the edges; conversions are cheap but parsing strings repeatedly is wasteful.\n- Use `mix()` instead of averaging channels — gamma-space averages look muddy.\n- Use `ramp()` for tonal scales and `readableOn()` for ink selection instead of hand-tuned hex pairs.\n- Keep out-of-gamut colors in the pipeline as long as you like — conversions are lossless. Check `isDisplayable()` before handing a color to something that can't represent it, and let the formatters clamp at the display boundary.\n",
7
- "examples": "---\ntitle: 'Palette: Examples'\ndescription: Practical examples and recipes for @vielzeug/palette.\n---\n\n## Examples\n\n- [Parse, Mix and Contrast](./examples/parse-mix-and-contrast.md)\n"
8
- },
9
- "examples": [
10
- {
11
- "id": "palette-basic",
12
- "code": "import { contrastRatio, mix, parseColor, ramp, readableOn, toHex } from '@vielzeug/palette'\n\nconst brand = parseColor('#3366cc')\nconst surface = parseColor('rgb(248 250 252)')\n\nconst hover = mix(brand, surface, 0.5)\nconsole.log('hover', toHex(hover))\n\nconst ink = readableOn(surface, [parseColor('#94a3b8'), parseColor('#0f172a')])\nconsole.log('ink', ink ? toHex(ink) : null)\nconsole.log('contrast', contrastRatio(surface, ink ?? brand).toFixed(2))\n\nconsole.log('ramp', ramp(brand, { steps: 5 }).map(toHex).join(' '))",
13
- "name": "Basics - parse, mix, contrast, ramp"
14
- }
15
- ],
16
- "typeSignatures": {
17
- "contrastRatio": "export { contrastRatio, readableOn, relativeLuminance } from './contrast.js';",
18
- "readableOn": "export { contrastRatio, readableOn, relativeLuminance } from './contrast.js';",
19
- "relativeLuminance": "export { contrastRatio, readableOn, relativeLuminance } from './contrast.js';",
20
- "hslToSrgb": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
21
- "isDisplayable": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
22
- "oklchToSrgb": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
23
- "srgbToHsl": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
24
- "srgbToOklch": "export { hslToSrgb, isDisplayable, oklchToSrgb, srgbToHsl, srgbToOklch } from './convert.js';",
25
- "PaletteConfigError": "export { PaletteConfigError, PaletteError, PaletteParseError } from './errors.js';",
26
- "PaletteError": "export { PaletteConfigError, PaletteError, PaletteParseError } from './errors.js';",
27
- "PaletteParseError": "export { PaletteConfigError, PaletteError, PaletteParseError } from './errors.js';",
28
- "toHex": "export { toHex, toHslString, toOklchString, toRgbString } from './format.js';",
29
- "toHslString": "export { toHex, toHslString, toOklchString, toRgbString } from './format.js';",
30
- "toOklchString": "export { toHex, toHslString, toOklchString, toRgbString } from './format.js';",
31
- "toRgbString": "export { toHex, toHslString, toOklchString, toRgbString } from './format.js';",
32
- "mix": "export { mix, ramp } from './mix.js';",
33
- "ramp": "export { mix, ramp } from './mix.js';",
34
- "parseColor": "export { parseColor } from './parse.js';",
35
- "FormatOptions": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
36
- "Hsla": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
37
- "Oklch": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
38
- "RampOptions": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
39
- "ReadableOnOptions": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';",
40
- "Rgba": "export type { FormatOptions, Hsla, Oklch, RampOptions, ReadableOnOptions, Rgba } from './types.js';"
41
- }
42
- }