@vielzeug/codex 26.11.7 → 26.11.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +44 -44
- package/data/llms-full.txt +42 -11
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/ore.json +2 -2
- package/data/packages/sigil.json +17 -14
- package/data/refine.json +414 -56
- package/data/search.json +4 -4
- package/package.json +2 -2
package/data/search.json
CHANGED
|
@@ -959,8 +959,8 @@
|
|
|
959
959
|
"description": "functional custom element authoring with typed props, reactive templates, lifecycle helpers, and testing utilities.",
|
|
960
960
|
"docs": {
|
|
961
961
|
"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",
|
|
962
|
-
"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.\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| `live(signal)` | one way binding that skips stale writes during input | sync | use for controlled inputs alongside a manual `@input` handler |\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 component disconnect |\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\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 return html`${when(slots.has('header'), () => html`<slot name=\"header\"></slot>`)}`;\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:\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\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| `live(signal)` | one way binding that skips stale writes during active user input; use with `@input` handler |\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). this is the complete controlled input loop that the `live()` + manual `@input` handler pair used to require.\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\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)` | run lifecycle hooks in isolation; overload accepts `propdefs` as first arg 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. `onmounted`/`oncleanup`/`watcheffect`/... work exactly as inside a real `setup()`, since they resolve the same implicit current component context:\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 required<t>]: propdef<t[k & keyof t]>;\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; // scoped reactive effect; auto cleaned on disconnect\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 {\n mount(parent: parentnode, anchor: node | null, registercleanup: (fn: () => void) => void): node[];\n}\n\ntype cssresult = {\n content: string;\n tostring(): string;\n};\n\ntype livebinding<t> = { readonly source: readable<t> };\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",
|
|
963
|
-
"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\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). this replaces the `live()` + manual `@input` handler pair with one binding.\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## live: one way bindings that preserve user edits\n\nuse `live(signal)` when a binding must skip a stale app state write while the user is mid edit, without writing\nuser input back. `model()` covers the common controlled input case; `live()` is for one way bindings that only\nneed the stale write guard.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, live } from '@vielzeug/ore';\n\ndefine('live search', {\n setup() {\n const query = signal('');\n\n return html`\n <input value=${live(query)} @input=${(e: event) => (query.value = (e.target as htmlinputelement).value)} />\n `;\n },\n});\n```\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, when } 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 ${when(slots.has('footer'), () => html`<footer><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\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 two way form inputs; use `live(signal)` for a one way binding that must not clobber user in progress edits.\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",
|
|
962
|
+
"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.\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| `live(signal)` | one way binding that skips stale writes during input | sync | use for controlled inputs alongside a manual `@input` handler |\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\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 return html`${when(slots.has('header'), () => html`<slot name=\"header\"></slot>`)}`;\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:\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\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| `live(signal)` | one way binding that skips stale writes during active user input; use with `@input` handler |\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). this is the complete controlled input loop that the `live()` + manual `@input` handler pair used to require.\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\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)` | run lifecycle hooks in isolation; overload accepts `propdefs` as first arg 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. `onmounted`/`oncleanup`/`watcheffect`/... work exactly as inside a real `setup()`, since they resolve the same implicit current component context:\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 required<t>]: propdef<t[k & keyof t]>;\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; // scoped reactive effect; auto cleaned on disconnect\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 {\n mount(parent: parentnode, anchor: node | null, registercleanup: (fn: () => void) => void): node[];\n}\n\ntype cssresult = {\n content: string;\n tostring(): string;\n};\n\ntype livebinding<t> = { readonly source: readable<t> };\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",
|
|
963
|
+
"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). this replaces the `live()` + manual `@input` handler pair with one binding.\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## live: one way bindings that preserve user edits\n\nuse `live(signal)` when a binding must skip a stale app state write while the user is mid edit, without writing\nuser input back. `model()` covers the common controlled input case; `live()` is for one way bindings that only\nneed the stale write guard.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, live } from '@vielzeug/ore';\n\ndefine('live search', {\n setup() {\n const query = signal('');\n\n return html`\n <input value=${live(query)} @input=${(e: event) => (query.value = (e.target as htmlinputelement).value)} />\n `;\n },\n});\n```\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, when } 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 ${when(slots.has('footer'), () => html`<footer><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\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 two way form inputs; use `live(signal)` for a one way binding that must not clobber user in progress edits.\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",
|
|
964
964
|
"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"
|
|
965
965
|
},
|
|
966
966
|
"examples": [],
|
|
@@ -1305,7 +1305,7 @@
|
|
|
1305
1305
|
"description": "qr code generation and scanning: pure matrix encoder, svg and canvas renderers, native barcodedetector scanning",
|
|
1306
1306
|
"docs": {
|
|
1307
1307
|
"index": " \ntitle: 'sigil: qr code generation and scanning'\ndescription: 'qr code generation and scanning: pure matrix encoder, svg and canvas renderers, native barcodedetector scanning'\npackage: sigil\ncategory: utilities\nkeywords: [qr, qrcode, barcode, encoder, scanner, svg, canvas, barcodedetector, pairing]\nexports: [encodeqr, tosvg, createqrscanner, qrcapacity, detectqr]\nrelated: [mesh, refine]\nenvironments: [browser, node]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"sigil\" />\n\n## why sigil?\n\nqr workflows usually pull in a general purpose barcode library that renders to canvas and guesses at colors, or a from scratch decoder you do not need. sigil is a pure, zero dependency encoder (numeric, alphanumeric, and byte modes; versions 1–40; all four error correction levels; automatic mask selection) with renderers that stay out of the way: an svg string that themes with css, and a canvas painter for print/bitmap flows. scanning is a thin lifecycle wrapper over the platform's native `barcodedetector`, so there is no decoder weight and no polyfill to ship.\n\n```ts\n// before: a qr library per concern, canvas only output, hardcoded colors\nimport qrcode from 'qrcode';\nconst dataurl = await qrcode.todataurl(text, { width: 256, color: { dark: '#000' } });\nimg.src = dataurl; // raster, fixed colors, no theme support\n\n// after: encode once, render anywhere\nimport { encodeqr, tosvg } from '@vielzeug/sigil';\nconst matrix = encodeqr(text); // smallest version that fits, auto mask\nelement.innerhtml = tosvg(matrix); // currentcolor modules: themes with css\n```\n\n| feature | sigil | `qrcode` (node style) | `jsqr` |\n| | | | |\n| bundle size | <packageinfo package=\"sigil\" type=\"size\" /> | ~100 kb+ | decoder only |\n| runtime dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> none | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> none |\n| output | matrix, svg string, canvas | canvas/dataurl/utf 8 | n/a |\n| themeable output | `currentcolor` by default | hardcoded color strings | n/a |\n| scanning | native `barcodedetector` wrapper | <ore icon name=\"x\" size=\"16\"></ore icon> | pure js decoder |\n| ssr safe import | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> |\n\n<div class=\"decision callout\">\n\n**use sigil when** you need qr output that themes with your ui (svg/`currentcolor`), a minimal encoder with no runtime dependencies, or a scanner that uses the platform decoder instead of shipping one.\n\n**consider `jsqr` style decoding when** you must scan in browsers without `barcodedetector`: sigil reports `sigilunsupportederror` rather than bundling a fallback decoder.\n\n</div>\n\n## installation\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/sigil\n```\n\n```sh [npm]\nnpm install @vielzeug/sigil\n```\n\n```sh [yarn]\nyarn add @vielzeug/sigil\n```\n\n:::\n\n## quick start\n\nencode to an svg string: works in node and the browser:\n\n```ts\nimport { encodeqr, qrcapacity, tosvg } from '@vielzeug/sigil';\n\nconst payload = 'https://vielzeug.dev';\nconst matrix = encodeqr(payload, { errorcorrection: 'm' });\ndocument.queryselector('#qr').innerhtml = tosvg(matrix, { label: 'vielzeug link' });\n```\n\nscan with the camera (browser only: see support notes in the usage guide):\n\n```ts\nimport { createqrscanner } from '@vielzeug/sigil';\n\nconst video = document.queryselector('video');\nconst scanner = createqrscanner({ video });\nscanner.onresult((result) => {\n console.log('scanned:', result.value); // once: true stops after first decode\n});\nawait scanner.start(); // throws sigilunsupportederror / sigilpermissionerror\n```\n\n## features\n\n<div class=\"features grid\">\n\n `encodeqr`: pure matrix encoder: numeric/alphanumeric/byte modes, versions 1–40, ec levels l/m/q/h, automatic or forced mask\n `qrcapacity`: byte capacity per version/mode/level, for pre flight validation\n `tosvg`: compact path merged svg string; `currentcolor` modules, `<title>` + `role=\"img\"` built in\n `drawtocanvas`: bitmap rendering with dpr aware scaling for print and download flows\n `detectqr`: one shot detection on any `imagebitmapsource`\n `createqrscanner`: camera scan loop with `once` mode, status events, `tap()` observability, and strict disposal\n `isqrscansupported`/`qrscansupport`: sync and async feature detection that never assumes\n\n</div>\n\n## documentation\n\n<div class=\"doc links\">\n\n [usage guide](./usage.md): encoding modes, capacity, rendering, scanning, and testing\n [api reference](./api.md): every export, option, type, and error\n [examples](./examples.md): copy paste recipes, including pairing two devices with `meshqrcodec`\n\n</div>\n\n## see also\n\n<div class=\"see also\">\n\n [mesh](../mesh/): backendless p2p sessions; `meshqrcodec` produces compact qr friendly pairing payloads\n [refine](../refine/): `ore qr code` and `ore qr scanner` wrap sigil in ready made, themeable components\n\n</div>\n\n<! markdownlint enable >\n",
|
|
1308
|
-
"api": " \ntitle: 'sigil: api reference'\ndescription: 'public api of @vielzeug/sigil: encoder, renderers, scanner, types, and errors.'\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution | common gotcha |\n| | | | |\n| `encodeqr` | encode a payload into a `qrmatrix` | sync | throws `sigilcapacityerror` over capacity |\n| `qrcapacity` | payload limit for a version/level/mode | sync | returns _characters_ for numeric/alphanumeric, _bytes_ for byte mode |\n| `tosvg` | render a matrix as an svg string | sync | escapes `dark`/`light` as raw css: pass values, not markup |\n| `drawtocanvas` | paint a matrix onto a canvas | sync | browser only; resizes the canvas for dpr |\n| `detectqr` | one shot detection on an image source | async | throws `sigilunsupportederror` without `barcodedetector` |\n| `createqrscanner` | camera scan loop | async (start) | must `dispose()`; camera tracks persist otherwise |\n| `isqrscansupported` | sync feature check | sync | constructor exists ≠ `qr_code` supported: prefer `qrscansupport()` |\n| `qrscansupport` | async feature check incl. formats | async | never assume support per browser/version |\n\n## package entry point\n\n| import | purpose |\n| | |\n| `@vielzeug/sigil` | complete public sigil api |\n\n## encoding\n\n### `encodeqr(data, options?)`\n\n```ts\nfunction encodeqr(data: string | uint8array, options?: qrencodeoptions): qrmatrix;\n```\n\nencodes `data` into a qr symbol. picks the most compact mode covering the whole input, the smallest fitting version, and the lowest penalty mask.\n\n| parameter | type | default | description |\n| | | | |\n| `data` | `string \\| uint8array` | n/a | payload; `uint8array` is raw binary and always byte mode (no utf 8 round trip) |\n| `options.errorcorrection` | `'l' \\| 'm' \\| 'q' \\| 'h'` | `'m'` | error correction level |\n| `options.version` | `1–40` | auto | pin the version; throws if payload can't fit |\n| `options.minversion` | `1–40` | `1` | smallest acceptable version |\n| `options.mode` | `qrmode` | auto | force a segment mode |\n| `options.mask` | `0–7` | auto | force the mask (test vectors only) |\n\n**returns** a frozen `qrmatrix` with `size`, `version`, `mode`, `errorcorrection`, `mask`, and `get(x, y)`.\n\n**throws** `sigilcapacityerror` (payload exceeds capacity), `sigiloptionerror` (invalid mode/version/mask combination).\n\n```ts\nimport { encodeqr } from '@vielzeug/sigil';\n\nconst matrix = encodeqr('hello world', { errorcorrection: 'q' });\nmatrix.size; // 21 (v1)\nmatrix.get(0, 0); // finder pattern → true\n```\n\n \n\n### `qrcapacity(version, errorcorrection, mode)`\n\n```ts\nfunction qrcapacity(version: number, errorcorrection: qrerrorcorrection, mode: qrmode): number;\n```\n\nreturns the payload limit: characters for `numeric`/`alphanumeric`, bytes for `byte`.\n\n```ts\nqrcapacity(1, 'm', 'byte'); // → 14\nqrcapacity(40, 'l', 'numeric'); // → 7089\n```\n\n## rendering\n\n### `tosvg(matrix, options?)`\n\n```ts\nfunction tosvg(matrix: qrmatrix, options?: qrsvgoptions): string;\n```\n\nreturns a complete `<svg>` string. runs in any environment: no dom required.\n\n| parameter | type | default | description |\n| | | | |\n| `options.dark` | `string` | `'currentcolor'` | dark module color |\n| `options.light` | `string` | `'transparent'` | background color |\n| `options.margin` | `number` | `4` | quiet zone modules |\n| `options.scale` | `number` | `1` | user units per module |\n| `options.optimizepath` | `boolean` | `true` | merge dark runs into one `<path>` |\n| `options.label` | `string` | n/a | `<title>` + `aria label`; enables `role=\"img\"` |\n\n```ts\nconst svg = tosvg(matrix, { label: 'pairing code', dark: 'var( qr dark)' });\n```\n\n \n\n### `drawtocanvas(matrix, canvas, options?)`: browser only\n\n```ts\nfunction drawtocanvas(matrix: qrmatrix, canvas: htmlcanvaselement, options?: qrcanvasoptions): number;\n```\n\npaints the matrix and returns the css pixel edge length. sizes the backing store for `devicepixelratio` so output stays crisp on retina displays.\n\n| parameter | type | default | description |\n| | | | |\n| `options.scale` | `number` | `1` | css px per module |\n| `options.margin` | `number` | `4` | quiet zone modules |\n| `options.dark` / `options.light` | `string` | `'#000'` / `'#fff'` | fill colors |\n\n## scanning (browser only)\n\n### `createqrscanner(options)`\n\n```ts\nfunction createqrscanner(options: qrscanneroptions): qrscanner;\n```\n\ncreates a camera scan loop around the native `barcodedetector`.\n\n| parameter | type | default | description |\n| | | | |\n| `options.video` | `htmlvideoelement` | n/a | element the stream attaches to (needs `autoplay playsinline muted`) |\n| `options.constraints` | `mediatrackconstraints` | `{ facingmode: 'environment' }` | `getusermedia` video constraints |\n| `options.intervalms` | `number` | `200` | minimum ms between detect passes |\n| `options.once` | `boolean` | `true` | stop after the first result |\n| `options.signal` | `abortsignal` | n/a | abort → `stop()` |\n| `options.detector` | `qrdetector` | native | injected detector for tests |\n| `options.mediadevices` | `pick<mediadevices, 'getusermedia'>` | `navigator.mediadevices` | injected media for tests |\n\n**returns** a `qrscanner`:\n\n| member | signature | description |\n| | | |\n| `start()` | `() => promise<void>` | request camera, attach stream, run the detect loop. rejects with `sigilunsupportederror` / `sigilpermissionerror`. `stop()`/`dispose()` while the camera prompt is pending win: the late stream is released and the call resolves |\n| `stop()` | `() => void` | stop the loop and tracks, return to `'idle'`; instance stays usable |\n| `onresult(handler)` | `(handler) => () => void` | decode results; returns unsubscribe |\n| `tap(handler, options?)` | `(handler, { signal? }) => () => void` | observe `sigilevent`s; handler errors are swallowed |\n| `status` | `qrscannerstatus` | `'idle' \\| 'starting' \\| 'scanning' \\| 'disposed'` |\n| `dispose()` / `[symbol.dispose]` | `() => void` | terminal teardown; `disposalsignal` aborts |\n| `disposed` | `boolean` | whether `dispose()` ran |\n\n```ts\nconst scanner = createqrscanner({ video });\nconst off = scanner.onresult(({ value }) => console.log(value));\nawait scanner.start();\n```\n\n \n\n### `detectqr(source, options?)`\n\n```ts\nfunction detectqr(\n source: imagebitmapsource,\n options?: { signal?: abortsignal; detector?: qrdetector },\n): promise<qrscanresult | null>;\n```\n\nsingle pass detection on an image source. returns the first result's `{ value, cornerpoints }`, or `null` when nothing decodes. throws `sigilunsupportederror` when no detector is available.\n\n \n\n### `isqrscansupported()` / `qrscansupport()`\n\n```ts\nfunction isqrscansupported(): boolean;\nfunction qrscansupport(): promise<boolean>;\n```\n\n`isqrscansupported` checks the `barcodedetector` constructor synchronously. `qrscansupport` additionally asks `getsupportedformats()` for `'qr_code'`: use it before showing scan affordances.\n\n## types\n\n```ts\ntype qrerrorcorrection = 'l' | 'm' | 'q' | 'h';\ntype qrmode = 'numeric' | 'alphanumeric' | 'byte';\ntype qrscannerstatus = 'idle' | 'starting' | 'scanning' | 'disposed';\n\ninterface qrmatrix {\n readonly errorcorrection: qrerrorcorrection;\n readonly mask: number;\n readonly mode: qrmode;\n readonly size: number; // 17 + 4 * version\n readonly version: number; // 1–40\n get(x: number, y: number): boolean; // true = dark; false outside bounds\n}\n\ninterface qrscanresult {\n readonly cornerpoints?: readonlyarray<{ readonly x: number; readonly y: number }>;\n readonly value: string;\n}\n\ninterface qrdetector {\n detect(\n source: imagebitmapsource,\n ): promise<readonlyarray<{ rawvalue: string; cornerpoints?: readonlyarray<{ x: number; y: number }> }>>;\n}\n\ntype sigilevent =\n | { readonly type: 'status change'; readonly status: qrscannerstatus }\n | { readonly type: 'detect'; readonly value: string; readonly elapsedms: number }\n | { readonly type: 'frame skipped'; readonly reason: 'not ready' | 'busy' }\n | { readonly type: 'error'; readonly error: sigilerror }\n | { readonly type: 'dispose' };\n```\n\n`qrencodeoptions`, `qrsvgoptions`, `qrcanvasoptions`, `qrscanneroptions`, and `qrscanner` are documented under their factories above.\n\n## errors\n\n| class | trigger | notable members |\n| | | |\n| `sigilerror` | base class for all sigil errors | n/a |\n| `sigilcapacityerror` | payload exceeds the version/mode limit | `bytes`, `maxbytes`, `version` |\n| `sigiloptionerror` | invalid option combination (forced mode can't represent input, bad mask/version) | n/a |\n| `sigilunsupportederror` | `barcodedetector`/`getusermedia`/canvas 2d context missing | n/a |\n| `sigilpermissionerror` | camera `notallowederror` | n/a |\n| `sigildisposederror` | `start()` on a disposed scanner | n/a |\n\nall carry `cause` when wrapping a platform error.\n",
|
|
1308
|
+
"api": " \ntitle: 'sigil: api reference'\ndescription: 'public api of @vielzeug/sigil: encoder, renderers, scanner, types, and errors.'\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution | common gotcha |\n| | | | |\n| `encodeqr` | encode a payload into a `qrmatrix` | sync | throws `sigilcapacityerror` over capacity |\n| `qrcapacity` | payload limit for a version/level/mode | sync | returns _characters_ for numeric/alphanumeric, _bytes_ for byte mode |\n| `tosvg` | render a matrix as an svg string | sync | escapes `dark`/`light` as raw css: pass values, not markup |\n| `drawtocanvas` | paint a matrix onto a canvas | sync | browser only; resizes the canvas for dpr |\n| `detectqr` | one shot detection on an image source | async | throws `sigilunsupportederror` without `barcodedetector` |\n| `createqrscanner` | camera scan loop | async (start) | must `dispose()`; camera tracks persist otherwise |\n| `isqrscansupported` | sync feature check | sync | constructor exists ≠ `qr_code` supported: prefer `qrscansupport()` |\n| `qrscansupport` | async feature check incl. formats | async | never assume support per browser/version |\n\n## package entry point\n\n| import | purpose |\n| | |\n| `@vielzeug/sigil` | complete public sigil api |\n\n## encoding\n\n### `encodeqr(data, options?)`\n\n```ts\nfunction encodeqr(data: string | uint8array, options?: qrencodeoptions): qrmatrix;\n```\n\nencodes `data` into a qr symbol. picks the most compact mode covering the whole input, the smallest fitting version, and the lowest penalty mask.\n\n| parameter | type | default | description |\n| | | | |\n| `data` | `string \\| uint8array` | n/a | payload; `uint8array` is raw binary and always byte mode (no utf 8 round trip) |\n| `options.errorcorrection` | `'l' \\| 'm' \\| 'q' \\| 'h'` | `'m'` | error correction level |\n| `options.version` | `1–40` | auto | pin the version; throws if payload can't fit |\n| `options.minversion` | `1–40` | `1` | smallest acceptable version |\n| `options.mode` | `qrmode` | auto | force a segment mode |\n| `options.mask` | `0–7` | auto | force the mask (test vectors only) |\n\n**returns** a frozen `qrmatrix` with `size`, `version`, `mode`, `errorcorrection`, `mask`, and `get(x, y)`.\n\n**throws** `sigilcapacityerror` (payload exceeds capacity), `sigiloptionerror` (invalid mode/version/mask combination).\n\n```ts\nimport { encodeqr } from '@vielzeug/sigil';\n\nconst matrix = encodeqr('hello world', { errorcorrection: 'q' });\nmatrix.size; // 21 (v1)\nmatrix.get(0, 0); // finder pattern → true\n```\n\n \n\n### `qrcapacity(version, errorcorrection, mode)`\n\n```ts\nfunction qrcapacity(version: number, errorcorrection: qrerrorcorrection, mode: qrmode): number;\n```\n\nreturns the payload limit: characters for `numeric`/`alphanumeric`, bytes for `byte`.\n\n```ts\nqrcapacity(1, 'm', 'byte'); // → 14\nqrcapacity(40, 'l', 'numeric'); // → 7089\n```\n\n## rendering\n\n### `tosvg(matrix, options?)`\n\n```ts\nfunction tosvg(matrix: qrmatrix, options?: qrsvgoptions): string;\n```\n\nreturns a complete `<svg>` string. runs in any environment: no dom required.\n\n| parameter | type | default | description |\n| | | | |\n| `options.dark` | `string` | `'currentcolor'` | dark module color (ignored when `gradient` is set) |\n| `options.light` | `string` | `'transparent'` | background color |\n| `options.margin` | `number` | `4` | quiet zone modules |\n| `options.scale` | `number` | `1` | user units per module |\n| `options.optimizepath` | `boolean` | `true` | merge dark runs into one `<path>` |\n| `options.label` | `string` | n/a | `<title>` + `aria label`; enables `role=\"img\"` |\n| `options.dotstyle` | `qrdotstyle` | `'square'` | data module shape; finder zones stay square |\n| `options.gradient` | `qrsvggradientoptions` | n/a | two stop linear gradient replacing module paint |\n| `options.image` | `qrsvgimageoptions` | n/a | centered logo; modules under it are not painted |\n\n```ts\ntype qrdotstyle = 'dots' | 'rounded' | 'square';\n\ntype qrsvggradientoptions = {\n from: string; // first stop\n to: string; // second stop\n angle?: number; // degrees, 0 = top to bottom (default)\n id?: string; // stable <defs> id; auto unique otherwise\n};\n\ntype qrsvgimageoptions = {\n href: string; // logo url (resolved by the consumer, embedded verbatim)\n size?: number; // fraction of the code edge (default 0.22)\n spacing?: number; // clear gap in modules around the logo (default 1)\n background?: string; // optional patch behind the logo\n radius?: number; // corner radius of the background patch\n};\n```\n\nstyling output stays scanner friendly: finder patterns never lose their square shape, and the carve around a logo is a gap, not painted noise. prefer `errorcorrection: 'h'` when overlaying a logo.\n\n```ts\nconst svg = tosvg(matrix, { label: 'pairing code', dark: 'var( qr dark)' });\nconst styled = tosvg(matrix, { dotstyle: 'rounded', gradient: { from: '#0ea5e9', to: '#7c3aed' } });\n```\n\n \n\n### `drawtocanvas(matrix, canvas, options?)`: browser only\n\n```ts\nfunction drawtocanvas(matrix: qrmatrix, canvas: htmlcanvaselement, options?: qrcanvasoptions): number;\n```\n\npaints the matrix and returns the css pixel edge length. sizes the backing store for `devicepixelratio` so output stays crisp on retina displays.\n\n| parameter | type | default | description |\n| | | | |\n| `options.scale` | `number` | `1` | css px per module |\n| `options.margin` | `number` | `4` | quiet zone modules |\n| `options.dark` / `options.light` | `string` | `'#000'` / `'#fff'` | fill colors |\n\n## scanning (browser only)\n\n### `createqrscanner(options)`\n\n```ts\nfunction createqrscanner(options: qrscanneroptions): qrscanner;\n```\n\ncreates a camera scan loop around the native `barcodedetector`.\n\n| parameter | type | default | description |\n| | | | |\n| `options.video` | `htmlvideoelement` | n/a | element the stream attaches to (needs `autoplay playsinline muted`) |\n| `options.constraints` | `mediatrackconstraints` | `{ facingmode: 'environment' }` | `getusermedia` video constraints |\n| `options.intervalms` | `number` | `200` | minimum ms between detect passes |\n| `options.once` | `boolean` | `true` | stop after the first result |\n| `options.signal` | `abortsignal` | n/a | abort → `stop()` |\n| `options.detector` | `qrdetector` | native | injected detector for tests |\n| `options.mediadevices` | `pick<mediadevices, 'getusermedia'>` | `navigator.mediadevices` | injected media for tests |\n\n**returns** a `qrscanner`:\n\n| member | signature | description |\n| | | |\n| `start()` | `() => promise<void>` | request camera, attach stream, run the detect loop. rejects with `sigilunsupportederror` / `sigilpermissionerror`. `stop()`/`dispose()` while the camera prompt is pending win: the late stream is released and the call resolves |\n| `stop()` | `() => void` | stop the loop and tracks, return to `'idle'`; instance stays usable |\n| `onresult(handler)` | `(handler) => () => void` | decode results; returns unsubscribe |\n| `tap(handler, options?)` | `(handler, { signal? }) => () => void` | observe `sigilevent`s; handler errors are swallowed |\n| `status` | `qrscannerstatus` | `'idle' \\| 'starting' \\| 'scanning' \\| 'disposed'` |\n| `dispose()` / `[symbol.dispose]` | `() => void` | terminal teardown; `disposalsignal` aborts |\n| `disposed` | `boolean` | whether `dispose()` ran |\n\n```ts\nconst scanner = createqrscanner({ video });\nconst off = scanner.onresult(({ value }) => console.log(value));\nawait scanner.start();\n```\n\n \n\n### `detectqr(source, options?)`\n\n```ts\nfunction detectqr(\n source: imagebitmapsource,\n options?: { signal?: abortsignal; detector?: qrdetector },\n): promise<qrscanresult | null>;\n```\n\nsingle pass detection on an image source. returns the first result's `{ value, cornerpoints }`, or `null` when nothing decodes. throws `sigilunsupportederror` when no detector is available.\n\n \n\n### `isqrscansupported()` / `qrscansupport()`\n\n```ts\nfunction isqrscansupported(): boolean;\nfunction qrscansupport(): promise<boolean>;\n```\n\n`isqrscansupported` checks the `barcodedetector` constructor synchronously. `qrscansupport` additionally asks `getsupportedformats()` for `'qr_code'`: use it before showing scan affordances.\n\n## types\n\n```ts\ntype qrerrorcorrection = 'l' | 'm' | 'q' | 'h';\ntype qrmode = 'numeric' | 'alphanumeric' | 'byte';\ntype qrscannerstatus = 'idle' | 'starting' | 'scanning' | 'disposed';\n\ninterface qrmatrix {\n readonly errorcorrection: qrerrorcorrection;\n readonly mask: number;\n readonly mode: qrmode;\n readonly size: number; // 17 + 4 * version\n readonly version: number; // 1–40\n get(x: number, y: number): boolean; // true = dark; false outside bounds\n}\n\ninterface qrscanresult {\n readonly cornerpoints?: readonlyarray<{ readonly x: number; readonly y: number }>;\n readonly value: string;\n}\n\ninterface qrdetector {\n detect(\n source: imagebitmapsource,\n ): promise<readonlyarray<{ rawvalue: string; cornerpoints?: readonlyarray<{ x: number; y: number }> }>>;\n}\n\ntype sigilevent =\n | { readonly type: 'status change'; readonly status: qrscannerstatus }\n | { readonly type: 'detect'; readonly value: string; readonly elapsedms: number }\n | { readonly type: 'frame skipped'; readonly reason: 'not ready' | 'busy' }\n | { readonly type: 'error'; readonly error: sigilerror }\n | { readonly type: 'dispose' };\n```\n\n`qrencodeoptions`, `qrsvgoptions`, `qrcanvasoptions`, `qrscanneroptions`, and `qrscanner` are documented under their factories above. `qrdotstyle`, `qrsvggradientoptions`, and `qrsvgimageoptions` are documented under `tosvg`.\n\n## errors\n\n| class | trigger | notable members |\n| | | |\n| `sigilerror` | base class for all sigil errors | n/a |\n| `sigilcapacityerror` | payload exceeds the version/mode limit | `bytes`, `maxbytes`, `version` |\n| `sigiloptionerror` | invalid option combination (forced mode can't represent input, bad mask/version) | n/a |\n| `sigilunsupportederror` | `barcodedetector`/`getusermedia`/canvas 2d context missing | n/a |\n| `sigilpermissionerror` | camera `notallowederror` | n/a |\n| `sigildisposederror` | `start()` on a disposed scanner | n/a |\n\nall carry `cause` when wrapping a platform error.\n",
|
|
1309
1309
|
"usage": " \ntitle: 'sigil: usage guide'\ndescription: encoding modes, capacity checks, svg/canvas rendering, camera scanning, and testing for @vielzeug/sigil.\n \n\n[[toc]]\n\n## basic usage\n\n`encodeqr` produces a `qrmatrix`: a frozen square of dark/light modules. render it with `tosvg` (string, works anywhere) or `drawtocanvas` (browser).\n\n```ts\nimport { encodeqr, qrcapacity, tosvg } from '@vielzeug/sigil';\n\nconst matrix = encodeqr('https://vielzeug.dev');\n// pick the smallest version automatically, or pin one:\nconst pinned = encodeqr('https://vielzeug.dev', { version: 5, errorcorrection: 'q' });\n\nconst svg = tosvg(matrix); // inline <svg> string: inject or serialize\n```\n\nthe encoder chooses the most compact mode for the whole input and the smallest version that fits. `mask` is chosen by the lowest iso penalty score: override it only for test vectors.\n\n## encoding modes and capacity\n\nthree segment modes cover every payload:\n\n| mode | alphabet | max payload (v40 l) |\n| | | |\n| `numeric` | `0–9` | 7,089 digits |\n| `alphanumeric` | `0–9 a z space $%*+ ./:` | 4,296 chars |\n| `byte` | utf 8 (no eci header) | 2,953 bytes |\n\nmode selection is automatic: `encodeqr('01234567')` uses `numeric`, `'hello world'` uses `alphanumeric`, anything else uses `byte`. force a mode with `mode`, but a forced mode that cannot represent the input throws `sigiloptionerror`.\n\n`uint8array` input is raw binary: it always encodes in byte mode, byte for byte, with no utf 8 round trip: invalid utf 8 (tokens, provisioning payloads) survives intact. forcing a non byte mode with binary input throws `sigiloptionerror`.\n\ncheck capacity before encoding with `qrcapacity(version, errorcorrection, mode)`: it returns the maximum _bytes_ (for `byte` mode) or _characters_ the symbol holds:\n\n```ts\nimport { qrcapacity, sigilcapacityerror } from '@vielzeug/sigil';\n\nqrcapacity(10, 'm', 'byte'); // → 213 (data codewords available at v10 m)\n\ntry {\n encodeqr(hugepayload, { version: 1 });\n} catch (error) {\n if (error instanceof sigilcapacityerror) {\n console.log(`${error.bytes} > ${error.maxbytes} at v${error.version}`);\n }\n}\n```\n\nuse `minversion` to keep a stable symbol size while a payload changes: useful when a layout must not reflow between renders.\n\n## error correction\n\n| level | recovery | trade off |\n| | | |\n| `l` | ~7% | smallest matrix |\n| `m` | ~15% | default: good balance |\n| `q` | ~25% | print, wear |\n| `h` | ~30% | logos/overlays, dense codes |\n\nhigher levels shrink capacity at the same version. for an overlaid logo, prefer `h` _and_ keep the logo inside the quiet zone's margin of safety.\n\n## rendering\n\n### svg: `tosvg`\n\n```ts\nconst svg = tosvg(matrix, {\n dark: 'currentcolor', // default: inherits text color\n light: 'transparent', // default\n margin: 4, // quiet zone in modules (spec minimum is 4)\n scale: 1, // user units per module: prefer scaling via css\n optimizepath: true, // merge adjacent modules into one path (default)\n label: 'pairing code', // <title> + role=\"img\"\n});\n```\n\n`optimizepath` merges each row's dark runs into a single `<path>`: orders of magnitude smaller markup. set `dark`/`light` to css variables to theme the code (`dark: 'var( qr dark)'`).\n\n### canvas: `drawtocanvas` (browser only)\n\n```ts\nconst sizepx = drawtocanvas(matrix, canvas, { scale: 8, margin: 4 });\n// canvas is resized for devicepixelratio; returns the css pixel edge length\n```\n\nuse canvas for print, download (`canvas.toblob`), or compositing. svg is the better default for display.\n\n## scanning (browser only)\n\nscanning wraps the native `barcodedetector`. it is **not** universally available: feature detect, never assume:\n\n| engine | `barcodedetector` | notes |\n| | | |\n| chrome / edge / android webview | yes | `qr_code` format supported |\n| firefox | no (behind flag in some builds) | `isqrscansupported()` → `false` |\n| safari | varies by version | check at runtime; do not rely on version sniffing |\n\n```ts\nimport { createqrscanner, isqrscansupported, qrscansupport } from '@vielzeug/sigil';\n\nisqrscansupported(); // sync: barcodedetector constructor exists\nawait qrscansupport(); // async: also verifies 'qr_code' is a supported format\n\nconst scanner = createqrscanner({\n video, // <video autoplay playsinline muted>\n constraints: { facingmode: 'environment' },\n intervalms: 200, // min ms between detect passes\n once: true, // stop after first result\n});\n\nscanner.onresult((result) => showpairing(result.value));\nscanner.tap((event) => console.debug(event.type)); // status change, detect, frame skipped…\n\nawait scanner.start(); // requests camera, attaches stream, starts the loop\nscanner.stop(); // releases the camera, back to 'idle'; start() resumes\nscanner.dispose(); // terminal: releases everything\n```\n\nstatuses are `'idle' | 'starting' | 'scanning' | 'disposed'`. a `stop()` or `dispose()` that lands while the camera permission prompt is pending wins the race: the late stream is released and `start()` resolves without restarting the loop.\n\n`start()` rejects with `sigilunsupportederror` (no detector/getusermedia) or `sigilpermissionerror` (`notallowederror`). detection failures mid scan surface through `tap` `error` events and stop the scanner.\n\n### one shot detection\n\n`detectqr(source)` runs a single pass over any `imagebitmapsource`: `imagedata`, `blob`, `videoframe`, an `<img>`, or a `<canvas>`:\n\n```ts\nimport { detectqr } from '@vielzeug/sigil';\n\nconst result = await detectqr(imagebitmap); // → { value, cornerpoints } | null\n```\n\n## testing\n\nboth seams are injectable: never touch globals in tests:\n\n```ts\nimport { createqrscanner } from '@vielzeug/sigil';\n\nconst fakescanner = createqrscanner({\n video: document.createelement('video'),\n detector: { detect: async () => [{ rawvalue: 'payload' }] }, // fake barcodedetector\n mediadevices: { getusermedia: async () => fakestream }, // fake camera\n});\n```\n\nfor the web components, `ore qr scanner` exposes a `scannerfactory` js property so tests inject a fake `qrscanner` without stubbing `barcodedetector` or `getusermedia`.\n\n## framework integration\n\nencoding is synchronous and ssr safe: render `tosvg` output as part of server markup:\n\n::: code group\n\n```tsx [react]\nfunction qr({ value }: { value: string }) {\n const svg = usememo(() => tosvg(encodeqr(value)), [value]);\n return <span dangerouslysetinnerhtml={{ __html: svg }} />;\n}\n```\n\n```vue [vue]\n<script setup>\nimport { computed } from 'vue';\nimport { encodeqr, tosvg } from '@vielzeug/sigil';\nconst props = defineprops({ value: string });\nconst svg = computed(() => tosvg(encodeqr(props.value ?? '')));\n</script>\n<template><span v html=\"svg\" /></template>\n```\n\n```html [svelte]\n<script>\n import { encodeqr, tosvg } from '@vielzeug/sigil';\n export let value;\n $: svg = tosvg(encodeqr(value));\n</script>\n<span>{@html svg}</span>\n```\n\n:::\n\nscanning needs lifecycle: start in `onmounted`/`onmount`, always `dispose()` in cleanup.\n\n## working with other vielzeug libraries\n\n **mesh**: `meshqrcodec` compresses webrtc pairing payloads (offer/answer json) to qr friendly strings. the [pair two devices with qr](./examples/pair two devices.md) recipe shows the full flow.\n **refine**: prefer `ore qr code` / `ore qr scanner` over hand rolled wrappers: they compose sigil with themeable markup, a11y labels, and state handling.\n\n## best practices\n\n pre validate payloads with `qrcapacity` before surfacing an encode control.\n keep the quiet zone: `margin` below 4 risks unreadable codes; never overlay content on it.\n prefer `tosvg` + `currentcolor` for display; reserve `drawtocanvas` for print/download.\n feature detect scanning with `qrscansupport()` before showing a scan affordance.\n always `dispose()` scanners: camera tracks outlive route changes otherwise.\n use `once: false` only when the ux genuinely expects repeated decodes.\n treat scanned strings as untrusted input: validate before navigation or pairing.\n pin `minversion` in animated/live payloads so the symbol doesn't resize mid flow.\n",
|
|
1310
1310
|
"examples": " \ntitle: 'sigil: examples'\ndescription: practical examples and recipes for @vielzeug/sigil.\n \n\n## examples\n\n [themed svg qr code](./examples/themed svg qr code.md)\n [pair two devices with qr](./examples/pair two devices.md)\n"
|
|
1311
1311
|
},
|
|
@@ -1324,7 +1324,7 @@
|
|
|
1324
1324
|
"name": "@vielzeug/sigil",
|
|
1325
1325
|
"related": "mesh refine",
|
|
1326
1326
|
"slug": "sigil",
|
|
1327
|
-
"source": "// public root surface of @vielzeug/sigil. every public export goes through this file.\nexport { drawtocanvas } from './canvas';\nexport { encodeqr, qrcapacity } from './encode';\nexport {\n sigilcapacityerror,\n sigildisposederror,\n sigilerror,\n sigiloptionerror,\n sigilpermissionerror,\n sigilunsupportederror,\n} from './errors';\nexport { createqrscanner, detectqr, isqrscansupported, qrscansupport } from './scan';\nexport { tosvg } from './svg';\nexport type {\n qrcanvasoptions,\n qrdetector,\n qrencodeoptions,\n qrerrorcorrection,\n qrmatrix,\n qrmode,\n qrscanner,\n qrscanneroptions,\n qrscannerstatus,\n qrscanresult,\n qrsvgoptions,\n sigilevent,\n} from './types';\n"
|
|
1327
|
+
"source": "// public root surface of @vielzeug/sigil. every public export goes through this file.\nexport { drawtocanvas } from './canvas';\nexport { encodeqr, qrcapacity } from './encode';\nexport {\n sigilcapacityerror,\n sigildisposederror,\n sigilerror,\n sigiloptionerror,\n sigilpermissionerror,\n sigilunsupportederror,\n} from './errors';\nexport { createqrscanner, detectqr, isqrscansupported, qrscansupport } from './scan';\nexport { tosvg } from './svg';\nexport type {\n qrcanvasoptions,\n qrdetector,\n qrdotstyle,\n qrencodeoptions,\n qrerrorcorrection,\n qrmatrix,\n qrmode,\n qrscanner,\n qrscanneroptions,\n qrscannerstatus,\n qrscanresult,\n qrsvggradientoptions,\n qrsvgimageoptions,\n qrsvgoptions,\n sigilevent,\n} from './types';\n"
|
|
1328
1328
|
},
|
|
1329
1329
|
{
|
|
1330
1330
|
"category": "data",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vielzeug/codex",
|
|
3
|
-
"version": "26.11.
|
|
3
|
+
"version": "26.11.9",
|
|
4
4
|
"description": "MCP server exposing all Vielzeug docs to AI clients",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
65
65
|
"@types/node": "^26.6.6",
|
|
66
|
-
"@vielzeug/refine": "26.11.
|
|
66
|
+
"@vielzeug/refine": "26.11.9",
|
|
67
67
|
"typescript": "^6.0.3",
|
|
68
68
|
"vitest": "^5.1.0"
|
|
69
69
|
}
|