@vielzeug/codex 26.11.16 → 26.11.18

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.
@@ -6,7 +6,18 @@
6
6
  "usage": "---\ntitle: 'Prism: Usage Guide'\ndescription: Create responsive SVG charts, update their data, handle interaction, and theme @vielzeug/prism.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate a host element with non-zero dimensions, then pass it to a chart factory. This example creates the host in JavaScript so the snippet can run as written.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\nimport '@vielzeug/prism/theme.css';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createLineChart(container, {\n a11y: { ariaLabel: 'Revenue by month' },\n series: [\n {\n name: 'Revenue',\n data: [\n { key: 1, value: 10 },\n { key: 2, value: 16 },\n ],\n },\n ],\n tooltip: true,\n});\n\nchart.dispose();\n```\n\nEach factory appends an SVG to its container and returns a `ChartHandle`. Prism observes the container with `ResizeObserver`; if it has zero dimensions on creation, Prism uses a temporary `600 × 300` size and warns in development. Give the host its layout before creating the chart.\n\n## Updating Data\n\nKeep application state outside Prism and pass the next complete data value to `update()`. The update method replaces chart data synchronously; the default transition may animate the resulting SVG.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nlet series = [{ data: [{ key: 1, value: 10 }], name: 'Live' }];\nconst chart = createLineChart(container, { series });\n\nseries = [\n {\n data: [\n { key: 1, value: 10 },\n { key: 2, value: 20 },\n ],\n name: 'Live',\n },\n];\nchart.update(series);\nchart.dispose();\n```\n\n`update()` accepts the type shown by that factory's handle: a complete series array for line, area, scatter, bar, and radar charts; a slice array for pie charts; a `HeatmapData` object for heatmap charts; and a number or stack-segment array for sparklines. Chart options such as axes, variant, callbacks, and accessibility are set at creation. For example, radar axes and a pie chart's variant do not change through `update()`.\n\n## Line Charts\n\nLine and area series use number or `Date` keys. All series in one chart must use the same key kind. Use `curve` to choose interpolation, and enable markers with `showPoints`.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createLineChart(container, {\n a11y: { ariaLabel: 'Revenue and expenses' },\n series: [\n {\n curve: 'monotone',\n data: [\n { key: 1, value: 100 },\n { key: 2, value: 150 },\n { key: 3, value: 130 },\n ],\n name: 'Revenue',\n showPoints: true,\n },\n {\n color: '#c2410c',\n data: [\n { key: 1, value: 70 },\n { key: 2, value: 95 },\n { key: 3, value: 110 },\n ],\n name: 'Expenses',\n },\n ],\n tooltip: true,\n xAxis: { label: 'Month' },\n yAxis: { grid: true, label: 'Dollars' },\n});\n\nchart.dispose();\n```\n\n### Independent Value Axes\n\nAssign a line series to the right axis when it uses a different value range. Both axes share the x-scale; `rightYAxis` configures the second axis and cannot configure its position or grid.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createLineChart(container, {\n a11y: { ariaLabel: 'Health and damage by level' },\n rightYAxis: { label: 'Damage' },\n series: [\n {\n data: [\n { key: 1, value: 30 },\n { key: 2, value: 20 },\n ],\n name: 'Health',\n },\n {\n data: [\n { key: 1, value: 100 },\n { key: 2, value: 300 },\n ],\n name: 'Damage',\n yAxis: 'right',\n },\n ],\n yAxis: { grid: true, label: 'Health' },\n});\n\nchart.dispose();\n```\n\nWhen any series uses the right axis, the primary value axis is placed on the left. Grid lines belong to the primary `yAxis`. The independent numeric scales mean that curve crossings do not imply equal values.\n\n### Time-Based X Axis\n\nUse `Date` values for every key when plotting time. Line and area charts use a time scale whose domain fits the data instead of rounding outward to tick boundaries.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });\nconst chart = createLineChart(container, {\n a11y: { ariaLabel: 'Signups over time' },\n series: [\n {\n data: [\n { key: new Date('2026-09-01'), value: 50 },\n { key: new Date('2026-09-08'), value: 80 },\n { key: new Date('2026-09-15'), value: 120 },\n ],\n name: 'Signups',\n },\n ],\n xAxis: { tickFormat: (value) => (value instanceof Date ? formatter.format(value) : String(value)) },\n});\n\nchart.dispose();\n```\n\n`tickFormat` formats axis labels only. Tooltip content and accessibility announcements use the underlying keys and values. To render an exact set of ticks instead of scale-generated ones, pass `tickValues`; gridlines follow the same list. Values must match the axis's scale kind, and an off-scale value warns in development:\n\n```ts\n// Force a tick on the last month, which nice-stepped ticks can skip.\nconst chart = createLineChart(container, {\n series: [\n {\n data: [\n { key: 0, value: 90 },\n { key: 11, value: 128 },\n ],\n name: 'Costs',\n },\n ],\n xAxis: { tickValues: [0, 6, 11] },\n});\n```\n\nNumeric tick labels at a magnitude of `1e5` or above default to compact notation (`123K`, `1.23M`) so long numbers fit the default value-axis margin; pass `tickFormat: String` for raw labels. Supplying a partial value-axis config merges over its default, so `yAxis: { tickFormat }` alone keeps the default grid lines.\n\n## Bar Charts\n\nBar chart keys are string categories. The default `grouped` variant puts series side by side; the horizontal variants put categories on the y-axis and values on the x-axis.\n\n```ts\nimport { createBarChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createBarChart(container, {\n a11y: { ariaLabel: 'Sales by quarter' },\n series: [\n {\n data: [\n { key: 'Q1', value: 200 },\n { key: 'Q2', value: 350 },\n { key: 'Q3', value: 280 },\n ],\n name: 'Sales',\n },\n ],\n tooltip: true,\n});\n\nchart.dispose();\n```\n\nChoose `grouped`, `stacked`, `grouped-horizontal`, or `stacked-horizontal` in `variant`. Negative values in a stacked chart are clamped to zero and produce a development warning. Bars in stacked variants remain square; `borderRadius` applies to grouped bars.\n\nAxes render by default, with grid lines on the value axis. For horizontal variants, `xAxis` is the value axis and `yAxis` is the category axis. Configure `grid` on the value axis.\n\nSet `showValues: true` to paint each bar's value at its end so the chart reads without hover; `valueFormat` shapes the label text. Stacked variants label the stack total at the top of the stack, and labels that would overflow the plot flip inside the bar with a contrasting fill. The labels are decorative (`aria-hidden`) — the accessible read stays with the chart's data table.\n\n## Area Charts\n\nArea series use a gradient fill by default. Set `fill: 'solid'` for a flat fill, or set `fillOpacity` to override the theme opacity for that series.\n\n```ts\nimport { createAreaChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createAreaChart(container, {\n a11y: { ariaLabel: 'Visitors over time' },\n crosshair: true,\n series: [\n {\n curve: 'monotone',\n data: [\n { key: 1, value: 12 },\n { key: 2, value: 18 },\n { key: 3, value: 15 },\n ],\n fill: 'solid',\n fillOpacity: 0.2,\n name: 'Visitors',\n showLine: true,\n },\n ],\n});\n\nchart.dispose();\n```\n\n## Scatter Charts\n\nScatter charts treat every datum as an independent point: `key` is the numeric or `Date` x-value and `value` is the y-value. The scales fit the observed values rather than forcing the y-domain to include zero. Set `pointRadius` on a series to change its marker size (default `3`).\n\n```ts\nimport { createScatterChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createScatterChart(container, {\n a11y: { ariaLabel: 'Height against weight' },\n series: [\n {\n data: [\n { key: 160, value: 55 },\n { key: 175, value: 70 },\n { key: 190, value: 88 },\n ],\n name: 'Cohort A',\n pointRadius: 5,\n },\n ],\n tooltip: true,\n});\n\nchart.dispose();\n```\n\nScatter callbacks identify the nearest point in two dimensions and do not provide cross-series `values`, because points do not share a category key. Keyboard navigation visits every point across series in x order. With a tooltip, `titleFormat` formats the x-value and `valueFormat` the y-value, in both the visible row and the spoken summary.\n\n## Forecast and Emphasis Styling\n\nAdd `dash` or `opacity` to individual `Datum` objects when one part of a series needs distinct styling. These fields do not change interaction, tooltip, or accessibility behavior.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst values = [10, 13, 15, 18];\nconst chart = createLineChart(container, {\n series: [\n {\n data: values.map((value, index) => ({\n key: index + 1,\n value,\n ...(index >= 2 ? { dash: '5 5', opacity: 0.4 } : {}),\n })),\n name: 'Forecast',\n showPoints: true,\n },\n ],\n});\n\nchart.dispose();\n```\n\nFor line and area charts, each datum's `dash` styles the segment from that datum to the next; the final datum has no outgoing segment. Line opacity also fades the datum's marker. Area styling affects the top line, not the fill. Bar opacity and dashes apply to the individual bar; scatter opacity applies to its point and scatter dashes are ignored. Pie, radar, and sparkline ignore these two fields.\n\n## Pie, Donut, and Semi Charts\n\nUse `createPieChart()` for all three shapes. `variant` is fixed when the chart is created; `update()` replaces the slice data.\n\n```ts\nimport { createPieChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:320px;height:240px';\ndocument.body.append(container);\n\nconst chart = createPieChart(container, {\n a11y: { ariaLabel: 'Orders by channel' },\n data: [\n { label: 'Direct', value: 42 },\n { label: 'Organic', value: 28 },\n { label: 'Referral', value: 18 },\n { label: 'Social', value: 12 },\n ],\n legend: true,\n tooltip: true,\n variant: 'donut',\n});\n\nchart.dispose();\n```\n\nThe `pie` default has no inner radius. `donut` and `semi` default to an inner radius of 55% of the outer radius. `innerRadius` overrides that size in pixels. Slice labels are omitted when they do not fit; keep a tooltip or legend when small slices need identifying.\n\n## Radar Charts\n\nDefine at least three axes when creating a radar chart. Series data uses string keys that match `RadarAxisConfig.key`; `update()` replaces series but keeps axes and other configuration fixed.\n\n```ts\nimport { createRadarChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:400px;height:320px';\ndocument.body.append(container);\n\nconst axes = [\n { key: 'strength', label: 'Strength' },\n { key: 'agility', label: 'Agility' },\n { key: 'endurance', label: 'Endurance' },\n];\nconst chart = createRadarChart(container, {\n a11y: { ariaLabel: 'Hero stats' },\n axes,\n domain: [0, 10],\n series: [\n {\n data: [\n { key: 'strength', value: 8 },\n { key: 'agility', value: 6 },\n { key: 'endurance', value: 9 },\n ],\n name: 'Adam',\n },\n ],\n tooltip: true,\n});\n\nchart.dispose();\n```\n\nThe default shared domain starts at zero and uses a nice maximum; set `domain` to compare series on a fixed range. Per-axis `min` and `max` override the chart domain for that axis. Grid rings, bands, curves, fills, vertex dots, and values are configurable; see `RadarChartConfig` and `RadarGridConfig` in the API reference.\n\n## Heatmaps\n\nDefine `rows`, `columns`, and `cells`; each cell names its `row` and `column` labels. A cell with `value: null` (or no matching cell at all) renders in `emptyColor` without in-cell text. `rowSummary` adds a right-hand column of pre-formatted per-row texts (aligned with `rows`, with an optional header) — useful for a per-row rate the cells cannot show. `update()` replaces cells and may replace `rows`, `columns`, `domain`, and `rowSummary`.\n\n```ts\nimport { createHeatmapChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:400px;height:320px';\ndocument.body.append(container);\n\nconst chart = createHeatmapChart(container, {\n a11y: { ariaLabel: 'Win rate by hero and region' },\n bins: [50, 75],\n cells: [\n { column: 'Forest', row: 'Aria', value: 90 },\n { column: 'Swamp', row: 'Aria', value: 40 },\n { column: 'Forest', row: 'Brom', value: 20 },\n { column: 'Swamp', row: 'Brom', value: 75 },\n ],\n columns: ['Forest', 'Swamp'],\n rows: ['Aria', 'Brom'],\n tooltip: true,\n valueFormat: (value) => `${value}%`,\n});\n\nchart.dispose();\n```\n\nWithout `bins` the ramp is continuous over the data's `[min, max]` domain (or an explicit `domain`); with `bins` each value maps to a discrete step and a swatch legend appears. `colorRange` sets the ramp low → high, `valueFormat` shapes in-cell values, tooltip values, and bin labels, and `showValues: false` hides the in-cell text.\n\n## Sparklines\n\nSparklines omit axes, margins, and legends. Choose `line`, `area`, or `bar` for numeric arrays, and `stack` for an array of `StackSegment` objects.\n\n```ts\nimport { createSparkline } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:240px;height:48px';\ndocument.body.append(container);\n\nconst chart = createSparkline(container, {\n a11y: { ariaLabel: 'Weekly orders' },\n data: [10, 14, 12, 18, 22],\n variant: 'area',\n});\n\nchart.update([10, 14, 12, 18, 22, 25]);\nchart.dispose();\n```\n\nFor a stacked sparkline, each segment can set `value`, `color`, and `label`. Sparklines do not offer keyboard navigation, a tooltip, or a live value announcer. Add a visible value or summary when the trend conveys important information.\n\n## Interaction\n\nSet `tooltip: true` to show Prism's default tooltip, or pass a `TooltipConfig` to format its content. `titleFormat` and `valueFormat` shape the default comparison tooltip on line, area, and bar charts—the title from the focused key and each row's value—without rebuilding its markup, and the same formatting is applied to the tooltip's spoken summary. A `render` callback receives the active `Datum` and `Series` and replaces the whole body, taking precedence over the formatters. Returned strings are inserted as text; return a DOM `Node` for structured content.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst compact = new Intl.NumberFormat(undefined, { notation: 'compact' });\nconst months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\nconst chart = createLineChart(container, {\n series: [{ data: [{ key: 11, value: 128000 }], name: 'EC2' }],\n tooltip: {\n titleFormat: (key) => months[Number(key)] ?? String(key),\n valueFormat: (value) => compact.format(value),\n },\n});\n\nchart.dispose();\n```\n\n`onHover` receives an event while a point, category, slice, or radar axis is active, then `null` when the interaction clears. `onClick` receives the selected event. For line, area, and bar charts, `ChartEvent.values` contains each series' datum at that shared key; a missing datum is `undefined`. Scatter events are `ChartEvent` objects without `values`; pie, radar, and sparkline use their chart-specific event types.\n\n`crosshair` is available on line, area, and scatter charts. By default it shows a vertical guide and snaps the line to the nearest datum. Set `horizontal: true` to add a horizontal guide or `vertical: false` to hide the vertical one. Set `snap: false` to make the guide follow the pointer; tooltip and callback data still come from the nearest datum.\n\n### Keyboard and Announcements\n\nSet `a11y: { ariaLabel }` on an informative chart. Prism gives the SVG `role=\"img\"`, an accessible name, and keyboard focus. Arrow keys move among chart data; `Home` and `End` move to the first and last item where supported; `Enter` or `Space` activates an item when an `onClick` callback is configured; `Escape` clears the active selection. Sparklines do not support keyboard navigation.\n\nWhen `a11y` is omitted, or set to `{ decorative: true }`, the SVG is marked `aria-hidden=\"true\"` and does not enter the keyboard tab order. Only mark charts decorative when their information is available elsewhere. Interactive cartesian, pie, radar, and heatmap charts use the tooltip as a polite live region when enabled; otherwise they announce active values in `.prism-live`. Sparklines have no live value announcements, so provide an equivalent visible value or summary.\n\n## Animation\n\nChart motion is enabled by default, with a 300 ms duration per animated lane (radar uses 400 ms). Pass `transition: false` to render updates synchronously, or pass `true` to state the default explicitly.\n\n```ts\nimport { createBarChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createBarChart(container, {\n series: [\n {\n data: [\n { key: 'A', value: 4 },\n { key: 'B', value: 7 },\n ],\n name: 'Count',\n },\n ],\n transition: { duration: 500, easing: 'ease-out', preference: 'system' },\n});\n\nchart.dispose();\n```\n\nColumns grow together from their baseline by default over 300 ms. Lines trace their final curve over 420 ms, uncovering point markers along the way without fading or shifting the series. Line data updates retain the default 300 ms geometry transition; an explicit `duration` overrides both timings.\n\n`preference: 'system'` (the default) disables JavaScript motion when the user prefers reduced motion. Use `'always'` to ignore that preference or `'never'` to disable motion. `stagger` sets an optional delay between bars, entering scatter points (in x order), or radar series; bar and scatter charts cap the effective delay so many marks do not add unbounded time. Named easing values are `ease-in`, `ease-in-out`, `ease-out`, `back-out`, `expo-out`, and `linear`; you can also provide an easing function.\n\n## Responsive Layout and Lifecycle\n\nSize the host with CSS. Prism observes its content box and updates the SVG dimensions and chart layout when it changes. Bar, line, and scatter resize redraws apply immediately rather than animating between layout sizes; entrance animations and explicit data-update transitions remain enabled. The legend is rendered as container chrome outside the SVG and included in resize calculations.\n\nCall `dispose()` when the view no longer owns the chart. Disposal is idempotent: it removes the SVG, tooltip, legend, and resize observation, stops in-flight chart motion, and aborts `disposalSignal`. `chart[Symbol.dispose]()` calls the same cleanup method.\n\nUse `tap()` when external code needs resize or dispose notifications rather than observing the chart DOM itself:\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createLineChart(container, {\n series: [{ data: [{ key: 1, value: 10 }], name: 'Revenue' }],\n});\nconst stopObserving = chart.tap((event) => {\n if (event.type === 'resize') console.log(event.width, event.height);\n if (event.type === 'dispose') console.log('chart disposed');\n});\n\nstopObserving();\nchart.dispose();\n```\n\n`tap()` returns an unsubscribe function and accepts `{ signal }` for automatic unsubscription. A listener exception is swallowed by the observer so it cannot interrupt chart rendering.\n\n## Theming\n\nImport the stylesheet once to load Prism's structural styles, default tokens, dark-mode rules, and reduced-motion CSS. You can override any CSS custom property on an ancestor of the chart.\n\n```css\n.dashboard-chart {\n --prism-color-1: #2563eb;\n --prism-color-2: #16a34a;\n --prism-grid-color: #94a3b8;\n --prism-line-width: 3;\n --prism-text-color: #172033;\n --prism-tooltip-bg: #111827;\n}\n```\n\n`setTheme()` provides a typed subset of theme properties. A scoped call writes inline values on the provided element; omit `scope` to write them to `document.documentElement`. Inline values override stylesheet tokens until reset.\n\n```ts\nimport { resetTheme, setTheme } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nsetTheme({ colors: ['#2563eb', '#16a34a'], fontFamily: 'Inter, sans-serif' }, { scope: container });\n// Call resetTheme({ scope: container }) when this scoped theme is no longer needed.\nresetTheme({ scope: container });\n```\n\n### Available Tokens\n\nThe stylesheet defines defaults for the following token groups. Pie-label color and size are read with fallback values by the renderer but are not declared in the base token block. Set a token on the chart container or an ancestor to scope an override.\n\n| Group | CSS custom properties |\n| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Palette and surfaces | `--prism-color-1` through `--prism-color-8`, `--prism-bg`, `--prism-border-radius` |\n| Axes and grid | `--prism-axis-color`, `--prism-axis-width`, `--prism-grid-color`, `--prism-grid-width`, `--prism-grid-dash`, `--prism-grid-opacity` |\n| Text | `--prism-font-family`, `--prism-font-size`, `--prism-font-size-label`, `--prism-font-size-title`, `--prism-font-weight`, `--prism-font-weight-title`, `--prism-text-color`, `--prism-text-color-secondary` |\n| Tooltip | `--prism-tooltip-bg`, `--prism-tooltip-color`, `--prism-tooltip-border`, `--prism-tooltip-radius`, `--prism-tooltip-padding`, `--prism-tooltip-shadow`, `--prism-tooltip-font-size` |\n| Crosshair | `--prism-crosshair-color`, `--prism-crosshair-width`, `--prism-crosshair-dash`, `--prism-crosshair-opacity` |\n| Points | `--prism-point-radius`, `--prism-point-radius-hover`, `--prism-point-stroke-width`, `--prism-point-stroke` |\n| Bars | `--prism-bar-radius`, `--prism-bar-hover-opacity`, `--prism-bar-gap`, `--prism-bar-band-fill`, `--prism-bar-band-opacity`, `--prism-bar-dim-opacity` |\n| Areas and lines | `--prism-area-opacity`, `--prism-area-stroke-width`, `--prism-area-gradient-start`, `--prism-area-gradient-end`, `--prism-line-width`, `--prism-line-width-hover` |\n| Interaction | `--prism-dim-opacity`, `--prism-active-point-radius`, `--prism-point-ring`, `--prism-focus-color` |\n| Sparklines | `--prism-spark-fill-opacity`, `--prism-spark-gradient-start`, `--prism-spark-gradient-end` |\n| Radar | `--prism-radar-grid-color`, `--prism-radar-grid-opacity`, `--prism-radar-band-fill`, `--prism-radar-band-opacity`, `--prism-radar-spoke-color`, `--prism-radar-fill-opacity`, `--prism-radar-stroke-width`, `--prism-radar-point-radius`, `--prism-radar-point-radius-active`, `--prism-radar-label-color`, `--prism-radar-label-size`, `--prism-radar-value-color`, `--prism-radar-value-size`, `--prism-radar-dim-opacity` |\n| Heatmap | `--prism-heatmap-label-color`, `--prism-heatmap-label-size`, `--prism-heatmap-value-size`, `--prism-heatmap-highlight-color` |\n| Motion | `--prism-duration-fast`, `--prism-duration`, `--prism-duration-slow`, `--prism-ease`, `--prism-ease-spring`, `--prism-transition`, `--prism-transition-fast` |\n| Legend and pie labels | `--prism-legend-gap`, `--prism-legend-dot-size`, `--prism-legend-font-size`, `--prism-pie-label-color`, `--prism-pie-label-size` |\n\nThe default palette and structural colors adapt to `prefers-color-scheme: dark`, `html.dark`, or `[data-prism-theme='dark']` on an ancestor. Scoped inline values set with `setTheme()` take precedence in either mode. The stylesheet also provides `prefers-reduced-motion` overrides for CSS transitions.\n\n## Errors and Diagnostics\n\nPrism throws `PrismRenderError` when the container is not a DOM element, when initial rendering fails, or when `update()` is called on a disposed chart. A wrapped initial-render error exposes its cause. Use `PrismError` to catch all Prism-originated errors.\n\nEmpty or malformed data is not always an exception. Depending on the chart, Prism may draw nothing or emit a development-only `console.warn`; examples include an unknown `bandScale` category, negative values in stacked bars, and radar axes with fewer than three entries or duplicate keys. Correct the input rather than relying on a warning for validation.\n\n## Framework Integration\n\nPrism has no React, Vue, or Svelte adapter. In any framework, give Prism a host element after it is mounted, call `update()` when data changes, and call `dispose()` before the host is removed. This plain DOM pattern shows the ownership boundary without depending on a framework-specific lifecycle API:\n\n```ts\nimport { createLineChart, type LineSeriesConfig } from '@vielzeug/prism';\n\nfunction mountChart(host: HTMLElement, series: LineSeriesConfig[]) {\n const chart = createLineChart(host, { a11y: { ariaLabel: 'Revenue' }, series });\n\n return {\n update(next: LineSeriesConfig[]) {\n chart.update(next);\n },\n dispose() {\n chart.dispose();\n },\n };\n}\n\nconst host = document.createElement('div');\nhost.style.cssText = 'width:640px;height:320px';\ndocument.body.append(host);\nconst view = mountChart(host, [{ data: [{ key: 1, value: 10 }], name: 'Revenue' }]);\nview.update([\n {\n data: [\n { key: 1, value: 10 },\n { key: 2, value: 15 },\n ],\n name: 'Revenue',\n },\n]);\nview.dispose();\n```\n\nThe application owns its state and host; Prism owns only the SVG, observer, and optional overlay elements it creates.\n\n## Working with Other Vielzeug Libraries\n\nUse Refine components for dashboard controls and keep Prism in a sized host element. Map Refine theme tokens to Prism CSS custom properties or call `setTheme()` with a scoped element; Prism does not require a Refine adapter. Prism uses Orbit internally to place tooltips, so chart users do not need to create Orbit floating elements for the built-in tooltip.\n\n## Best Practices\n\n- Give the host a non-zero size before creating a chart.\n- Set `a11y.ariaLabel` when a chart communicates information.\n- Use `Date` or number keys consistently across each line or area chart.\n- Pass the complete new data value to `update()`.\n- Keep chart options fixed after creation; recreate the chart to change them.\n- Dispose the handle when its host leaves the owning view.\n- Use `transition: false` for deterministic synchronous rendering.\n- Prefer CSS custom properties for reusable theme overrides.\n",
7
7
  "examples": "---\ntitle: 'Prism: Examples'\ndescription: Focused recipes for creating, updating, interacting with, and theming Prism charts.\n---\n\n- [Create a line chart](./examples/line-chart.md)\n- [Plot a time series](./examples/time-series.md)\n- [Plot a scatter chart](./examples/scatter-chart.md)\n- [Compare categories with a bar chart](./examples/bar-chart.md)\n- [Render compact charts](./examples/compact-charts.md)\n- [Compare hero stats with a radar chart](./examples/radar-chart.md)\n- [Show a win-rate matrix with a heatmap](./examples/heatmap-chart.md)\n- [Update chart data](./examples/update-data.md)\n- [Sync a details panel with hover](./examples/hover-details.md)\n- [Render a custom tooltip](./examples/custom-tooltip.md)\n- [Match charts to your design system](./examples/theming.md)\n"
8
8
  },
9
- "examples": [],
9
+ "examples": [
10
+ {
11
+ "id": "bar-chart",
12
+ "code": "import { createBarChart } from '@vielzeug/prism'\n\nconst host = document.createElement('div')\nhost.style.cssText = 'width: 100%; max-width: 640px; height: 300px'\ndocument.body.append(host)\n\nconst chart = createBarChart(host, {\n a11y: { ariaLabel: 'Downloads per package' },\n legend: true,\n series: [\n { data: [{ key: 'ore', value: 420 }, { key: 'prism', value: 310 }, { key: 'refine', value: 505 }], name: 'This week' },\n { data: [{ key: 'ore', value: 380 }, { key: 'prism', value: 295 }, { key: 'refine', value: 440 }], name: 'Last week' },\n ],\n tooltip: true,\n})\n\nconsole.log('rendered a grouped bar chart — hover the bars')\nvoid chart",
13
+ "name": "Bar chart"
14
+ },
15
+ {
16
+ "id": "line-chart",
17
+ "code": "import { createLineChart } from '@vielzeug/prism'\n\n// Charts render into any element and update through the returned handle:\n// update() replaces the whole series array, transitions animate the delta.\nconst host = document.createElement('div')\nhost.style.cssText = 'width: 100%; max-width: 640px; height: 320px'\ndocument.body.append(host)\n\nconst months = [1, 2, 3, 4, 5, 6]\nconst revenue = [12, 19, 15, 25, 32, 30]\n\nconst chart = createLineChart(host, {\n a11y: { ariaLabel: 'Revenue and costs by month' },\n legend: true,\n series: [\n { curve: 'monotone', data: months.map((m, i) => ({ key: m, value: revenue[i] })), name: 'Revenue', showPoints: true },\n ],\n tooltip: true,\n})\n\n// Explicit updates: swap in a second series after a moment, like live data would.\nsetTimeout(() => {\n chart.update([\n { curve: 'monotone', data: months.map((m, i) => ({ key: m, value: revenue[i] })), name: 'Revenue', showPoints: true },\n { color: '#e05252', curve: 'monotone', data: months.map((m) => ({ key: m, value: m * 4 + 5 })), name: 'Costs' },\n ])\n console.log('added a second series via chart.update()')\n}, 1200)",
18
+ "name": "Line chart"
19
+ }
20
+ ],
10
21
  "typeSignatures": {
11
22
  "EasingFn": "export type { EasingFn, EasingName } from './animation/easing';",
12
23
  "EasingName": "export type { EasingFn, EasingName } from './animation/easing';",
@@ -5,7 +5,18 @@
5
5
  "api": "---\ntitle: 'Refine: API Reference'\ndescription: Published component, stylesheet, framework type, and error entry points for @vielzeug/refine.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------- | ------------------------------------------------------------------------------------ | ------------------ | -------------------------------------------------------------------------------------- |\n| `@vielzeug/refine/<component>` | Register one custom element and export its public types | Sync | Importing a type alone does not register the element |\n| `@vielzeug/refine/tokens.css` | Load required theme tokens, animations, and cascade layers | CSS | Import once before components render |\n| `@vielzeug/refine/fouc.css` | Hide unregistered `ore-*` elements until upgrade | CSS | Load before first paint |\n| `@vielzeug/refine/styles/preflight.css` | Apply the optional browser reset | CSS | The reset affects global elements |\n| `@vielzeug/refine/frameworks/elements` | Register typed DOM tag mappings | Types only | Import for side effects in TypeScript |\n| `@vielzeug/refine/frameworks/react` | Register typed React JSX elements | Types only | Does not provide runtime wrappers |\n| `@vielzeug/refine/frameworks/vue` | Register typed Vue global components | Types only | Does not install a Vue plugin |\n| `@vielzeug/refine/theme` | `createThemeController()`: light/dark/system document theme | Sync | Does not persist the preference or set an accent color |\n| `@vielzeug/refine/blueprint` | `parseUiBlueprint()`: validate a model-authored UI document against a fixed registry | Sync | Pure contract only: it registers no components and renders nothing |\n| `@vielzeug/refine/blueprint/render` | `renderUiBlueprint()`: render a validated document with registered components | Sync | Registers its thirteen components on import; rejects before touching the container |\n| `eventFieldValue()` / `eventFieldChecked()` | Read a form control's value/checked from `event.currentTarget` | Sync | Exported from the package root; guards non-field targets |\n| `animateReflow()` | Token-driven FLIP reflow for keyed lists | Async (next frame) | Exported from the package root; elements need stable keys or it correctly does nothing |\n| `setMotionMode()` / `getMotionMode()` | Read/write the `data-motion` attribute on `<html>` | Sync | Exported from the package root; an unknown mode throws `RangeError` |\n| `RefineError` | Base class for package-defined public errors | Sync | Component configuration warnings do not throw this error |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/refine` | Export `registerIcons`, icon definition types, `RefineError`, `animateReflow`, the motion-mode functions, and the field readers without registering components |\n| `@vielzeug/refine/<component>` | Register one component and export its tag constant, props, events, and related types |\n| `@vielzeug/refine/theme` | `createThemeController()` and its theme types |\n| `@vielzeug/refine/blueprint` | On-demand UI document contract: `parseUiBlueprint()`, the node types, bounds, `UI_BLUEPRINT_REGISTRY`, and `UI_BLUEPRINT_JSON_SCHEMA` |\n| `@vielzeug/refine/blueprint/render` | `renderUiBlueprint()` and the thirteen component tags it registers |\n| `@vielzeug/refine/tokens.css` | Required global design contract |\n| `@vielzeug/refine/fouc.css` | Optional pre-upgrade visibility rule |\n| `@vielzeug/refine/styles/*` | Focused theme, animation, layer, and preflight stylesheets |\n| `@vielzeug/refine/frameworks/*` | TypeScript augmentations for DOM, React, and Vue |\n\n## Icon Registration and Adapters\n\n`registerIcons(icons: Readonly<Record<string, IconDefinition>>): void` is available from `@vielzeug/refine/icons`, `@vielzeug/refine`, and `@vielzeug/refine/icon`. The common `icons` entry and root remain free of component registration side effects.\n\n`IconDefinition`, `IconElement`, and `IconAttributes` are exported from all three entries. Shared definition and registration modules live in `src/icons/`, alongside adapters and internal SVG helpers/defaults. Definitions contain a numeric `viewBox` tuple, optional presentation attributes, and recursive SVG children; they do not require a provider identity. Invalid registrations throw the root-exported `RefineError` atomically.\n\n| Entry | Export | Purpose |\n| ----------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------- |\n| `@vielzeug/refine/icons` | `registerIcons`, `IconDefinition`, `IconElement`, `IconAttributes` | Common library-neutral registration and definition API |\n| `@vielzeug/refine/icons/lucide` | `lucideIcons`, `LucideIconData` | Pure adapter for selected structural Lucide SVG data |\n| `@vielzeug/refine/icons/lucide/all` | Side-effect registration | Explicitly register the full installed Lucide library |\n| `@vielzeug/refine/icons/heroicons` | `heroiconsIcons`, `IconifyIcon` | Convert a caller-named map of individual Heroicons Iconify data |\n| `@vielzeug/refine/icons/tabler` | `tablerIcons`, `IconifyIcon` | Convert a caller-named map of individual Tabler Iconify data |\n| `@vielzeug/refine/icons/mdi` | `mdiIcons`, `IconifyIcon` | Convert a caller-named map of individual MDI Iconify data |\n| `@vielzeug/refine/icons/iconify` | `iconifyIcon`, `iconifyIcons` | Convert individual Iconify data or selected/complete collections |\n| `@vielzeug/refine/icons/iconify` | `IconifyIcon`, `IconifyAlias`, `IconifyCollection`, `IconifyTransform` | Structural data types; no Iconify dependency required |\n\nLucide is an optional peer, not a mandatory dependency. Only `icons/lucide/all` requires an installed `lucide` package; consumers selecting that entry declare it themselves. The structural `icons/lucide` adapter accepts supplied data without importing Lucide.\n\nThe standalone IIFE exposes `registerIcons`, `lucideIcons`, `heroiconsIcons`, `tablerIcons`, `mdiIcons`, `iconifyIcon`, and `iconifyIcons` under `Refine.components.content`. Neither the IIFE nor component entries import Lucide. Iconify conversion drops provider `class` metadata, validates finite numeric offsets and positive finite dimensions before transforms, and retains the strict SVG allowlist. See the [icon reference](./components/icon.md) for presentation overrides, local SVG ID rewriting, supported families, and licenses.\n\nThe three family adapters share this signature:\n\n```ts\nheroiconsIcons(icons: Readonly<Record<string, IconifyIcon>>): Record<string, IconDefinition>;\ntablerIcons(icons: Readonly<Record<string, IconifyIcon>>): Record<string, IconDefinition>;\nmdiIcons(icons: Readonly<Record<string, IconifyIcon>>): Record<string, IconDefinition>;\n```\n\nEach accepts individual Iconify SVG data, preserves input keys without adding a namespace, and returns definitions without registering them. They require `DOMParser`, preserve each icon's geometry/presentation/transforms, and throw `RefineError` for invalid Iconify data. They do not accept React/Vue components, collection JSON, or raw SVG path strings. Use `iconifyIcons(collection, names?)` for collections and alias resolution.\n\n## Styles\n\n```ts\nimport '@vielzeug/refine/fouc.css';\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n`tokens.css` is required. It defines tokens, animations, and cascade-layer order without resetting global elements. `preflight.css` is optional and includes FOUC suppression.\n\n| Import path | Purpose |\n| --------------------------------------- | ----------------------------------------------- |\n| `@vielzeug/refine/fouc.css` | FOUC suppression for unupgraded custom elements |\n| `@vielzeug/refine/tokens.css` | Tokens, animation helpers, and cascade layers |\n| `@vielzeug/refine/styles/theme.css` | Theme token declarations |\n| `@vielzeug/refine/styles/animation.css` | Animation helpers |\n| `@vielzeug/refine/styles/layers.css` | Cascade layer declarations |\n| `@vielzeug/refine/styles/preflight.css` | Optional browser reset and FOUC suppression |\n\n## Components\n\nEach component uses one registration and type entry point:\n\n```ts\nimport '@vielzeug/refine/button';\nimport type { OreButtonProps } from '@vielzeug/refine/button';\n```\n\n| Area | Components |\n| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Content | `accordion`, `avatar`, `card`, `card-picker`, `carousel`, `chat-message`, `chat-panel`, `code-window`, `copy-command`, `icon`, `keyboard-key`, `list`, `marquee`, `prose`, `qr-code`, `rank-list`, `speech-player`, `speed-reading`, `stats`, `table`, `text` |\n| Feedback | `alert`, `badge`, `chip`, `cookie-banner`, `password-strength`, `progress`, `pull-to-refresh`, `skeleton`, `state`, `toast`, `typing-indicator` |\n| Inputs | `app-store-button`, `button`, `calendar`, `checkbox`, `color-picker`, `combobox`, `counter`, `datagrid`, `date-picker`, `file-input`, `input`, `message-composer`, `number-input`, `otp-input`, `qr-scanner`, `query-bar`, `radio`, `rating`, `select`, `slider`, `switch`, `textarea`, `time-picker` |\n| Layout | `box`, `dock`, `grid`, `navbar`, `separator`, `sidebar` |\n| Navigation | `breadcrumb`, `media-navigation`, `navigation-menu`, `pagination`, `stepper`, `tabs` |\n| Overlay | `command-palette`, `dialog`, `drawer`, `menu`, `popover`, `spotlight`, `tooltip`, `tour` |\n\nEach row lists the entry points that own a documentation page. Sub-element entries (`accordion-item`, `tab-item`, `avatar-group`, `list-item`, `step`, and the rest) are documented on their parent's page and share its category.\n\nEach component page lists its attributes, JavaScript properties, events, slots, parts, and CSS custom properties.\n\nThe [`query-bar`](./components/query-bar.md) entry also exports `QueryState`, `QueryTokenDef`, `QueryQuickFilter`, `QueryBarLabels`, and pure grammar helpers. Vocabulary entries default to single selection; `selection: 'multiple'` allows distinct values for the same key. `anyLabel` customizes the unrestricted single-selection choice, such as “Default order” for sorting. Options accept an optional `icon` (registered `ore-icon` name), displayed beside their labels in the drawer. `tokenValues(state, key)` reads all values, `removeToken(state, token)` removes an exact pair, and `clearTokens(state, key)` clears a group. Its unified field contains applied filters, with a compact secondary row for filter entry, quick toggles, and a `toolbar-end` slot for application content such as a result count. Drawer selection uses the same state and vocabulary as typed suggestions. Pending edits block incidental backdrop/swipe dismissal; explicit Cancel, Close, and Escape discard them. Search-hidden selections remain visible in a summary.\n\n## Framework Types\n\n```ts\nimport type {} from '@vielzeug/refine/frameworks/elements';\nimport type {} from '@vielzeug/refine/frameworks/react';\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\nThe declarations cover every supported tag and derive component properties from Refine's authoritative `HTMLElementTagNameMap`. They provide types only; component registration still uses component subpaths.\n\n## Events and Form Controls\n\nForm controls expose `.value` or `.checked` and dispatch standard `input` and `change` events. Read the property from `event.currentTarget`.\n\nFinite-choice properties use Ore's `prop.oneOf()` parsing: values outside a component's documented options resolve to\nthe declared default, or `undefined` when no default is declared.\n\nForm-associated controls participate in native form submission, validity checks, and reset. A named control's value\nis available through `new FormData(form)`, and supported `required` constraints affect `form.checkValidity()`,\n`form.reportValidity()`, and submit blocking. The `error` property renders and announces feedback; it does not by\nitself set native constraint validity.\n\nStateful overlays expose controlled `open`, optional `default-open`, and an `open-change` custom event with `{ open, reason }` detail. Component pages define additional detail fields and reasons.\n\n## Utilities\n\n### `createThemeController(options?)`\n\n```ts\nimport { createThemeController } from '@vielzeug/refine/theme';\n\nconst theme = createThemeController(); // starts in 'system' mode\ntheme.setPreference('dark');\ntheme.dispose();\n```\n\nOwns the light/dark/system theme for the document: a reactive `preference` signal, the effective `resolved` mode (`'dark' | 'light'` after resolving `system` against the OS), and the DOM application `styles/theme.css` expects: the `.dark` class plus the `color-scheme` property on the root element, so every `light-dark()` token resolves to the right branch. While in `system` mode the controller tracks the OS `prefers-color-scheme` via sentinel's `createMediaQuery`.\n\nThe controller does **not** persist the preference or expose an accent color: those are consumer concerns (wire `watch(controller.preference, save)` for persistence; set `--color-primary-hue` yourself). Options: `initial` (starting preference, default `'system'`), `root` (element carrying the classes, default `document.documentElement`), `target` (window whose `matchMedia` backs `system`). The handle is disposable: `dispose()`, `disposed`, `disposalSignal`, `[Symbol.dispose]`.\n\n### `eventFieldValue(event)` / `eventFieldChecked(event)`\n\n```ts\nimport { eventFieldChecked, eventFieldValue } from '@vielzeug/refine';\n\ninput.addEventListener('input', (event) => {\n const value = eventFieldValue(event); // string | undefined: never a blind cast\n});\n```\n\nGuarded readers for the standard `input`/`change` event pattern above: they read `value`/`checked` from `event.currentTarget` only when the target actually carries it, so a handler wired to the wrong element yields `undefined`/`false` instead of a crash or a lie. Exported from the package root, which registers no components.\n\n---\n\n### `animateReflow(host, signal, options)`\n\n```ts\nimport { animateReflow } from '@vielzeug/refine';\n\nconst reflow = animateReflow(list, abortController.signal, {\n elements: () => [...list.querySelectorAll('li')],\n getKey: (item) => item.dataset.id,\n});\nreflow.run(() => renderItems(nextItems));\n```\n\nToken-driven FLIP reflow for keyed lists: captures the current layout, runs `mutate`, then animates the tracked elements into their new positions on the next frame. The same helper the DataGrid, command palette, and toast stack use.\n\n| Parameter | Type | Description |\n| ----------------------- | ----------------------------- | --------------------------------------------------------- |\n| `host` | `HTMLElement` | Element whose computed style carries the timing tokens |\n| `signal` | `AbortSignal` | Aborting cancels in-flight animations |\n| `options.elements` | `() => HTMLElement[]` | Tracked elements, read live on both sides of the mutation |\n| `options.getKey` | `(el) => string \\| undefined` | Stable identity per element; all-or-nothing |\n| `options.durationToken` | `string?` | Duration token, default `'--duration-200'` |\n| `options.easingToken` | `string?` | Easing token, default `'--ease-move'` |\n| `options.stagger` | `number?` | Per-element delay in ms, default `0` |\n\n**Returns** a `Reflow` handle with one method: `run(mutate)` (sync; the animation is fire-and-forget). Timing is read from the tokens at animation time, so Motion Mode reduction skips the reflow instead of playing it instantly. Every path that cannot animate (no elements, missing keys, zeroed tokens, aborted signal, no Web Animations API) still runs `mutate` exactly once and never throws. See [Animation & Motion → List Reflow](./animation#list-reflow-animatereflow) for behavior details.\n\n---\n\n### `setMotionMode(mode)` / `getMotionMode()`\n\n```ts\nimport { getMotionMode, setMotionMode } from '@vielzeug/refine';\n\nsetMotionMode('reduced'); // returns the applied mode\n```\n\nRead/write the `data-motion` attribute on `<html>` (`'full' | 'reduced' | 'system'`; `'system'` removes the attribute). An unknown mode throws `RangeError`. The attribute drives the token layer: see [Animation & Motion → Motion Mode](./animation#motion-mode).\n\n## On-Demand UI Documents\n\n`@vielzeug/refine/blueprint` is the trusted boundary for UI that a model writes. A harness asks a model to describe a small UI in JSON, and this contract decides whether that JSON may be rendered. It is data only: no code, no HTML, no callbacks, no styles, no URLs. See [On-Demand UI Documents](./on-demand-ui) for the full guide.\n\n```ts\nimport { parseUiBlueprint, safeParseUiBlueprint } from '@vielzeug/refine/blueprint';\n\nconst result = safeParseUiBlueprint(JSON.parse(modelOutput)); // model output stays `unknown`\nif (!result.success)\n showError(result.issues); // safe to display: field paths, no secrets\nelse renderValidated(result.document);\n```\n\n| Export | Purpose |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `UI_BLUEPRINT_VERSION` | The only document version accepted (`1`) |\n| `parseUiBlueprint(value)` | Validate `unknown`. Returns the document unchanged, or throws `UiBlueprintError`. Nothing is repaired or partially accepted |\n| `safeParseUiBlueprint(value)` | Non-throwing form: `{ success: true, document }` or `{ success: false, issues }` |\n| `UiBlueprintError` | `RefineError` subclass carrying `issues: readonly string[]`, each a field path such as `root.children[0].size` |\n| `UI_BLUEPRINT_COMPONENTS` | The thirteen accepted component names: `text`, `box`, `card`, `button`, `badge`, `separator`, `slider`, `switch`, `checkbox`, `number-input`, `alert`, `progress`, `icon` |\n| `UI_BLUEPRINT_REGISTRY` | The same registry as data: element tag, child policy, attribute names, slot-text fields, and accepted values per component |\n| `UI_BLUEPRINT_JSON_SCHEMA` | JSON Schema (draft 2020-12) for the contract, for harnesses with structured output |\n| `BlueprintDocument`, `BlueprintNode`, and the node interfaces | TypeScript types for the document shape. Every node accepts an optional bounded `id` through `BlueprintNodeMeta` |\n| `MAX_BLUEPRINT_NODES`, `MAX_BLUEPRINT_DEPTH`, `MAX_BLUEPRINT_CHILDREN`, `MAX_BLUEPRINT_TEXT_LENGTH`, `MAX_BLUEPRINT_LABEL_LENGTH`, `MAX_BLUEPRINT_NUMBER`, `MAX_BLUEPRINT_ID_LENGTH` | Document bounds, not user-configurable |\n\n`@vielzeug/refine/blueprint` imports nothing but `RefineError`: it is pure, DOM-free, and safe to run in a model harness, a worker, or CI. It registers no components.\n\n`UI_BLUEPRINT_JSON_SCHEMA` constrains generation but cannot express the tree-wide node and depth bounds, so runtime validation stays mandatory. Treat the schema as a generation aid, never as the trust boundary.\n\n### `renderUiBlueprint(container, value, options?)`\n\n```ts\nimport { renderUiBlueprint } from '@vielzeug/refine/blueprint/render';\n\ntry {\n const { element, nodes } = renderUiBlueprint(host, JSON.parse(modelOutput), { label: 'Generated summary' });\n nodes.get('rate')?.addEventListener('change', () => recalculate());\n} catch (error) {\n // The container is untouched: the previous preview is still on screen.\n}\n```\n\nValidate `value`, then render it into `container` using only registry components. Importing the entry registers those thirteen components, so no separate component imports are needed.\n\n| Parameter | Type | Description |\n| ----------------- | ------------- | ---------------------------------------------------------------------------------- |\n| `container` | `HTMLElement` | Element that receives the rendered tree |\n| `value` | `unknown` | Untrusted model output. Validated before anything is rendered |\n| `options.label` | `string?` | Accessible name for a `role=\"group\"` wrapper. Host-owned: a document cannot set it |\n| `options.replace` | `boolean?` | Clear the container first. Default `true`; `false` appends |\n\n**Returns** a `UiBlueprintRenderResult`: `{ element, nodes }`, the rendered root and a `ReadonlyMap<string, HTMLElement>` keyed by each node's optional `id` so the host can wire behaviour to addressable controls. `id` is host-facing metadata: the renderer never writes it to the DOM. Validation runs first, so a rejected document throws `UiBlueprintError` before the container is read or written: an invalid response can never partially render or erase a valid preview. Text becomes a text node, never markup.\n\n### `createUiBlueprintElement(node, owner?, nodes?)`\n\n```ts\nimport { createUiBlueprintElement } from '@vielzeug/refine/blueprint/render';\n\nconst element = createUiBlueprintElement(document.root, 'root', nodeMap);\n```\n\nBuild one element for an already-validated node. Pass a `Map` as `nodes` to collect every id-tagged element it creates, including nested ones; `owner` labels the node's position in rejection messages. This is the component registry: adding a component means adding a rule in the contract and a case here, and nothing else. It throws `TypeError` for an unregistered node type, so a hand-built node cannot bypass validation either. Embedders that place nodes themselves use this; `renderUiBlueprint()` is the normal entry point.\n\n## Types\n\nComponent props follow the `Ore<Component>Props` naming pattern. Event maps follow `Ore<Component>Events`. Import both from the component subpath that owns them.\n\n`RefineElementMap`, `RefineReactIntrinsicElements`, and `RefineVueGlobalComponents` are exported from their respective `frameworks/*` type entry points.\n\nThe package root also exports `Reflow` (the `run()` handle), `ReflowOptions` (its options object), and `MotionMode` (`'full' | 'reduced' | 'system'`).\n\n## Errors\n\n### `RefineError`\n\n```ts\nclass RefineError extends Error {\n constructor(message: string, opts?: ErrorOptions);\n}\n```\n\nBase class for public Refine errors. It preserves `cause` through `ErrorOptions`.\n\n### `UiBlueprintError`\n\n```ts\nclass UiBlueprintError extends RefineError {\n readonly issues: readonly string[];\n}\n```\n\nThrown by `parseUiBlueprint()` and `renderUiBlueprint()` for a rejected on-demand UI document. Every rejection is collected first, so `issues` lists all of them at once, each as a field path plus a plain reason (`root.children[0].size: expected one of sm, md, lg, received string.`). The messages name fields and allowed values, report a wrong-typed value only as its _type_, and echo an accepted-type value only as a truncated snippet, so they are safe to display to a user. See [On-Demand UI Documents](./on-demand-ui).\n",
6
6
  "usage": "---\ntitle: 'Refine: Usage Guide'\ndescription: Register Refine components, configure properties, handle events, compose slots, and integrate frameworks.\n---\n\n[[toc]]\n\n## Basic Usage\n\nLoad the global design contract once, then register only the components used by the page.\n\n```ts\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/button';\nimport '@vielzeug/refine/input';\nimport '@vielzeug/refine/dialog';\n\nconst input = document.querySelector('ore-input');\nconst save = document.querySelector('ore-button');\n\nif (!(input instanceof HTMLElement) || !(save instanceof HTMLElement)) {\n throw new Error('Expected Refine controls');\n}\n\nsave.addEventListener('click', () => {\n console.log((input as HTMLElement & { value: string }).value);\n});\n```\n\nAdd the browser reset only when the application owns global element styling:\n\n```ts\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n## Choose an Icon Library\n\nRefine includes only its internal component icons. Register application icons before mounting them: use `registerIcons` and neutral `IconDefinition` data from `@vielzeug/refine/icons`, the pure `@vielzeug/refine/icons/lucide` adapter for selected Lucide icons, or `@vielzeug/refine/icons/iconify` for local Heroicons, Tabler, and Material Design Icons data. Keep importing the component from `@vielzeug/refine/icon`. Lucide is an optional peer: install `lucide` yourself only when choosing its data or `@vielzeug/refine/icons/lucide/all`; core and structural adapters do not require it. The [icon reference](./components/icon.md) covers imports, licenses, and presentation behavior.\n\nFor selected individual Iconify data, use `heroiconsIcons`, `tablerIcons`, or `mdiIcons` from `@vielzeug/refine/icons/heroicons`, `/tabler`, or `/mdi`. For example, `registerIcons(heroiconsIcons({ Search, Home }))` preserves your app keys. Install the matching `@iconify-icons/<family>` data package yourself; these helpers do not accept framework components. Keep `iconifyIcons` for collection JSON and aliases.\n\n## Set Attributes and Properties\n\nUse attributes for serializable HTML state.\n\n```html\n<ore-button variant=\"outline\" color=\"secondary\" size=\"lg\" disabled>\n Save changes\n</ore-button>\n```\n\nUse JavaScript properties for arrays, objects, callbacks, and controlled state.\n\n```ts\nimport '@vielzeug/refine/datagrid';\nimport type { OreDataGridProps } from '@vielzeug/refine/datagrid';\n\nconst grid = document.querySelector('ore-datagrid') as HTMLElement & OreDataGridProps;\ngrid.columns = [\n { key: 'name', label: 'Name', sortable: true },\n { key: 'role', label: 'Role' },\n];\ngrid.rows = [\n { id: '1', name: 'Ada', role: 'Admin' },\n { id: '2', name: 'Linus', role: 'Editor' },\n];\n```\n\nEnumerated properties such as `variant`, `size`, and `color` accept the values listed on each component's reference\npage. An unsupported value resolves to the property's declared default (or `undefined` when it has no default).\n\nIn an Ore template, `model()` can bind a Refine field's `value` to a Ripple signal and write user input back:\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { html, model } from '@vielzeug/ore';\nimport '@vielzeug/refine/input';\n\nconst email = signal('');\nconst field = html`<ore-input label=\"Email\" type=\"email\" value=${model(email)} />`;\n```\n\n## Handle Events\n\nForm controls dispatch standard `input` and `change` events. Read their current property from `event.currentTarget`.\n\n```ts\nconst input = document.querySelector('ore-input');\ninput?.addEventListener('input', (event) => {\n const target = event.currentTarget as HTMLElement & { value: string };\n console.log(target.value);\n});\n```\n\nCustom events use kebab-case names and typed detail objects.\n\n```ts\nimport type { OreDialogEvents } from '@vielzeug/refine/dialog';\n\nconst dialog = document.querySelector('ore-dialog');\ndialog?.addEventListener('open-change', (event: CustomEvent<OreDialogEvents['open-change']>) => {\n console.log(event.detail.open, event.detail.reason);\n});\n```\n\n## Native Form Validation\n\nRefine's form-associated controls integrate with native form submission, `FormData`, validity checks, and reset.\nUse `required` for a required-value constraint; setting `error` displays and announces feedback but does not, by\nitself, invalidate the form.\n\n```html\n<form id=\"profile-form\">\n <ore-input name=\"email\" type=\"email\" label=\"Email\" required></ore-input>\n <ore-select name=\"role\" label=\"Role\" required>\n <option value=\"\">Choose a role…</option>\n <option value=\"editor\">Editor</option>\n <option value=\"admin\">Admin</option>\n </ore-select>\n <ore-button type=\"submit\">Save</ore-button>\n</form>\n\n<script type=\"module\">\n import '@vielzeug/refine/input';\n import '@vielzeug/refine/select';\n import '@vielzeug/refine/button';\n\n const form = document.querySelector('#profile-form');\n form.addEventListener('submit', (event) => {\n event.preventDefault();\n console.log(new FormData(form).get('email'));\n });\n</script>\n```\n\nThe browser runs native validation before dispatching `submit`. Call `form.reportValidity()` to show validation\nfeedback directly, or `form.checkValidity()` for a boolean check without the browser's validation UI.\n\n## Compose Slots\n\nDefault slots hold primary content. Named slots identify component-owned regions.\n\n```html\n<ore-card>\n <span slot=\"header\">Account</span>\n <p>Profile settings</p>\n <div slot=\"footer\">\n <ore-button variant=\"ghost\">Cancel</ore-button>\n <ore-button>Save</ore-button>\n </div>\n</ore-card>\n```\n\nInput components commonly expose `prefix`, `suffix`, `label`, `helper`, and `error` slots. Each component reference lists its supported slots.\n\n## Load TypeScript Framework Declarations\n\nImport the declaration matching the framework once in an application type entry point.\n\n::: code-group\n\n```ts [DOM]\nimport type {} from '@vielzeug/refine/frameworks/elements';\n```\n\n```ts [React]\nimport type {} from '@vielzeug/refine/frameworks/react';\n```\n\n```ts [Vue]\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\n:::\n\nThese entry points provide typed tags and component properties. They do not register components or install runtime adapters.\n\n## Framework Integration\n\nRefine elements use native DOM properties, events, and slots. Frameworks differ only in how they forward custom-element properties and events.\n\n::: code-group\n\n```tsx [React 19]\nimport '@vielzeug/refine/button';\n\nexport function SaveButton() {\n return <ore-button variant=\"solid\">Save</ore-button>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport '@vielzeug/refine/button';\n</script>\n\n<template>\n <ore-button variant=\"solid\">Save</ore-button>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import '@vielzeug/refine/button';\n</script>\n\n<ore-button variant=\"solid\">Save</ore-button>\n```\n\n:::\n\nSee [Framework Integration](./frameworks.md) for custom events, controlled properties, SSR guards, and framework-specific configuration.\n\n## Working with Other Vielzeug Libraries\n\n### Ore\n\nUse Ore when authoring a custom element that composes Refine components.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('save-panel', {\n setup() {\n return html`<ore-button @click=${() => console.log('save')}>Save</ore-button>`;\n },\n});\n```\n\n### Ripple\n\nUse Ripple to drive component properties from application state.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { effect, signal } from '@vielzeug/ripple';\n\nconst loading = signal(false);\nconst button = document.querySelector('ore-button') as HTMLElement & { loading?: boolean };\nconst loadingEffect = effect(() => {\n button.loading = loading.value;\n});\n\nloadingEffect.dispose();\n```\n\n### Necromancer\n\nUse Necromancer directly when you need animation handles, groups, or explicit keyframes. Refine's [`animateReflow`](./animation#list-reflow-animatereflow) is the token-driven wrapper over its FLIP primitive and is enough for keyed lists that reflow.\n\n## Best Practices\n\n- **Import** `tokens.css` once before rendering components.\n- **Register** components through explicit subpaths.\n- **Set** structured data and callbacks as JavaScript properties.\n- **Read** form state from the event target instead of custom event payloads.\n- **Provide** accessible labels for icon-only controls.\n- **Use** component reference pages for supported slots, parts, and CSS properties.\n- **Dispose** application-owned Ripple effects and service handles.\n- **Guard** DOM-dependent component registration during SSR.\n- **Working with AI agents?** Install the `vielzeug` skill (`npx -y @vielzeug/codex skills install`) so agents reach for Refine components and tokens instead of custom widgets: see the [Codex usage guide](../codex/usage.md#agent-skill).\n- **Rendering model-authored UI?** Validate it through the [on-demand UI document contract](./on-demand-ui) instead of trusting model output; never build DOM from unvalidated JSON.\n"
7
7
  },
8
- "examples": [],
8
+ "examples": [
9
+ {
10
+ "id": "components",
11
+ "code": "// The refine bundle registers every ore-* custom element as soon as it loads,\n// so examples can build UI from markup directly. Theme tokens come from the\n// same CSS the docs site uses, including dark mode.\nconst card = document.createElement('ore-card')\ncard.innerHTML = `\n <h3 style=\"margin: 0 0 0.5rem\">Session status</h3>\n <p style=\"margin: 0 0 1rem\">\n <ore-badge color=\"success\">Hunt phase</ore-badge>\n <ore-badge color=\"warning\">2 clues left</ore-badge>\n </p>\n <ore-alert color=\"info\" heading=\"Boss enraged\">\n Crossfade to the boss theme when the clue counter hits zero.\n </ore-alert>\n`\ndocument.body.append(card)\n\nconst group = document.createElement('ore-button-group')\ngroup.style.marginTop = '1rem'\ngroup.innerHTML = `\n <ore-button color=\"primary\">Start hunt</ore-button>\n <ore-button variant=\"outline\">Pause</ore-button>\n`\ndocument.body.append(group)\n\ngroup.querySelector('ore-button')?.addEventListener('click', () => {\n console.log('hunt started — refine components are real custom elements')\n})",
12
+ "name": "Themed components"
13
+ },
14
+ {
15
+ "id": "form",
16
+ "code": "// Form controls are themeable custom elements with the same tokens as the\n// docs site. Wire them up with plain DOM events.\nconst form = document.createElement('div')\nform.style.cssText = 'display: flex; flex-direction: column; gap: 0.75rem; max-width: 320px'\nform.innerHTML = `\n <ore-input label=\"Player name\" placeholder=\"Ada Lovelace\"></ore-input>\n <ore-checkbox-group label=\"Party roles\">\n <ore-checkbox checked value=\"healer\">Healer</ore-checkbox>\n <ore-checkbox value=\"scout\">Scout</ore-checkbox>\n </ore-checkbox-group>\n <ore-slider max=\"20\" value=\"7\">Initiative</ore-slider>\n <ore-button color=\"primary\">Roll initiative</ore-button>\n`\ndocument.body.append(form)\n\nconst slider = form.querySelector('ore-slider')\nform.querySelector('ore-button')?.addEventListener('click', () => {\n const name = form.querySelector('ore-input')?.value ?? '(anonymous)'\n console.log(name, 'rolls initiative', slider?.getAttribute('value'))\n})",
17
+ "name": "Form controls"
18
+ }
19
+ ],
9
20
  "typeSignatures": {
10
21
  "RefineError": "export { RefineError } from './errors';",
11
22
  "IconAttributes": "export type { IconAttributes, IconDefinition, IconElement } from './icons';",
@@ -1,9 +1,9 @@
1
1
  {
2
- "apiSource": "export { toFilterPredicate, toSearchMatcher } from './adapters';\nexport {\n dedupeEntries,\n escapeRegExp,\n type RankableEntry,\n rankEntries,\n type SplitSegment,\n splitPattern,\n} from './entries';\nexport { ScoutConfigError, ScoutDisposedError, ScoutError } from './errors';\nexport { findMatchRanges, highlight, highlightField } from './highlight';\nexport type { ReactiveSearch } from './reactive';\nexport { createReactiveSearch, createSearch } from './reactive';\nexport type { ScoutIndex } from './scout-index';\nexport { createIndex } from './scout-index';\nexport { segmentWords } from './segment';\nexport type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';\n",
2
+ "apiSource": "export { toFilterPredicate, toSearchMatcher } from './adapters';\nexport {\n dedupeEntries,\n escapeRegExp,\n type RankableEntry,\n rankEntries,\n type SplitSegment,\n splitPattern,\n} from './entries';\nexport { ScoutConfigError, ScoutDisposedError, ScoutError } from './errors';\nexport { findMatchRanges, highlight, highlightField } from './highlight';\nexport { createSearch } from './reactive';\nexport type { ScoutIndex } from './scout-index';\nexport { createIndex } from './scout-index';\nexport { segmentWords } from './segment';\nexport type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';\n",
3
3
  "docs": {
4
- "index": "---\ntitle: 'Scout: Fast fuzzy search for TypeScript'\ndescription: Trigram-indexed fuzzy search with per-field weights, match highlighting, and an optional reactive layer.\npackage: scout\ncategory: utilities\nkeywords: [fuzzy-search, search, trigram, full-text, filter, highlight, reactive, ripple]\nexports:\n [\n createIndex,\n createReactiveSearch,\n createSearch,\n ScoutConfigError,\n ScoutDisposedError,\n ScoutError,\n findMatchRanges,\n highlight,\n highlightField,\n segmentWords,\n toFilterPredicate,\n toSearchMatcher,\n ]\nrelated: [arsenal, sourcerer, vault, ripple]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"scout\" />\n\n## Why Scout?\n\nArsenal's `fuzzy` / `fuzzyFilter` helpers perform pairwise Levenshtein distance: O(n·m) per item per query. For ≤200 items they are fine. For 500–100k items with real-time keystrokes, you need an index.\n\nScout builds a **trigram inverted index** at construction time. Query time scores only items sharing a trigram with the query; broad queries can still approach O(n), while selective queries avoid scoring the whole corpus.\n\n```ts\n// Before\nconst matches = users.filter((user) => user.name.toLowerCase().includes(query.toLowerCase()));\n\n// After\nimport { createIndex } from '@vielzeug/scout';\n\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst matches = index.search(query);\n```\n\n| Feature | Arsenal `fuzzy*` | Scout `createIndex` | Fuse.js |\n| ------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | ~3 KB | <PackageInfo package=\"scout\" type=\"size\" /> | ~23 KB |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Algorithm | Levenshtein | Trigram + overlap coefficient | Bitap |\n| Query time | O(n·m) | O(candidates) | O(n·m) |\n| Stateful index | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Match highlighting | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Reactive layer | <ore-icon name=\"x\" size=\"16\"></ore-icon> | Atomic external-store snapshots + debounce | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Incremental updates | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial |\n\n<div class=\"decision-callout\">\n\n**Use Scout when** you need search over 500+ items, real-time UI search boxes (combobox, command palette), or framework-neutral subscribable search state.\n\n**Consider `arsenal.fuzzyFilter` when** you have fewer than 200 items and don't need a persistent index.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/scout\n```\n\n```sh [npm]\nnpm install @vielzeug/scout\n```\n\n```sh [yarn]\nyarn add @vielzeug/scout\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst users = [\n { email: 'ada@example.com', name: 'Ada Lovelace' },\n { email: 'grace@example.com', name: 'Grace Hopper' },\n];\n\nconst index = createIndex(users, {\n fields: [{ field: 'name', weight: 2 }, { field: 'email' }],\n});\n\nconst results = index.search('ada');\nconsole.log(results[0]?.item.name); // Ada Lovelace\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createIndex()`: Trigram inverted index; construction O(corpus × field_length), query O(candidates)\n- Per-field weights: Promote `name` matches over secondary fields; finite positive weights and custom `stringify` functions supported\n- `createReactiveSearch()`: Index + reactive `SearchState` in one call; `.index` for incremental mutations\n- `createSearch()`: Reactive search state backed by an existing `ScoutIndex`; share one index across many states\n- `highlight()` / `highlightField()`: Split field text into `HighlightPart[]` fragments for styled rendering\n- `findMatchRanges()`: Compute match ranges for custom display strings (truncated previews, formatted values)\n- `toSearchMatcher()`: Matcher adapter for filtering in-memory collections with a `ScoutIndex`\n- `toFilterPredicate()`: Snapshot `(item: T) => boolean` predicate for `Array.filter` or vault queries\n- `setItems()`: Reconcile a refreshed corpus by reference, preserve incoming order, and notify once\n- Incremental updates: `add()` / `remove()` / `reindex()` patch individual items in O(field_length)\n- `onMutate()`: Subscribe to index mutations; powers `createSearch()`'s reactivity and bulk reconciliation\n- `segmentWords()`: Split unsegmented-script text (CJK, Thai, ...) into words via native `Intl.Segmenter`\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Arsenal](/arsenal/): Use `fuzzyFilter` for ad-hoc filtering of small lists (< 200 items) without building an index\n- [Ripple](/ripple/): bridge a complete Scout `SearchState` with `fromSubscribable()` when composing a larger reactive graph\n- [Sourcerer](/sourcerer/): use a `ScoutIndex` matcher to filter in-memory collections alongside remote sources\n- [Vault](/vault/): `toFilterPredicate()` wraps a one-time Scout query as a vault-compatible `filter()` predicate\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Scout: API Reference'\ndescription: 'Complete API reference for @vielzeug/scout: createIndex, createReactiveSearch, createSearch, highlight, highlightField, toSearchMatcher, toFilterPredicate.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------ | --------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------- |\n| `createIndex()` | Build trigram index from an item array | Sync | Index is built at call time: pass all initial items |\n| `ScoutIndex.search()` | Query the index, returns scored + highlighted results | Sync | Empty query returns all items with `score = 1` |\n| `ScoutIndex.add()` | Add one item to the index | Sync | No-op if same reference already indexed |\n| `ScoutIndex.remove()` | Remove one item by reference | Sync | No-op for unknown references |\n| `ScoutIndex.reindex()` | Re-index a mutated item in-place; preserves order | Sync | Call after mutating item properties; no-op if not in index |\n| `ScoutIndex.setItems()` | Reconcile a refreshed corpus in one mutation | Sync | Uses reference identity; duplicate references collapse |\n| `ScoutIndex.items` | All indexed items in insertion order | Sync | Returns a new array snapshot each call |\n| `ScoutIndex.revision` | Monotonic counter incremented after each mutation | Sync | Use as a cache-busting token for external result caches |\n| `ScoutIndex.onMutate()` | Subscribe to changed index mutations | Sync | A changed `setItems()` reconciliation emits once; no-ops emit nothing |\n| `createSearch()` | Atomic search store backed by a `ScoutIndex` | Sync | Read one snapshot and dispose the store when done |\n| `createReactiveSearch()` | One-call index + reactive search state | Sync | Exposes `.index` for incremental mutations |\n| `findMatchRanges()` | Compute match ranges for a text + query pair | Sync | Returns sorted, non-overlapping `[start, end]` ranges |\n| `highlight()` | Split text into highlighted/unhighlighted fragments | Sync | Ranges must be sorted and non-overlapping |\n| `highlightField()` | Highlight a named field from a `SearchResult` | Sync | Shorthand for the `matches.find(…).ranges → highlight()` pattern |\n| `toSearchMatcher()` | Adapt `ScoutIndex` to Sourcerer's local `filter` callback | Sync | Recomputes cached query matches after index mutation |\n| `toFilterPredicate()` | Snapshot predicate from a one-time query | Sync | Re-call when query or corpus changes |\n| `segmentWords()` | Split unsegmented-script text (CJK, Thai, ...) into words | Sync | Uses native `Intl.Segmenter`: not applied inside `tokenize()` itself (see Pitfalls) |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ----------------- | ---------------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/scout` | All exports: index/search/highlighting/adapters, `ScoutConfigError`, `ScoutDisposedError`, `ScoutError`, and all types |\n\n---\n\n## `createIndex(items, options)`\n\nBuilds a trigram inverted index from `items`. Construction is O(corpus × field_length); subsequent `search()` calls are O(candidates).\n\n```ts\nfunction createIndex<T>(items: T[], options: ScoutIndexOptions<T>): ScoutIndex<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ |\n| `items` | `T[]` | Initial corpus to index. |\n| `options.fields` | `ReadonlyArray<FieldDef<T>>` | Fields to index. Required; at least one entry. |\n| `options.threshold` | `number` | Finite overlap score in `0..1` (default `0.2`). |\n| `options.limit` | `number` | Finite non-negative integer max results (default `50`). |\n| `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring; shorter queries use O(n) containment scan (default `3`). |\n\n**Example**\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst products = [\n { sku: 'WGT-001', title: 'Widget Pro' },\n { sku: 'GAD-002', title: 'Gadget Plus' },\n];\n\nconst index = createIndex(products, {\n fields: [{ field: 'title', weight: 2 }, { field: 'sku' }],\n threshold: 0.25,\n limit: 20,\n});\n```\n\n---\n\n## `ScoutIndex<T>`\n\nReturned by `createIndex()`.\n\n### `.search(query, options?)`\n\n```ts\nsearch(query: string, options?: SearchConstraints): SearchResult<T>[]\n```\n\nReturns results sorted by score descending. Empty query returns all items with `score = 1`. Results below `threshold` are excluded; at most `limit` results are returned.\n\n```ts\nconst results = index.search('alice');\n// [{ item, score, matches }]\n```\n\n### `.add(item)`\n\nAdds `item` to the index. No-op if the same reference is already indexed. O(field_length).\n\n### `.remove(item)`\n\nRemoves `item` by reference equality. No-op if not found. O(field_length).\n\n### `.reindex(item)`\n\nRe-reads the item's current field values and rebuilds its index entry in-place, updating only fields whose values changed. Preserves insertion order. No-op if the item is not in the index.\n\n```ts\nitem.name = 'new name';\nindex.reindex(item);\n```\n\n### `.setItems(items)`\n\n```ts\nsetItems(items: readonly T[]): void\n```\n\nReconciles the index to a refreshed corpus in one mutation. Existing references are reindexed, missing references are removed, added references are indexed, and incoming first-occurrence order becomes index order. Duplicate references collapse to one item. Calls `onMutate()` once when indexed values, membership, or order changes.\n\n```ts\nindex.setItems(latestUsers);\n```\n\n### `.size`\n\n`number`: current number of indexed items.\n\n### `.items`\n\n`readonly T[]`: all indexed items in insertion order. Returns a new array snapshot each call.\n\n```ts\nconst all = index.items;\n```\n\n### `.onMutate(listener)`\n\n```ts\nonMutate(listener: () => void): () => void\n```\n\nSubscribes `listener` to run after every changed `add()` / `remove()` / `reindex()` / `setItems()` operation. No-ops, including unchanged bulk reconciliation, do not fire it. A changed `setItems()` reconciliation fires once. `createSearch()` uses this internally to keep `results` in sync with index mutations; most callers building on `createIndex()` directly will not need it.\n\n```ts\nconst unsubscribe = index.onMutate(() => {\n console.log(`Index changed: now ${index.size} items`);\n});\n\nindex.add(newUser); // logs \"Index changed: now 6 items\"\nunsubscribe();\n```\n\n### `.revision`\n\n`number`: monotonically increasing counter, incremented after every changed `add()` / `remove()` / `reindex()` / `setItems()` operation. Use as a cache-busting token when caching search results outside the index: `toSearchMatcher()` uses it for this purpose.\n\n---\n\n## `createSearch(index, options?)`\n\nWraps a `ScoutIndex` in a zero-dependency external store. `getSnapshot()` returns the current query, loading flag, and results as one consistent snapshot; `subscribe()` notifies after the complete snapshot is committed.\n\n```ts\nfunction createSearch<T>(index: ScoutIndex<T>, options?: CreateSearchOptions): SearchState<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------- |\n| `options.debounce` | `number` | Finite non-negative integer milliseconds before query commit (default `200`). Pass `0` for immediate updates. |\n| `options.limit` | `number` | Finite non-negative integer override of index-level limit. |\n| `options.threshold` | `number` | Finite `0..1` override of index-level threshold. |\n| `options.minQueryLength` | `number` | Finite positive integer override of index-level minimum query length. |\n\n**Returns `SearchState<T>`**\n\n| Member | Type | Description |\n| ------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------ |\n| `getSnapshot()` | `() => SearchSnapshot<T>` | Returns the stable current snapshot. Identity changes only after a state transition. |\n| `setQuery(query)` | `(query: string) => void` | Starts or immediately commits a query according to `debounce`. |\n| `subscribe(listener, options?)` | `(listener, options?) => () => void` | Notifies after an atomic snapshot commit. Supports `{ signal }` cleanup. |\n| `tap(handler, options?)` | `(handler, options?) => () => void` | Observes typed state and disposal events. Handler errors are swallowed. |\n| `disposalSignal` | `AbortSignal` | Aborted when `dispose()` is called. Use to tie other lifecycles to this search. |\n| `disposed` | `boolean` | `true` after `dispose()` has been called. |\n| `clear()` | `() => void` | Resets query, cancels debounce, and restores empty-query results synchronously. |\n| `dispose()` | `() => void` | Releases timers and subscriptions. |\n| `[Symbol.dispose]()` | `() => void` | `using`-compatible disposal. |\n\n**Example**\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst users = [{ name: 'Ada Lovelace' }, { name: 'Grace Hopper' }];\nconst index = createIndex(users, { fields: ['name'] });\nconst search = createSearch(index, { debounce: 150 });\n\nsearch.subscribe(() => {\n console.log(search.getSnapshot().results.map((result) => result.item.name));\n});\n\nsearch.setQuery('ada');\n```\n\n---\n\n## `createReactiveSearch(items, options)`\n\nCreates a `ScoutIndex` and a reactive `SearchState` in one call: the shorthand for `createIndex` + `createSearch`. Returns a `ReactiveSearch<T>` which extends `SearchState<T>` with a `.index` property for incremental mutations.\n\n```ts\nfunction createReactiveSearch<T>(items: T[], options: ScoutIndexOptions<T> & { debounce?: number }): ReactiveSearch<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | ---------------------------- | ----------------------------------------------------------------------- |\n| `items` | `T[]` | Initial corpus to index. |\n| `options.fields` | `ReadonlyArray<FieldDef<T>>` | Fields to index. Required. |\n| `options.debounce` | `number` | Finite non-negative integer debounce milliseconds (default `200`). |\n| `options.threshold` | `number` | Finite overlap score in `0..1` (default `0.2`). |\n| `options.limit` | `number` | Finite non-negative integer max results (default `50`). |\n| `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring (default `3`). |\n\n**Returns `ReactiveSearch<T>`**: all `SearchState<T>` members plus:\n\n| Member | Type | Description |\n| ------- | --------------- | ---------------------------------------------------- |\n| `index` | `ScoutIndex<T>` | The underlying index for `add`, `remove`, `reindex`. |\n\n**Example**\n\n```ts\nimport { createReactiveSearch } from '@vielzeug/scout';\n\nconst users = [{ email: 'ada@example.com', name: 'Ada Lovelace' }];\nconst search = createReactiveSearch(users, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n});\n\nsearch.subscribe(() => console.log(search.getSnapshot().results.map((result) => result.item.name)));\n\nsearch.index.add({ email: 'grace@example.com', name: 'Grace Hopper' });\nsearch.dispose();\n```\n\n---\n\n## `findMatchRanges(text, query)`\n\nNormalizes raw `query` with Scout's tokenizer, then computes sorted, non-overlapping literal ranges for each normalized token within `text`. Useful when you need to apply highlighting to a different string than the indexed field value (e.g. a truncated preview or a differently formatted display string).\n\n```ts\nfunction findMatchRanges(text: string, query: string): [number, number][];\n```\n\n**Example**\n\n```ts\nimport { findMatchRanges, highlight } from '@vielzeug/scout';\n\nconst ranges = findMatchRanges('Alice Johnson', 'alice!');\n// [[0, 5]]\n\nconst parts = highlight('Alice Johnson', ranges);\n// [{ text: 'Alice', highlighted: true }, { text: ' Johnson', highlighted: false }]\n```\n\nReturns an empty array if either `text` or `query` is empty.\n\n---\n\n## `highlight(text, ranges)`\n\nSplits `text` into `HighlightPart[]` fragments based on `ranges` from `FieldMatch.ranges`.\n\n```ts\nfunction highlight(text: string, ranges: [number, number][]): HighlightPart[];\n```\n\n**Example**\n\n```ts\nimport { highlight } from '@vielzeug/scout';\n\nhighlight('Hello World', [[0, 5]]);\n// [{ text: 'Hello', highlighted: true }, { text: ' World', highlighted: false }]\n```\n\nReturns an empty array when `text` is empty. Returns a single unhighlighted part when `ranges` is empty.\n\n---\n\n## `highlightField(result, field, text)`\n\nConvenience shorthand that finds the match ranges for `field` in `result.matches` and calls `highlight()` in one step. Eliminates the manual `result.matches.find(m => m.field === …).ranges` lookup.\n\n```ts\nfunction highlightField<T>(result: SearchResult<T>, field: keyof T & string, text: string): HighlightPart[];\n```\n\n**Example**\n\n```ts\nimport { createIndex, highlightField } from '@vielzeug/scout';\n\nconst users = [{ name: 'Alice Johnson' }];\nconst index = createIndex(users, { fields: ['name'] });\n\nfor (const result of index.search('alice')) {\n const parts = highlightField(result, 'name', result.item.name);\n console.log(parts.map((part) => (part.highlighted ? `[${part.text}]` : part.text)).join(''));\n}\n```\n\nWhen the field has no match (e.g. the query matched via a different field), returns a single unhighlighted part.\n\n---\n\n## `toSearchMatcher(index, options?)`\n\nReturns an `(item, query) => boolean` matcher compatible with Sourcerer's local `filter` option.\n\n```ts\nfunction toSearchMatcher<T>(index: ScoutIndex<T>, options?: SearchConstraints): (item: T, query: string) => boolean;\n```\n\nOne matching-item set is cached per query and index revision, so filtering does not repeat index work per item and stays current after index mutation.\n\n```ts\nimport { createIndex, toSearchMatcher } from '@vielzeug/scout';\nimport { createLocalSource } from '@vielzeug/sourcerer';\n\nconst users = [{ email: 'ada@example.com', name: 'Ada Lovelace' }];\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst source = createLocalSource(users, { filter: toSearchMatcher(index), params: '' });\n\nsource.setParams('ada');\n```\n\n---\n\n## `toFilterPredicate(index, query, options?)`\n\nReturns a `(item: T) => boolean` predicate computed from a one-time query. Use with `Array.filter` or vault's `query.filter()`.\n\n```ts\nfunction toFilterPredicate<T>(index: ScoutIndex<T>, query: string, options?: SearchConstraints): (item: T) => boolean;\n```\n\nThe predicate is a snapshot: re-call `toFilterPredicate` if the query or corpus changes.\n\n```ts\nimport { createIndex, toFilterPredicate } from '@vielzeug/scout';\n\nconst products = [{ title: 'Widget Pro' }, { title: 'Gadget Plus' }];\nconst index = createIndex(products, { fields: ['title'] });\nconst results = products.filter(toFilterPredicate(index, 'widget'));\n\nconst top5 = products.filter(toFilterPredicate(index, 'widget', { limit: 5 }));\n```\n\n---\n\n## `segmentWords(text)`\n\nSplits `text` into whitespace-joined word segments using the runtime's native `Intl.Segmenter`: no dependency beyond the platform API. Falls back to returning `text` unchanged where `Intl.Segmenter` isn't available.\n\n```ts\nfunction segmentWords(text: string): string;\n```\n\n`tokenize()`'s trigram-based scoring already works on unsegmented scripts (Chinese, Japanese, Thai, ...) without this: trigrams are generated per-character, not per-word. `segmentWords()` is for `findMatchRanges()` / highlighting and the multi-word query semantics on `SearchConstraints`, which assume space-separated words. **Not applied inside `tokenize()` itself**: benchmarked at ~15x slower than the plain regex path for the common whitespace-delimited case, which would regress `createIndex()`'s construction cost for every caller, not just those indexing unsegmented scripts.\n\n**Example**\n\n```ts\nimport { createIndex, segmentWords } from '@vielzeug/scout';\n\nconst documents = [{ title: '日本語を勉強しています' }];\nconst index = createIndex(documents, {\n fields: [{ field: 'title', stringify: (value) => segmentWords(String(value)) }],\n});\n```\n\n---\n\n## Types\n\n### `SearchConstraints`\n\nShared search-tuning knobs used by `ScoutIndexOptions`, `CreateSearchOptions`, and all search functions.\n\n```ts\ntype SearchConstraints = {\n limit?: number; // finite non-negative integer; default 50\n minQueryLength?: number; // finite positive integer; default 3\n threshold?: number; // finite 0..1 value; default 0.2\n};\n```\n\n### `FieldDef<T>`\n\n```ts\ntype FieldDef<T> =\n | (keyof T & string)\n | {\n field: keyof T & string;\n weight?: number; // default 1\n stringify?: (value: unknown) => string;\n };\n```\n\n### `ScoutIndexOptions<T>`\n\n```ts\ntype ScoutIndexOptions<T> = SearchConstraints & {\n fields: ReadonlyArray<FieldDef<T>>;\n};\n```\n\n### `CreateSearchOptions`\n\n```ts\ntype CreateSearchOptions = SearchConstraints & {\n debounce?: number; // finite non-negative integer; default 200\n};\n```\n\n### `SearchResult<T>`\n\n```ts\ntype SearchResult<T> = {\n item: T;\n matches: FieldMatch<keyof T & string>[]; // literal normalized-token ranges; may be empty for fuzzy-only results\n score: number; // [0, 1]; 1 when query is empty\n};\n```\n\n### `FieldMatch<F>`\n\nGeneric over the union of field names: `match.field` is typed to the actual fields of `T`.\n\n```ts\ntype FieldMatch<F extends string = string> = {\n field: F;\n ranges: [number, number][]; // literal normalized-token [start, end] ranges in original field value\n};\n```\n\n### `HighlightPart`\n\n```ts\ntype HighlightPart = {\n highlighted: boolean;\n text: string;\n};\n```\n\n### `SearchSnapshot<T>`\n\n```ts\ntype SearchSnapshot<T> = Readonly<{\n isSearching: boolean;\n query: string;\n results: ReadonlyArray<SearchResult<T>>;\n}>;\n```\n\nSnapshots and their result arrays are frozen at runtime.\n\n### `ScoutEvent<T>`\n\n```ts\ntype ScoutEvent<T> = { readonly snapshot: SearchSnapshot<T>; readonly type: 'state-change' };\n```\n\n### `SearchState<T>`\n\n```ts\ntype SearchState<T> = {\n readonly disposalSignal: AbortSignal;\n readonly disposed: boolean;\n clear(): void;\n dispose(): void;\n getSnapshot(): SearchSnapshot<T>;\n setQuery(query: string): void;\n subscribe(listener: () => void, options?: { signal?: AbortSignal }): () => void;\n tap(handler: (event: ScoutEvent<T>) => void, options?: { signal?: AbortSignal }): () => void;\n [Symbol.dispose](): void;\n};\n```\n\n`subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run. `tap()` emits `state-change` only: disposal is observable through `disposed` and `disposalSignal`; tapper errors are swallowed.\n\n### `ReactiveSearch<T>`\n\n```ts\ntype ReactiveSearch<T> = SearchState<T> & {\n readonly index: ScoutIndex<T>;\n};\n```\n\nSee `createReactiveSearch()` above.\n\n---\n\n## Errors\n\n### `ScoutError`\n\nBase class for all scout errors. Use `instanceof ScoutError` to catch any scout-originated error.\n\n```ts\nclass ScoutError extends Error {}\n```\n\n**Named subclasses**\n\n| Class | Thrown when |\n| -------------------- | ------------------------------------------------------------------------------- |\n| `ScoutConfigError` | An index, search, or reactive search receives invalid fields or numeric options |\n| `ScoutDisposedError` | A method is called on a disposed `SearchState` instance |\n\n## Entry Ranking\n\nReference lists: glossaries, rule compendiums, profile directories: rank and render through the same helpers.\n\n### `rankEntries(entries, query, options?)`\n\nOrders `RankableEntry` items (`{ id, label, meta, text }`) by how directly they match the query: exact label, label prefix, label contains, meta contains, text contains, and finally `options.fuzzyIds` hits as last resort. Non-matching entries drop; ties break alphabetically. A blank query returns every entry.\n\n### `dedupeEntries(entries)`\n\nDrops entries whose label and body text are identical to an earlier entry (case-insensitive): alias rows in merged catalogs.\n\n### `splitPattern(text, pattern)`\n\nSplits text on a global regular expression, marking matched pieces (`SplitSegment`), for rendering keyword links over prose. A `null` pattern keeps the text whole.\n\n### `escapeRegExp(value)`\n\nEscapes a literal for embedding in a regular expression: build keyword patterns from display names.\n",
6
- "usage": "---\ntitle: 'Scout: Usage Guide'\ndescription: 'How-to guide for @vielzeug/scout: building indexes, reactive search, highlighting, and integrating with sourcerer and vault.'\n---\n\n[[toc]]\n\n## Basic Usage\n\n### Building an index\n\nPass your item array and field configuration to `createIndex`. All items are indexed immediately at construction time.\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst users = [\n { email: 'ada@example.com', name: 'Ada Lovelace' },\n { email: 'grace@example.com', name: 'Grace Hopper' },\n];\n\nconst index = createIndex(users, {\n fields: ['name', 'email'],\n});\n```\n\n### Searching\n\nCall `index.search(query)` with any string. Results are sorted by score descending.\n\n```ts\nconst results = index.search('alice');\n\nfor (const { item, score, matches } of results) {\n console.log(item.name, score);\n}\n```\n\nAn empty `query` returns all items with `score = 1`:\n\n```ts\nindex.search(''); // All items, score = 1 each\n```\n\n### Per-field weights\n\nGive fields different weights to control score ranking. A match on a high-weight field ranks the item higher than a match on a low-weight field.\n\n```ts\nconst index = createIndex(users, {\n fields: [\n { field: 'name', weight: 3 }, // name matches rank 3× higher\n { field: 'department', weight: 1 },\n { field: 'bio', weight: 0.5 },\n ],\n});\n```\n\n### Non-string fields\n\nUse `stringify` to convert numeric or boolean fields to searchable text.\n\n```ts\nconst index = createIndex(products, {\n fields: [\n 'title',\n { field: 'price', stringify: (v) => `$${v}` },\n { field: 'inStock', stringify: (v) => (v ? 'available in stock' : 'out of stock') },\n ],\n});\n```\n\n### Non-Latin scripts (CJK, Thai, ...)\n\n`tokenize()` indexes any script correctly: trigrams are generated per-character, so Chinese, Japanese, Cyrillic, and accented Latin text are all searchable out of the box. What it doesn't do is insert word boundaries for scripts that don't use spaces (Chinese, Japanese, Thai, ...), which affects `findMatchRanges()` / highlighting and multi-word query semantics. Pre-segment those fields with `segmentWords()`:\n\n```ts\nimport { createIndex, segmentWords } from '@vielzeug/scout';\n\nconst docs = [{ title: '日本語を勉強しています' }, { title: '我喜欢学习中文' }];\n\nconst index = createIndex(docs, {\n fields: [{ field: 'title', stringify: (v) => segmentWords(String(v)) }],\n});\n\nindex.search('日本語'); // matches the first document\n```\n\n`segmentWords()` uses the runtime's native `Intl.Segmenter`: no dependency. It's opt-in per field rather than built into `tokenize()` because it benchmarks ~15x slower than the default regex path for ordinary whitespace-delimited text.\n\n### Limiting results\n\nPass `limit`, `threshold`, and `minQueryLength` in options to control result count and quality. `limit` must be a finite non-negative integer, `threshold` a finite value in `0..1`, and `minQueryLength` a finite positive integer; invalid values throw `ScoutConfigError`.\n\n```ts\n// At most 10 results, minimum overlap score 0.3\nconst results = index.search('widget', { limit: 10, threshold: 0.3 });\n```\n\nPer-call options override the index-level defaults set in `createIndex`.\n\nScores come from the overlap (Szymkiewicz–Simpson) coefficient: the fraction of the _shorter_\ntrigram set (almost always the query) found in the longer one. This is deliberate for the\nautocomplete/command-palette use case `createIndex` targets: a short query that's a clean prefix\nof a much longer field value (e.g. `'fin'` against `'Finalize Q3 budget report'`) scores on how\nmuch of the query matched, not diluted by how much longer the target field happens to be.\n\n### Controlling short-query behaviour\n\nQueries shorter than `minQueryLength` (default `3`) fall back to an O(n) substring containment scan. Short-query matches return `score = 1.0`.\n\n```ts\n// Use trigram scoring even for 1-char queries (good for small corpora)\nconst index = createIndex(items, { fields: ['name'], minQueryLength: 1 });\n\n// Force containment scan for all queries up to 8 chars (good for autocomplete on large sets)\nconst results = index.search('alice', { minQueryLength: 8 });\n```\n\n## Reactive Search\n\n### `createReactiveSearch()`: recommended\n\nFor most use cases, `createReactiveSearch` builds the index and state together. It returns one external store whose snapshot contains `query`, `isSearching`, and `results`, plus `.index` for incremental mutations:\n\n```ts\nimport { createReactiveSearch } from '@vielzeug/scout';\n\nconst search = createReactiveSearch(users, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n});\n\nsearch.subscribe(() => {\n const { isSearching, results } = search.getSnapshot();\n if (isSearching) showLoadingSpinner();\n else renderResults(results.map((result) => result.item));\n});\n\ninput.addEventListener('input', (event) => {\n search.setQuery((event.currentTarget as HTMLInputElement).value);\n});\n\nsearch.index.add(newUser);\nsearch.dispose();\n```\n\nEach notification observes a complete committed snapshot. During a debounce window, `query` contains the latest input, `isSearching` is `true`, and `results` remain the last committed results.\n\n### `createSearch()`: separate index and state\n\nUse `createSearch` when sharing one index across multiple search stores:\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst search = createSearch(index, { debounce: 150 });\n```\n\n### `using` declaration\n\n```ts\n{\n using search = createReactiveSearch(users, { fields: ['name'] });\n // search.dispose() called automatically at scope exit\n}\n```\n\n### Zero debounce for synchronous updates\n\nPass `debounce: 0` for synchronous commits with no searching transition:\n\n```ts\nconst search = createReactiveSearch(users, { fields: ['name'], debounce: 0 });\n\nsearch.setQuery('alice');\nconsole.log(search.getSnapshot().results); // Already updated\n```\n\n### Resetting search\n\n```ts\nsearch.clear(); // Resets query, results, and isSearching atomically\n```\n\n### Composing with Ripple\n\nA complete `SearchState` implements Ripple's structural subscribable contract:\n\n```ts\nimport { createRipple } from '@vielzeug/ripple';\n\nconst ripple = createRipple();\nconst state = ripple.fromSubscribable(search, { signal: search.disposalSignal });\nconst topResult = ripple.computed(() => state.value.results[0]?.item ?? null);\n```\n\n## Incremental Updates\n\nUse `add()`, `remove()`, and `reindex()` for individual reference-based mutations. Use `setItems()` when a refreshed collection replaces the current corpus; Scout reconciles membership, current field values, and source order in one notification.\n\n```ts\nconst index = createIndex(products, { fields: ['title'] });\n\n// Add a newly created item\nconst newProduct = { id: 99, title: 'New Widget' };\nindex.add(newProduct);\n\n// Remove a deleted item (by reference)\nindex.remove(products[0]);\n\n// Re-index a mutated item after in-place mutation\nproducts[1].title = 'Updated Title';\nindex.reindex(products[1]);\n```\n\n> `remove()`, `reindex()`, and `setItems()` use **reference equality** (`===`). Pass retained object references from the current corpus; `setItems()` collapses duplicate references.\n\n### Replacing a refreshed corpus\n\n```ts\nconst latestProducts = await loadProducts();\n\nindex.setItems(latestProducts);\n```\n\n`setItems()` removes references absent from `latestProducts`, adds new references, reindexes retained references, and adopts the incoming order. It calls `onMutate()` once only when index membership, field values, or order changes.\n\n### Inspecting the corpus\n\nUse `.items` to read all currently indexed items in insertion order, or `.size` for a count:\n\n```ts\nconsole.log(index.size); // 42\nconsole.log(index.items); // [{ id: 1, title: ... }, ...]\n```\n\n### Reacting to mutations directly\n\n`createSearch()` already keeps `results` in sync with `add()`/`remove()`/`reindex()`/`setItems()` internally. `toSearchMatcher()` also invalidates its query cache after index mutation. If you're building your own reactivity on top of a plain `ScoutIndex` (no `ripple` involved), subscribe with `onMutate()`:\n\n```ts\nconst unsubscribe = index.onMutate(() => {\n rerenderResultsList();\n});\n\nindex.add(newProduct); // triggers rerenderResultsList()\n\nunsubscribe(); // when done\n```\n\n`onMutate()` only fires for mutations that actually change the index: a duplicate `add()` or a `remove()` of an unindexed item is a no-op and doesn't notify listeners.\n\n## Match Highlighting\n\nEvery `SearchResult` carries `matches`: per-field literal normalized-token ranges. A fuzzy trigram candidate can have `matches: []` when no literal query token appears in its field text.\n\n### `highlightField()`: recommended\n\n`highlightField(result, field, text)` is the shorthand that does the field lookup and fragment split in one step:\n\n```ts\nimport { highlightField } from '@vielzeug/scout';\n\nfor (const result of index.search('alice')) {\n const parts = highlightField(result, 'name', result.item.name);\n // [{ text: 'Alice', highlighted: true }, { text: ' Johnson', highlighted: false }]\n renderHighlightedText(parts);\n}\n```\n\n::: warning `part.text` is unescaped\n`highlight()` / `highlightField()` return the **original, unescaped** field text split into\nfragments: never concatenate `part.text` into an HTML string for `innerHTML`. Render each\npart as text (`textContent`, a framework's text binding) and wrap `highlighted` parts in your\nown element:\n\n```ts\nfunction renderHighlightedText(parts: HighlightPart[]): DocumentFragment {\n const fragment = document.createDocumentFragment();\n\n for (const part of parts) {\n if (part.highlighted) {\n const mark = document.createElement('mark');\n\n mark.textContent = part.text; // textContent: never innerHTML\n fragment.appendChild(mark);\n } else {\n fragment.appendChild(document.createTextNode(part.text));\n }\n }\n\n return fragment;\n}\n```\n\n:::\n\n### `findMatchRanges()` + `highlight()`: manual\n\nUse `findMatchRanges()` when you need to apply match ranges to a different string than the indexed field value: for example a truncated preview or a differently formatted display string:\n\n```ts\nimport { findMatchRanges, highlight } from '@vielzeug/scout';\n\nconst [result] = index.search('alice');\nconst preview = result.item.bio.slice(0, 100);\nconst ranges = findMatchRanges(preview, 'alice');\nconst parts = highlight(preview, ranges);\n```\n\nOr use `highlight()` directly when you already have the ranges from `result.matches`:\n\n```ts\nconst [result] = index.search('alice');\nconst nameMatch = result.matches.find((m) => m.field === 'name');\nconst parts = highlight(result.item.name, nameMatch?.ranges ?? []);\n```\n\n## Searchable Reference Lists\n\nA glossary or compendium mixes entry kinds and needs direct-match ranking above fuzzy hits. Rank with `rankEntries`, render keyword links with `splitPattern`, and highlight the typed query with `findMatchRanges` + `highlight`.\n\n```ts\nimport { dedupeEntries, escapeRegExp, findMatchRanges, highlight, rankEntries, splitPattern } from '@vielzeug/scout';\n\nconst keywordPattern = new RegExp(`(${keywords.map((k) => escapeRegExp(k.name)).join('|')})`, 'g');\nconst results = rankEntries(entries, query, { fuzzyIds: fuzzyIndexIds });\n\nfor (const entry of results) {\n for (const segment of splitPattern(entry.text, keywordPattern)) {\n if (segment.matched) renderKeywordLink(segment.text);\n else for (const part of highlight(segment.text, findMatchRanges(segment.text, query))) renderMark(part);\n }\n}\n```\n\nDedupe merged catalogs with `dedupeEntries` before ranking so alias rows do not shadow their originals.\n\n## Debug Logging\n\nUse `tap()` for typed runtime observation without affecting search behavior:\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst search = createSearch(index, { debounce: 150 });\nconst stop = search.tap((event) => {\n console.debug(event.snapshot.query, event.snapshot.isSearching, event.snapshot.results.length);\n});\n\nsearch.setQuery('alice');\nstop();\n```\n\n`tap()` emits only `state-change`; observe disposal through `disposed` or `disposalSignal`. Tapper errors are swallowed. Use `subscribe()` instead when application state must update after each snapshot commit.\n\n::: warning Development logging\n`query` carries the full, literal search query string: if your queries may carry PII (names, emails, medical/financial terms typed by end users), don't log them in production.\n:::\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { createReactiveSearch } from '@vielzeug/scout';\nimport { useEffect, useMemo, useSyncExternalStore } from 'react';\n\ntype User = { id: number; name: string; email: string };\n\nfunction useScoutSearch(items: User[]) {\n const search = useMemo(\n () =>\n createReactiveSearch(items, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n }),\n [items],\n );\n const snapshot = useSyncExternalStore(search.subscribe, search.getSnapshot, search.getSnapshot);\n\n useEffect(() => () => search.dispose(), [search]);\n\n return { ...snapshot, setQuery: search.setQuery };\n}\n```\n\n```ts [Vue 3]\nimport { createReactiveSearch } from '@vielzeug/scout';\nimport { onScopeDispose, shallowRef } from 'vue';\n\ntype User = { id: number; name: string; email: string };\n\nfunction useScoutSearch(items: User[]) {\n const search = createReactiveSearch(items, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n });\n const snapshot = shallowRef(search.getSnapshot());\n const stop = search.subscribe(() => {\n snapshot.value = search.getSnapshot();\n });\n\n onScopeDispose(() => {\n stop();\n search.dispose();\n });\n\n return { search, snapshot };\n}\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { createReactiveSearch } from '@vielzeug/scout';\n import { onDestroy } from 'svelte';\n\n type User = { id: number; name: string; email: string };\n\n export let items: User[];\n\n const search = createReactiveSearch(items, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n });\n let snapshot = search.getSnapshot();\n const stop = search.subscribe(() => { snapshot = search.getSnapshot(); });\n\n onDestroy(() => { stop(); search.dispose(); });\n</script>\n\n<input value={snapshot.query} on:input={(event) => search.setQuery(event.currentTarget.value)} placeholder=\"Search…\" />\n{#each snapshot.results as { item }}\n <p>{item.name}</p>\n{/each}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Sourcerer\n\n`toSearchMatcher()` adapts a `ScoutIndex` into Sourcerer's local-source filter.\n\n```ts\nimport { createIndex, toSearchMatcher } from '@vielzeug/scout';\nimport { createLocalSource } from '@vielzeug/sourcerer';\n\nconst index = createIndex(users, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n});\nconst source = createLocalSource(users, { filter: toSearchMatcher(index), params: '' });\n\nsource.setParams('alice');\nconsole.log(source.state.items);\n```\n\n> Update the index and source from the same collection change. Use `index.setItems(items)` with `source.setItems(items)` for replacement collections.\n\n### With Vault\n\n`toFilterPredicate()` returns an `(item: T) => boolean` snapshot predicate: pass it to vault's `query.filter()` or plain `Array.filter`.\n\n```ts\nimport { createIndex, toFilterPredicate } from '@vielzeug/scout';\n\nconst index = createIndex(products, { fields: ['title', 'sku'] });\n\nconst matching = products.filter(toFilterPredicate(index, 'widget'));\n\nconst rows = await db.query('products').filter(toFilterPredicate(index, searchTerm)).toArray();\n```\n\nCall `toFilterPredicate` again whenever the query or corpus changes: the predicate is a snapshot, not reactive.\n\n## Best Practices\n\n- **Build the index once**: `createIndex()` runs in O(corpus × field_length). Create it at module level or in an effect, not inside render loops.\n- **Keep the index in sync**: call `index.add()` / `remove()` / `reindex()` when items mutate. Stale index entries return wrong scores.\n- **Tune threshold before limit**: set a meaningful `threshold` (e.g. `0.25–0.4`) to suppress noise, then use `limit` to cap the list length.\n- **Set `minQueryLength` for your corpus size**: the default `3` works well for most cases. Lower it for small corpora where single-char queries are expected; raise it for large corpora to avoid expensive O(n) scans.\n- **Dispose reactive state**: always call `search.dispose()` or use `using` when the component unmounts.\n- **Weight by importance**: name/title fields should have weight `2–3`; secondary fields (description, tags) stay at `1`.\n- **Segment CJK/Thai fields explicitly**: `segmentWords()` is opt-in per field, not automatic, to keep `createIndex()` fast for the common whitespace-delimited case.\n",
4
+ "index": "---\ntitle: 'Scout: Fast fuzzy search for TypeScript'\ndescription: Trigram-indexed fuzzy search with per-field weights, match highlighting, and an optional reactive layer.\npackage: scout\ncategory: utilities\nkeywords: [fuzzy-search, search, trigram, full-text, filter, highlight, reactive, ripple]\nexports:\n [\n createIndex,\n createSearch,\n ScoutConfigError,\n ScoutDisposedError,\n ScoutError,\n findMatchRanges,\n highlight,\n highlightField,\n segmentWords,\n toFilterPredicate,\n toSearchMatcher,\n ]\nrelated: [arsenal, sourcerer, vault, ripple]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"scout\" />\n\n## Why Scout?\n\nArsenal's `fuzzy` / `fuzzyFilter` helpers perform pairwise Levenshtein distance: O(n·m) per item per query. For ≤200 items they are fine. For 500–100k items with real-time keystrokes, you need an index.\n\nScout builds a **trigram inverted index** at construction time. Query time scores only items sharing a trigram with the query; broad queries can still approach O(n), while selective queries avoid scoring the whole corpus.\n\n```ts\n// Before\nconst matches = users.filter((user) => user.name.toLowerCase().includes(query.toLowerCase()));\n\n// After\nimport { createIndex } from '@vielzeug/scout';\n\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst matches = index.search(query);\n```\n\n| Feature | Arsenal `fuzzy*` | Scout `createIndex` | Fuse.js |\n| ------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | ~3 KB | <PackageInfo package=\"scout\" type=\"size\" /> | ~23 KB |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Algorithm | Levenshtein | Trigram + query coverage | Bitap |\n| Query time | O(n·m) | O(candidates) | O(n·m) |\n| Stateful index | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Match highlighting | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Reactive layer | <ore-icon name=\"x\" size=\"16\"></ore-icon> | Atomic external-store snapshots + debounce | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Incremental updates | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial |\n\n<div class=\"decision-callout\">\n\n**Use Scout when** you need search over 500+ items, real-time UI search boxes (combobox, command palette), or framework-neutral subscribable search state.\n\n**Consider `arsenal.fuzzyFilter` when** you have fewer than 200 items and don't need a persistent index.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/scout\n```\n\n```sh [npm]\nnpm install @vielzeug/scout\n```\n\n```sh [yarn]\nyarn add @vielzeug/scout\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst users = [\n { email: 'ada@example.com', name: 'Ada Lovelace' },\n { email: 'grace@example.com', name: 'Grace Hopper' },\n];\n\nconst index = createIndex(users, {\n fields: [{ field: 'name', weight: 2 }, { field: 'email' }],\n});\n\nconst results = index.search('ada');\nconsole.log(results[0]?.item.name); // Ada Lovelace\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createIndex()`: Trigram inverted index; construction O(corpus × field_length), query O(candidates)\n- Per-field weights: Promote `name` matches over secondary fields; finite positive weights and custom `stringify` functions supported\n- `createSearch()`: Reactive search state backed by a `ScoutIndex`; share one index across many states\n- `highlight()` / `highlightField()`: Split field text into `HighlightPart[]` fragments for styled rendering\n- `findMatchRanges()`: Compute match ranges for custom display strings (truncated previews, formatted values)\n- `toSearchMatcher()`: Matcher adapter for filtering in-memory collections with a `ScoutIndex`\n- `toFilterPredicate()`: Snapshot `(item: T) => boolean` predicate for `Array.filter` or vault queries\n- `setItems()`: Reconcile a refreshed corpus by key, preserve incoming order, and notify once\n- `key` option + `removeKey()`: Stable item identity for immutable data; skip unchanged work with fresh copies and delete by id\n- Incremental updates: `add()` / `remove()` / `reindex()` patch individual items in O(field_length)\n- `subscribe()`: Subscribe to index mutations; powers `createSearch()`'s reactivity and bulk reconciliation\n- `segmentWords()`: Split unsegmented-script text (CJK, Thai, ...) into words via native `Intl.Segmenter`\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Arsenal](/arsenal/): Use `fuzzyFilter` for ad-hoc filtering of small lists (< 200 items) without building an index\n- [Ripple](/ripple/): bridge a complete Scout `SearchState` with `fromSubscribable()` when composing a larger reactive graph\n- [Sourcerer](/sourcerer/): use a `ScoutIndex` matcher to filter in-memory collections alongside remote sources\n- [Vault](/vault/): `toFilterPredicate()` wraps a one-time Scout query as a vault-compatible `filter()` predicate\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
+ "api": "---\ntitle: 'Scout: API Reference'\ndescription: 'Complete API reference for @vielzeug/scout: createIndex, createSearch, highlight, highlightField, toSearchMatcher, toFilterPredicate.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------ | --------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------ |\n| `createIndex()` | Build trigram index from an item array | Sync | Index is built at call time: pass all initial items |\n| `ScoutIndex.search()` | Query the index, returns scored + highlighted results | Sync | Empty query returns all items with `score = 1` |\n| `ScoutIndex.add()` | Add one item to the index | Sync | An existing key adopts the new object; without a `key`, same reference is a no-op |\n| `ScoutIndex.remove()` | Remove the item stored under `key(item)` | Sync | No-op for unknown keys |\n| `ScoutIndex.removeKey()` | Remove the item stored under a raw key | Sync | Returns whether an item was removed |\n| `ScoutIndex.reindex()` | Store `item` under its key and reindex changed fields | Sync | With a `key`, a fresh copy of the item is enough; no-op for unknown keys |\n| `ScoutIndex.setItems()` | Reconcile a refreshed corpus in one mutation | Sync | Uses key identity (reference by default); equal fresh copies notify nothing |\n| `ScoutIndex.items` | All indexed items in insertion order | Sync | Returns a new array snapshot each call |\n| `ScoutIndex.revision` | Monotonic counter incremented after each mutation | Sync | Use as a cache-busting token for external result caches |\n| `ScoutIndex.subscribe()` | Subscribe to changed index mutations | Sync | A changed `setItems()` reconciliation emits once; no-ops emit nothing |\n| `createSearch()` | Atomic search store backed by a `ScoutIndex` | Sync | Read one snapshot and dispose the store when done |\n| `findMatchRanges()` | Compute match ranges for a text + query pair | Sync | Returns sorted, non-overlapping `[start, end)` ranges in the original text |\n| `highlight()` | Split text into highlighted/unhighlighted fragments | Sync | Ranges must be sorted and non-overlapping |\n| `highlightField()` | Highlight a named field from a `SearchResult` | Sync | Shorthand for the `matches.find(…).ranges → highlight()` pattern |\n| `toSearchMatcher()` | Adapt `ScoutIndex` to Sourcerer's local `filter` callback | Sync | Recomputes cached query matches after index mutation |\n| `toFilterPredicate()` | Snapshot predicate from a one-time query | Sync | Re-call when query or corpus changes |\n| `segmentWords()` | Split unsegmented-script text (CJK, Thai, ...) into words | Sync | Uses native `Intl.Segmenter`: not applied inside `normalize()` itself (see Pitfalls) |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ----------------- | ---------------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/scout` | All exports: index/search/highlighting/adapters, `ScoutConfigError`, `ScoutDisposedError`, `ScoutError`, and all types |\n\n---\n\n## `createIndex(items, options)`\n\nBuilds a trigram inverted index from `items`. Construction is O(corpus × field_length); subsequent `search()` calls are O(candidates). With a `key`, construction throws `ScoutConfigError` when two different items share one key, matching `setItems()`.\n\n```ts\nfunction createIndex<T>(items: readonly T[], options: ScoutIndexOptions<T>): ScoutIndex<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ |\n| `items` | `readonly T[]` | Initial corpus to index. |\n| `options.fields` | `ReadonlyArray<FieldDef<T>>` | Fields to index. Required; at least one entry. |\n| `options.key` | `(item: T) => unknown` | Stable item identity for `add`/`remove`/`reindex`/`setItems` (default: object reference). |\n| `options.threshold` | `number` | Finite query-coverage score in `0..1` (default `0.2`). |\n| `options.limit` | `number` | Finite non-negative integer max results (default `50`). |\n| `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring; shorter queries use O(n) containment scan (default `3`). |\n\n**Example**\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst products = [\n { sku: 'WGT-001', title: 'Widget Pro' },\n { sku: 'GAD-002', title: 'Gadget Plus' },\n];\n\nconst index = createIndex(products, {\n fields: [{ field: 'title', weight: 2 }, { field: 'sku' }],\n threshold: 0.25,\n limit: 20,\n});\n```\n\n---\n\n## `ScoutIndex<T>`\n\nReturned by `createIndex()`.\n\n### `.search(query, options?)`\n\n```ts\nsearch(query: string, options?: SearchConstraints): SearchResult<T>[]\n```\n\nReturns results sorted by score descending. Empty query returns all items with `score = 1`. Results below `threshold` are excluded; at most `limit` results are returned.\n\n```ts\nconst results = index.search('alice');\n// [{ item, score, matches }]\n```\n\n### `.add(item)`\n\nAdds `item` to the index. If another object is already stored under `key(item)`, that record adopts `item` and its changed fields are reindexed (no notification when nothing changed); without a custom `key`, re-adding the same reference is a no-op. O(field_length).\n\n### `.remove(item)`\n\nRemoves the item stored under `key(item)`. No-op if not found. O(field_length).\n\n### `.removeKey(key)`\n\n```ts\nremoveKey(key: unknown): boolean\n```\n\nRemoves the item stored under `key` and returns whether an item was removed. Use with a custom `key` to delete by id without fabricating a `T`.\n\n### `.reindex(item)`\n\nStores `item` under `key(item)`, re-reads its field values, and rebuilds its index entry in-place, updating only fields whose text changed. Preserves insertion order. With a custom `key`, passing a fresh copy of the item is enough. No-op if the key is not in the index.\n\n```ts\nitem.name = 'new name';\nindex.reindex(item);\n```\n\n### `.setItems(items)`\n\n```ts\nsetItems(items: readonly T[]): void\n```\n\nReconciles the index to a refreshed corpus in one mutation by key identity (reference identity by default). Retained items adopt their incoming object and are reindexed, missing keys are removed, added keys are indexed, and incoming first-occurrence order becomes index order. Duplicate references collapse to one item; two different objects sharing one key throw `ScoutConfigError`. Calls `subscribe()` listeners once when indexed field text, membership, or order changed — reconciling an equal corpus of fresh copies notifies nothing.\n\n```ts\nindex.setItems(latestUsers);\n```\n\n### `.size`\n\n`number`: current number of indexed items.\n\n### `.items`\n\n`readonly T[]`: all indexed items in insertion order — the latest object stored for each key. Returns a new array snapshot each call.\n\n```ts\nconst all = index.items;\n```\n\n### `.subscribe(listener)`\n\n```ts\nsubscribe(listener: () => void): () => void\n```\n\nSubscribes `listener` to run after every changed `add()` / `remove()` / `reindex()` / `setItems()` operation. No-ops, including unchanged bulk reconciliation, do not fire it. A changed `setItems()` reconciliation fires once. `createSearch()` uses this internally to keep `results` in sync with index mutations; most callers building on `createIndex()` directly will not need it.\n\n```ts\nconst unsubscribe = index.subscribe(() => {\n console.log(`Index changed: now ${index.size} items`);\n});\n\nindex.add(newUser); // logs \"Index changed: now 6 items\"\nunsubscribe();\n```\n\n### `.revision`\n\n`number`: monotonically increasing counter, incremented after every changed `add()` / `remove()` / `reindex()` / `setItems()` operation. Use as a cache-busting token when caching search results outside the index: `toSearchMatcher()` uses it for this purpose.\n\n---\n\n## `createSearch(index, options?)`\n\nWraps a `ScoutIndex` in a zero-dependency external store. `getSnapshot()` returns the current query, loading flag, and results as one consistent snapshot; `subscribe()` notifies after the complete snapshot is committed.\n\n```ts\nfunction createSearch<T>(index: ScoutIndex<T>, options?: CreateSearchOptions): SearchState<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------- |\n| `options.debounce` | `number` | Finite non-negative integer milliseconds before query commit (default `200`). Pass `0` for immediate updates. |\n| `options.limit` | `number` | Finite non-negative integer override of index-level limit. |\n| `options.threshold` | `number` | Finite `0..1` override of index-level threshold. |\n| `options.minQueryLength` | `number` | Finite positive integer override of index-level minimum query length. |\n\n**Returns `SearchState<T>`**\n\n| Member | Type | Description |\n| ------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------ |\n| `getSnapshot()` | `() => SearchSnapshot<T>` | Returns the stable current snapshot. Identity changes only after a state transition. |\n| `setQuery(query)` | `(query: string) => void` | Starts or immediately commits a query according to `debounce`. |\n| `subscribe(listener, options?)` | `(listener, options?) => () => void` | Notifies after an atomic snapshot commit. Supports `{ signal }` cleanup. |\n| `disposalSignal` | `AbortSignal` | Aborted when `dispose()` is called. Use to tie other lifecycles to this search. |\n| `disposed` | `boolean` | `true` after `dispose()` has been called. |\n| `clear()` | `() => void` | Resets query, cancels debounce, and restores empty-query results synchronously. |\n| `dispose()` | `() => void` | Releases timers and subscriptions. |\n| `[Symbol.dispose]()` | `() => void` | `using`-compatible disposal. |\n\n**Example**\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst users = [{ name: 'Ada Lovelace' }, { name: 'Grace Hopper' }];\nconst index = createIndex(users, { fields: ['name'] });\nconst search = createSearch(index, { debounce: 150 });\n\nsearch.subscribe(() => {\n console.log(search.getSnapshot().results.map((result) => result.item.name));\n});\n\nsearch.setQuery('ada');\n```\n\n---\n\n## `findMatchRanges(text, query)`\n\nNormalizes `text` and `query` with Scout's shared normalization (lowercase, punctuation to single spaces, Latin-only accent folding), matches the whole normalized query as a phrase first, then each word individually — a one-character word matches only at a word start — merges overlaps, and maps the ranges back to the original string. Useful when you need to apply highlighting to a different string than the indexed field value (e.g. a truncated preview or a differently formatted display string).\n\n```ts\nfunction findMatchRanges(text: string, query: string): [number, number][];\n```\n\n**Example**\n\n```ts\nimport { findMatchRanges, highlight } from '@vielzeug/scout';\n\nconst ranges = findMatchRanges('Alice Johnson', 'alice!');\n// [[0, 5]]\n\nconst parts = highlight('Alice Johnson', ranges);\n// [{ text: 'Alice', highlighted: true }, { text: ' Johnson', highlighted: false }]\n```\n\nReturns an empty array if either `text` or `query` is empty.\n\n---\n\n## `highlight(text, ranges)`\n\nSplits `text` into `HighlightPart[]` fragments based on `ranges` from `FieldMatch.ranges`.\n\n```ts\nfunction highlight(text: string, ranges: [number, number][]): HighlightPart[];\n```\n\n**Example**\n\n```ts\nimport { highlight } from '@vielzeug/scout';\n\nhighlight('Hello World', [[0, 5]]);\n// [{ text: 'Hello', highlighted: true }, { text: ' World', highlighted: false }]\n```\n\nReturns an empty array when `text` is empty. Returns a single unhighlighted part when `ranges` is empty.\n\n---\n\n## `highlightField(result, field, text)`\n\nConvenience shorthand that finds the match ranges for `field` in `result.matches` and calls `highlight()` in one step. Eliminates the manual `result.matches.find(m => m.field === …).ranges` lookup.\n\n```ts\nfunction highlightField<T>(result: SearchResult<T>, field: keyof T & string, text: string): HighlightPart[];\n```\n\n**Example**\n\n```ts\nimport { createIndex, highlightField } from '@vielzeug/scout';\n\nconst users = [{ name: 'Alice Johnson' }];\nconst index = createIndex(users, { fields: ['name'] });\n\nfor (const result of index.search('alice')) {\n const parts = highlightField(result, 'name', result.item.name);\n console.log(parts.map((part) => (part.highlighted ? `[${part.text}]` : part.text)).join(''));\n}\n```\n\nWhen the field has no match (e.g. the query matched via a different field), returns a single unhighlighted part.\n\n---\n\n## `toSearchMatcher(index, options?)`\n\nReturns an `(item, query) => boolean` matcher compatible with Sourcerer's local `filter` option.\n\n```ts\nfunction toSearchMatcher<T>(index: ScoutIndex<T>, options?: SearchConstraints): (item: T, query: string) => boolean;\n```\n\nOne matching-item set is cached per query and index revision, so filtering does not repeat index work per item and stays current after index mutation.\n\n```ts\nimport { createIndex, toSearchMatcher } from '@vielzeug/scout';\nimport { createLocalSource } from '@vielzeug/sourcerer';\n\nconst users = [{ email: 'ada@example.com', name: 'Ada Lovelace' }];\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst source = createLocalSource(users, { filter: toSearchMatcher(index), params: '' });\n\nsource.setParams('ada');\n```\n\n---\n\n## `toFilterPredicate(index, query, options?)`\n\nReturns a `(item: T) => boolean` predicate computed from a one-time query. Use with `Array.filter` or vault's `query.filter()`.\n\n```ts\nfunction toFilterPredicate<T>(index: ScoutIndex<T>, query: string, options?: SearchConstraints): (item: T) => boolean;\n```\n\nThe predicate is a snapshot: re-call `toFilterPredicate` if the query or corpus changes.\n\n```ts\nimport { createIndex, toFilterPredicate } from '@vielzeug/scout';\n\nconst products = [{ title: 'Widget Pro' }, { title: 'Gadget Plus' }];\nconst index = createIndex(products, { fields: ['title'] });\nconst results = products.filter(toFilterPredicate(index, 'widget'));\n\nconst top5 = products.filter(toFilterPredicate(index, 'widget', { limit: 5 }));\n```\n\n---\n\n## `segmentWords(text)`\n\nSplits `text` into whitespace-joined word segments using the runtime's native `Intl.Segmenter`: no dependency beyond the platform API. Falls back to returning `text` unchanged where `Intl.Segmenter` isn't available.\n\n```ts\nfunction segmentWords(text: string): string;\n```\n\n`normalize()`'s trigram-based scoring already works on unsegmented scripts (Chinese, Japanese, Thai, ...) without this: trigrams are generated per-character, not per-word. `segmentWords()` is for `findMatchRanges()` highlighting and its phrase matching, which assume space-separated words. **Not applied inside `normalize()` itself**: benchmarked at ~15x slower than the plain regex path for the common whitespace-delimited case, which would regress `createIndex()`'s construction cost for every caller, not just those indexing unsegmented scripts.\n\n**Example**\n\n```ts\nimport { createIndex, segmentWords } from '@vielzeug/scout';\n\nconst documents = [{ title: '日本語を勉強しています' }];\nconst index = createIndex(documents, {\n fields: [{ field: 'title', stringify: (value) => segmentWords(String(value)) }],\n});\n```\n\n---\n\n## Types\n\n### `SearchConstraints`\n\nShared search-tuning knobs used by `ScoutIndexOptions`, `CreateSearchOptions`, and all search functions.\n\n```ts\ntype SearchConstraints = {\n limit?: number; // finite non-negative integer; default 50\n minQueryLength?: number; // finite positive integer; default 3\n threshold?: number; // finite 0..1 value; default 0.2\n};\n```\n\n### `FieldDef<T>`\n\n```ts\ntype FieldDef<T> =\n | (keyof T & string)\n | {\n field: keyof T & string;\n weight?: number; // default 1\n stringify?: (value: unknown) => string;\n };\n```\n\n### `ScoutIndexOptions<T>`\n\n```ts\ntype ScoutIndexOptions<T> = SearchConstraints & {\n fields: ReadonlyArray<FieldDef<T>>;\n key?: (item: T) => unknown; // stable identity; default (item) => item\n};\n```\n\n### `CreateSearchOptions`\n\n```ts\ntype CreateSearchOptions = SearchConstraints & {\n debounce?: number; // finite non-negative integer; default 200\n};\n```\n\n### `SearchResult<T>`\n\n```ts\ntype SearchResult<T> = {\n item: T;\n matches: FieldMatch<keyof T & string>[]; // literal [start, end) ranges in original field values; empty for fuzzy-only results\n score: number; // weighted query coverage in [0, 1]; 1 when query is empty\n};\n```\n\n### `FieldMatch<F>`\n\nGeneric over the union of field names: `match.field` is typed to the actual fields of `T`.\n\n```ts\ntype FieldMatch<F extends string = string> = {\n field: F;\n ranges: [number, number][]; // literal [start, end) ranges in the original field value\n};\n```\n\n### `HighlightPart`\n\n```ts\ntype HighlightPart = {\n highlighted: boolean;\n text: string;\n};\n```\n\n### `SearchSnapshot<T>`\n\n```ts\ntype SearchSnapshot<T> = Readonly<{\n isSearching: boolean;\n query: string;\n results: ReadonlyArray<SearchResult<T>>;\n}>;\n```\n\nSnapshots and their result arrays are frozen at runtime.\n\n### `SearchState<T>`\n\n```ts\ntype SearchState<T> = {\n readonly disposalSignal: AbortSignal;\n readonly disposed: boolean;\n clear(): void;\n dispose(): void;\n getSnapshot(): SearchSnapshot<T>;\n setQuery(query: string): void;\n subscribe(listener: () => void, options?: { signal?: AbortSignal }): () => void;\n [Symbol.dispose](): void;\n};\n```\n\n`subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run.\n\n---\n\n## Errors\n\n### `ScoutError`\n\nBase class for all scout errors. Use `instanceof ScoutError` to catch any scout-originated error.\n\n```ts\nclass ScoutError extends Error {}\n```\n\n**Named subclasses**\n\n| Class | Thrown when |\n| -------------------- | ------------------------------------------------------------------------------ |\n| `ScoutConfigError` | An index or search receives invalid fields, numeric options, or duplicate keys |\n| `ScoutDisposedError` | A method is called on a disposed `SearchState` instance |\n\n## Entry Ranking\n\nReference lists: glossaries, rule compendiums, profile directories: rank and render through the same helpers.\n\n### `rankEntries(entries, query, options?)`\n\nOrders `RankableEntry` items (`{ id, label, meta, text }`) by how directly they match the query: exact label, label prefix, label contains, meta contains, text contains, and finally `options.fuzzyIds` hits as last resort. Non-matching entries drop; ties break alphabetically. A blank query returns every entry.\n\n### `dedupeEntries(entries)`\n\nDrops entries whose label and body text are identical to an earlier entry (case-insensitive): alias rows in merged catalogs.\n\n### `splitPattern(text, pattern)`\n\nSplits text on a global regular expression, marking matched pieces (`SplitSegment`), for rendering keyword links over prose. A `null` pattern keeps the text whole.\n\n### `escapeRegExp(value)`\n\nEscapes a literal for embedding in a regular expression: build keyword patterns from display names.\n",
6
+ "usage": "---\ntitle: 'Scout: Usage Guide'\ndescription: 'How-to guide for @vielzeug/scout: building indexes, reactive search, highlighting, and integrating with sourcerer and vault.'\n---\n\n[[toc]]\n\n## Basic Usage\n\n### Building an index\n\nPass your item array and field configuration to `createIndex`. All items are indexed immediately at construction time.\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst users = [\n { email: 'ada@example.com', name: 'Ada Lovelace' },\n { email: 'grace@example.com', name: 'Grace Hopper' },\n];\n\nconst index = createIndex(users, {\n fields: ['name', 'email'],\n});\n```\n\n### Searching\n\nCall `index.search(query)` with any string. Results are sorted by score descending.\n\n```ts\nconst results = index.search('alice');\n\nfor (const { item, score, matches } of results) {\n console.log(item.name, score);\n}\n```\n\nAn empty `query` returns all items with `score = 1`:\n\n```ts\nindex.search(''); // All items, score = 1 each\n```\n\n### Per-field weights\n\nGive fields different weights to control score ranking. A match on a high-weight field ranks the item higher than a match on a low-weight field.\n\n```ts\nconst index = createIndex(users, {\n fields: [\n { field: 'name', weight: 3 }, // name matches rank 3× higher\n { field: 'department', weight: 1 },\n { field: 'bio', weight: 0.5 },\n ],\n});\n```\n\n### Non-string fields\n\nUse `stringify` to convert numeric or boolean fields to searchable text.\n\n```ts\nconst index = createIndex(products, {\n fields: [\n 'title',\n { field: 'price', stringify: (v) => `$${v}` },\n { field: 'inStock', stringify: (v) => (v ? 'available in stock' : 'out of stock') },\n ],\n});\n```\n\n### Non-Latin scripts (CJK, Thai, ...)\n\nScout's normalization indexes any script correctly: trigrams are generated per-character, so Chinese, Japanese, Cyrillic, and accented Latin text are all searchable out of the box. What it doesn't do is insert word boundaries for scripts that don't use spaces (Chinese, Japanese, Thai, ...), which affects `findMatchRanges()` / highlighting and multi-word phrase matching. Pre-segment those fields with `segmentWords()`:\n\n```ts\nimport { createIndex, segmentWords } from '@vielzeug/scout';\n\nconst docs = [{ title: '日本語を勉強しています' }, { title: '我喜欢学习中文' }];\n\nconst index = createIndex(docs, {\n fields: [{ field: 'title', stringify: (v) => segmentWords(String(v)) }],\n});\n\nindex.search('日本語'); // matches the first document\n```\n\n`segmentWords()` uses the runtime's native `Intl.Segmenter`: no dependency. It's opt-in per field rather than built into the shared normalization because it benchmarks ~15x slower than the default regex path for ordinary whitespace-delimited text.\n\n### Limiting results\n\nPass `limit`, `threshold`, and `minQueryLength` in options to control result count and quality. `limit` must be a finite non-negative integer, `threshold` a finite value in `0..1`, and `minQueryLength` a finite positive integer; invalid values throw `ScoutConfigError`.\n\n```ts\n// At most 10 results, minimum query-coverage score 0.3\nconst results = index.search('widget', { limit: 10, threshold: 0.3 });\n```\n\nPer-call options override the index-level defaults set in `createIndex`.\n\nScores are query coverage: the fraction of the **query's** trigrams found in a field, scaled by\nthat field's relative weight. `'fin'` against `'Finalize Q3 roadmap'` scores how much of the\nquery was found (about `0.67`), independent of how long the field is; conversely, a long query\nlike `'tomato soup recipe'` does not reward a field that merely contains part of it. Each item\nis also scored against the union of all its fields' text at the smallest field weight, so a\ncross-field query like `'alice smith'` finds `{ first: 'Alice', last: 'Smith' }` as well as one\ncombined `Alice Smith` field.\n\n### Controlling short-query behaviour\n\nQueries shorter than `minQueryLength` (default `3`) fall back to an O(n) substring containment scan. Short-query matches return `score = 1.0`.\n\n```ts\n// Use trigram scoring even for 1-char queries (good for small corpora)\nconst index = createIndex(items, { fields: ['name'], minQueryLength: 1 });\n\n// Force containment scan for all queries up to 8 chars (good for autocomplete on large sets)\nconst results = index.search('alice', { minQueryLength: 8 });\n```\n\n## Reactive Search\n\n`createSearch()` wraps a `ScoutIndex` in one external store whose snapshot contains `query`, `isSearching`, and `results`. The index stays in your hands for incremental mutations, and one index can back several search stores:\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst index = createIndex(users, { fields: [{ field: 'name', weight: 2 }, 'email'] });\nconst search = createSearch(index, { debounce: 150 });\n\nsearch.subscribe(() => {\n const { isSearching, results } = search.getSnapshot();\n if (isSearching) showLoadingSpinner();\n else renderResults(results.map((result) => result.item));\n});\n\ninput.addEventListener('input', (event) => {\n search.setQuery((event.currentTarget as HTMLInputElement).value);\n});\n\nindex.add(newUser); // the search state re-runs the committed query\nsearch.dispose();\n```\n\nEach notification observes a complete committed snapshot. During a debounce window, `query` contains the latest input, `isSearching` is `true`, and `results` remain the last committed results. Index mutations re-run the last committed query, so new items surface without another `setQuery()`.\n\n### `using` declaration\n\n```ts\n{\n using search = createSearch(index, { debounce: 150 });\n // search.dispose() called automatically at scope exit\n}\n```\n\n### Zero debounce for synchronous updates\n\nPass `debounce: 0` for synchronous commits with no searching transition:\n\n```ts\nconst search = createSearch(index, { debounce: 0 });\n\nsearch.setQuery('alice');\nconsole.log(search.getSnapshot().results); // Already updated\n```\n\n### Resetting search\n\n```ts\nsearch.clear(); // Resets query, results, and isSearching atomically\n```\n\n### Composing with Ripple\n\nA complete `SearchState` implements Ripple's structural subscribable contract:\n\n```ts\nimport { createRipple } from '@vielzeug/ripple';\n\nconst ripple = createRipple();\nconst state = ripple.fromSubscribable(search, { signal: search.disposalSignal });\nconst topResult = ripple.computed(() => state.value.results[0]?.item ?? null);\n```\n\n## Incremental Updates\n\nUse `add()`, `remove()`, and `reindex()` for individual mutations. Use `setItems()` when a refreshed collection replaces the current corpus; Scout reconciles membership, current field values, and source order in one notification.\n\n```ts\nconst index = createIndex(products, { fields: ['title'] });\n\n// Add a newly created item\nconst newProduct = { id: 99, title: 'New Widget' };\nindex.add(newProduct);\n\n// Remove a deleted item (by key; the default key is the reference)\nindex.remove(products[0]);\n\n// Re-index a mutated item after in-place mutation\nproducts[1].title = 'Updated Title';\nindex.reindex(products[1]);\n```\n\n> Without a `key`, `remove()`, `reindex()`, and `setItems()` identify items by **reference equality** (`===`): pass retained object references from the current corpus, and `setItems()` collapses duplicate references. With a `key`, any object carrying the same key works: see [Immutable data and stable keys](#immutable-data-and-stable-keys).\n\n### Immutable data and stable keys\n\nIf your pipeline creates fresh objects on every update (framework stores, immutable reducers, mapped projections), pass a `key` that identifies each item across generations:\n\n```ts\nconst index = createIndex(products, {\n fields: ['title'],\n key: (product) => product.id,\n});\n\n// setItems() with fresh copies of unchanged items: no reindex, no notification.\n// Changed keys reindex only their changed fields; missing keys drop out.\nindex.setItems(await loadProducts()); // [{ id: 7, title: 'New title' }, ...]\n\n// reindex() accepts any fresh object carrying the key:\nindex.reindex({ id: 7, title: 'Retitled' });\n\n// Or delete by key directly, without fabricating a Product:\nindex.removeKey(7);\n```\n\nTwo different objects that share one key — inside a single `setItems()` call or the initial `createIndex()` corpus — throw `ScoutConfigError`. Search results always return the latest object stored for each key.\n\n### Replacing a refreshed corpus\n\n```ts\nconst latestProducts = await loadProducts();\n\nindex.setItems(latestProducts);\n```\n\n`setItems()` removes keys absent from `latestProducts`, indexes new keys, reindexes retained keys against their incoming objects, and adopts the incoming order. It notifies `subscribe()` listeners once, only when index membership, field text, or order changed.\n\n### Inspecting the corpus\n\nUse `.items` to read all currently indexed items in insertion order, or `.size` for a count:\n\n```ts\nconsole.log(index.size); // 42\nconsole.log(index.items); // [{ id: 1, title: ... }, ...]\n```\n\n### Reacting to mutations directly\n\n`createSearch()` already keeps `results` in sync with `add()`/`remove()`/`reindex()`/`setItems()` internally. `toSearchMatcher()` also invalidates its query cache after index mutation. If you're building your own reactivity on top of a plain `ScoutIndex` (no `ripple` involved), subscribe with `subscribe()`:\n\n```ts\nconst unsubscribe = index.subscribe(() => {\n rerenderResultsList();\n});\n\nindex.add(newProduct); // triggers rerenderResultsList()\n\nunsubscribe(); // when done\n```\n\n`subscribe()` only fires for mutations that actually change the index: a duplicate `add()` or a `remove()` of an unindexed item is a no-op and doesn't notify listeners.\n\n## Match Highlighting\n\nEvery `SearchResult` carries `matches`: per-field literal `[start, end)` ranges into the original field value. A fuzzy trigram candidate can have `matches: []` when no literal query text appears in its field value.\n\n### `highlightField()`: recommended\n\n`highlightField(result, field, text)` is the shorthand that does the field lookup and fragment split in one step:\n\n```ts\nimport { highlightField } from '@vielzeug/scout';\n\nfor (const result of index.search('alice')) {\n const parts = highlightField(result, 'name', result.item.name);\n // [{ text: 'Alice', highlighted: true }, { text: ' Johnson', highlighted: false }]\n renderHighlightedText(parts);\n}\n```\n\n::: warning `part.text` is unescaped\n`highlight()` / `highlightField()` return the **original, unescaped** field text split into\nfragments: never concatenate `part.text` into an HTML string for `innerHTML`. Render each\npart as text (`textContent`, a framework's text binding) and wrap `highlighted` parts in your\nown element:\n\n```ts\nfunction renderHighlightedText(parts: HighlightPart[]): DocumentFragment {\n const fragment = document.createDocumentFragment();\n\n for (const part of parts) {\n if (part.highlighted) {\n const mark = document.createElement('mark');\n\n mark.textContent = part.text; // textContent: never innerHTML\n fragment.appendChild(mark);\n } else {\n fragment.appendChild(document.createTextNode(part.text));\n }\n }\n\n return fragment;\n}\n```\n\n:::\n\n### `findMatchRanges()` + `highlight()`: manual\n\nUse `findMatchRanges()` when you need to apply match ranges to a different string than the indexed field value: for example a truncated preview or a differently formatted display string:\n\n```ts\nimport { findMatchRanges, highlight } from '@vielzeug/scout';\n\nconst [result] = index.search('alice');\nconst preview = result.item.bio.slice(0, 100);\nconst ranges = findMatchRanges(preview, 'alice');\nconst parts = highlight(preview, ranges);\n```\n\nOr use `highlight()` directly when you already have the ranges from `result.matches`:\n\n```ts\nconst [result] = index.search('alice');\nconst nameMatch = result.matches.find((m) => m.field === 'name');\nconst parts = highlight(result.item.name, nameMatch?.ranges ?? []);\n```\n\n## Searchable Reference Lists\n\nA glossary or compendium mixes entry kinds and needs direct-match ranking above fuzzy hits. Rank with `rankEntries`, render keyword links with `splitPattern`, and highlight the typed query with `findMatchRanges` + `highlight`.\n\n```ts\nimport { dedupeEntries, escapeRegExp, findMatchRanges, highlight, rankEntries, splitPattern } from '@vielzeug/scout';\n\nconst keywordPattern = new RegExp(`(${keywords.map((k) => escapeRegExp(k.name)).join('|')})`, 'g');\nconst results = rankEntries(entries, query, { fuzzyIds: fuzzyIndexIds });\n\nfor (const entry of results) {\n for (const segment of splitPattern(entry.text, keywordPattern)) {\n if (segment.matched) renderKeywordLink(segment.text);\n else for (const part of highlight(segment.text, findMatchRanges(segment.text, query))) renderMark(part);\n }\n}\n```\n\nDedupe merged catalogs with `dedupeEntries` before ranking so alias rows do not shadow their originals.\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { createIndex, createSearch } from '@vielzeug/scout';\nimport { useEffect, useMemo, useSyncExternalStore } from 'react';\n\ntype User = { id: number; name: string; email: string };\n\nfunction useScoutSearch(items: User[]) {\n const search = useMemo(() => {\n const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });\n\n return createSearch(index, { debounce: 150 });\n }, [items]);\n const snapshot = useSyncExternalStore(search.subscribe, search.getSnapshot, search.getSnapshot);\n\n useEffect(() => () => search.dispose(), [search]);\n\n return { ...snapshot, setQuery: search.setQuery };\n}\n```\n\n```ts [Vue 3]\nimport { createIndex, createSearch } from '@vielzeug/scout';\nimport { onScopeDispose, shallowRef } from 'vue';\n\ntype User = { id: number; name: string; email: string };\n\nfunction useScoutSearch(items: User[]) {\n const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });\n const search = createSearch(index, { debounce: 150 });\n const snapshot = shallowRef(search.getSnapshot());\n const stop = search.subscribe(() => {\n snapshot.value = search.getSnapshot();\n });\n\n onScopeDispose(() => {\n stop();\n search.dispose();\n });\n\n return { search, snapshot };\n}\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { createIndex, createSearch } from '@vielzeug/scout';\n import { onDestroy } from 'svelte';\n\n type User = { id: number; name: string; email: string };\n\n export let items: User[];\n\n const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });\n const search = createSearch(index, { debounce: 150 });\n let snapshot = search.getSnapshot();\n const stop = search.subscribe(() => { snapshot = search.getSnapshot(); });\n\n onDestroy(() => { stop(); search.dispose(); });\n</script>\n\n<input value={snapshot.query} on:input={(event) => search.setQuery(event.currentTarget.value)} placeholder=\"Search…\" />\n{#each snapshot.results as { item }}\n <p>{item.name}</p>\n{/each}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Sourcerer\n\n`toSearchMatcher()` adapts a `ScoutIndex` into Sourcerer's local-source filter.\n\n```ts\nimport { createIndex, toSearchMatcher } from '@vielzeug/scout';\nimport { createLocalSource } from '@vielzeug/sourcerer';\n\nconst index = createIndex(users, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n});\nconst source = createLocalSource(users, { filter: toSearchMatcher(index), params: '' });\n\nsource.setParams('alice');\nconsole.log(source.state.items);\n```\n\n> Update the index and source from the same collection change. Use `index.setItems(items)` with `source.setItems(items)` for replacement collections.\n\n### With Vault\n\n`toFilterPredicate()` returns an `(item: T) => boolean` snapshot predicate: pass it to vault's `query.filter()` or plain `Array.filter`.\n\n```ts\nimport { createIndex, toFilterPredicate } from '@vielzeug/scout';\n\nconst index = createIndex(products, { fields: ['title', 'sku'] });\n\nconst matching = products.filter(toFilterPredicate(index, 'widget'));\n\nconst rows = await db.query('products').filter(toFilterPredicate(index, searchTerm)).toArray();\n```\n\nCall `toFilterPredicate` again whenever the query or corpus changes: the predicate is a snapshot, not reactive.\n\n## Best Practices\n\n- **Build the index once**: `createIndex()` runs in O(corpus × field_length). Create it at module level or in an effect, not inside render loops.\n- **Keep the index in sync**: call `index.add()` / `remove()` / `reindex()` when items mutate, or `index.setItems()` with the refreshed collection. Stale index entries return wrong scores.\n- **Set a `key` for immutable data**: when updates create fresh objects, `key: (item) => item.id` lets `setItems()` skip unchanged items and `removeKey()` delete by id.\n- **Tune threshold before limit**: set a meaningful `threshold` (e.g. `0.25–0.4`) to suppress noise, then use `limit` to cap the list length.\n- **Set `minQueryLength` for your corpus size**: the default `3` works well for most cases. Lower it for small corpora where single-char queries are expected; raise it for large corpora to avoid expensive O(n) scans.\n- **Dispose reactive state**: always call `search.dispose()` or use `using` when the component unmounts.\n- **Weight by importance**: name/title fields should have weight `2–3`; secondary fields (description, tags) stay at `1`.\n- **Segment CJK/Thai fields explicitly**: `segmentWords()` is opt-in per field, not automatic, to keep `createIndex()` fast for the common whitespace-delimited case.\n",
7
7
  "examples": "---\ntitle: 'Scout: Examples'\ndescription: 'Practical examples for @vielzeug/scout: basic search, reactive combobox, and sourcerer integration.'\n---\n\n## Examples\n\n- [Basic Search](./examples/basic-search)\n- [Reactive Combobox](./examples/reactive-combobox)\n- [Sourcerer Integration](./examples/sourcerer-integration)\n"
8
8
  },
9
9
  "examples": [
@@ -19,12 +19,12 @@
19
19
  },
20
20
  {
21
21
  "id": "incremental-updates",
22
- "code": "import { createIndex } from '@vielzeug/scout'\n\nconst products = [\n { id: 1, title: 'Wireless Mouse', price: 25 },\n { id: 2, title: 'Mechanical Keyboard', price: 80 },\n { id: 3, title: 'USB-C Hub', price: 35 },\n]\n\nconst index = createIndex(products, { fields: ['title'] })\n\n// onMutate() fires after changed add()/remove()/reindex()/setItems() operations :\n// not on no-ops like removing an item that isn't indexed\nconst unsubscribe = index.onMutate(() => {\n console.log(` (index changed: now ${index.size} items)`)\n})\n\nconsole.log('Search \"keyboard\":', index.search('keyboard').map(r => r.item.title))\n\n// Add a newly created item\nindex.add({ id: 4, title: 'Gaming Keyboard', price: 120 })\nconsole.log('After add():', index.search('keyboard').map(r => r.item.title))\n\n// Re-index a mutated item: reference equality, so mutate in place first\nproducts[0].title = 'Wireless Trackball'\nindex.reindex(products[0])\nconsole.log('After reindex():', index.search('trackball').map(r => r.item.title))\n\n// Reconcile a refreshed corpus in one mutation: removes missing references,\n// adds new ones, reindexes retained values, and preserves this incoming order\nindex.setItems([products[0], { id: 4, title: 'Portable SSD', price: 95 }])\nconsole.log('After setItems():', index.items.map(item => item.title))\n\nunsubscribe()",
22
+ "code": "import { createIndex } from '@vielzeug/scout'\n\nconst products = [\n { id: 1, title: 'Wireless Mouse', price: 25 },\n { id: 2, title: 'Mechanical Keyboard', price: 80 },\n { id: 3, title: 'USB-C Hub', price: 35 },\n]\n\nconst index = createIndex(products, { fields: ['title'] })\n\n// subscribe() fires after changed add()/remove()/reindex()/setItems() operations :\n// not on no-ops like removing an item that isn't indexed\nconst unsubscribe = index.subscribe(() => {\n console.log(` (index changed: now ${index.size} items)`)\n})\n\nconsole.log('Search \"keyboard\":', index.search('keyboard').map(r => r.item.title))\n\n// Add a newly created item\nindex.add({ id: 4, title: 'Gaming Keyboard', price: 120 })\nconsole.log('After add():', index.search('keyboard').map(r => r.item.title))\n\n// Re-index a mutated item: items default to reference identity, so mutate in place first\n// (with a key option, a fresh copy with the same key works too)\nproducts[0].title = 'Wireless Trackball'\nindex.reindex(products[0])\nconsole.log('After reindex():', index.search('trackball').map(r => r.item.title))\n\n// Reconcile a refreshed corpus in one mutation: removes missing references,\n// adds new ones, reindexes retained values, and preserves this incoming order\nindex.setItems([products[0], { id: 4, title: 'Portable SSD', price: 95 }])\nconsole.log('After setItems():', index.items.map(item => item.title))\n\nunsubscribe()",
23
23
  "name": "Incremental Updates"
24
24
  },
25
25
  {
26
26
  "id": "reactive-search",
27
- "code": "import { createReactiveSearch } from '@vielzeug/scout'\n\nconst users = [\n { name: 'Alice Johnson', email: 'alice@example.com' },\n { name: 'Bob Smith', email: 'bob@example.com' },\n { name: 'Charlie Brown', email: 'charlie@example.com' },\n { name: 'Alicia Keys', email: 'alicia@example.com' },\n]\n\n// One call creates the index and the reactive search state together\nconst search = createReactiveSearch(users, { fields: ['name', 'email'], debounce: 0 })\n\nconst show = (label) => {\n console.log(label, '\\u2192', search.getSnapshot().results.map(r => r.item.name).join(', ') || '(none)')\n}\n\nshow('Empty query') // all 4 users\n\nsearch.setQuery('ali')\nshow('Query: \"ali\"') // Alice Johnson, Alicia Keys, Dave Alison\n\nsearch.setQuery('alice')\nshow('Query: \"alice\"') // Alice Johnson\n\n// Add a new user at runtime via the exposed index\nsearch.index.add({ name: 'Alice Cooper', email: 'cooper@example.com' })\nshow('After add()') // now includes Alice Cooper\n\nsearch.clear()\nshow('After clear()') // all 5 users\n\nsearch.dispose()\nconsole.log('Disposed:', search.disposed)",
27
+ "code": "import { createIndex, createSearch } from '@vielzeug/scout'\n\nconst users = [\n { name: 'Alice Johnson', email: 'alice@example.com' },\n { name: 'Bob Smith', email: 'bob@example.com' },\n { name: 'Charlie Brown', email: 'charlie@example.com' },\n { name: 'Alicia Keys', email: 'alicia@example.com' },\n]\n\n// The index holds the corpus; the search store keeps one snapshot in sync with it\nconst index = createIndex(users, { fields: ['name', 'email'] })\nconst search = createSearch(index, { debounce: 0 })\n\nconst show = (label) => {\n console.log(label, '\\u2192', search.getSnapshot().results.map(r => r.item.name).join(', ') || '(none)')\n}\n\nshow('Empty query') // all 4 users\n\nsearch.setQuery('ali')\nshow('Query: \"ali\"') // Alice Johnson, Alicia Keys, Dave Alison\n\nsearch.setQuery('alice')\nshow('Query: \"alice\"') // Alice Johnson\n\n// Add a new user at runtime: the search state re-runs the committed query\nindex.add({ name: 'Alice Cooper', email: 'cooper@example.com' })\nshow('After add()') // now includes Alice Cooper\n\nsearch.clear()\nshow('After clear()') // all 5 users\n\nsearch.dispose()\nconsole.log('Disposed:', search.disposed)",
28
28
  "name": "Reactive Search"
29
29
  },
30
30
  {
@@ -48,22 +48,19 @@
48
48
  "findMatchRanges": "export { findMatchRanges, highlight, highlightField } from './highlight';",
49
49
  "highlight": "export { findMatchRanges, highlight, highlightField } from './highlight';",
50
50
  "highlightField": "export { findMatchRanges, highlight, highlightField } from './highlight';",
51
- "ReactiveSearch": "export type { ReactiveSearch } from './reactive';",
52
- "createReactiveSearch": "export { createReactiveSearch, createSearch } from './reactive';",
53
- "createSearch": "export { createReactiveSearch, createSearch } from './reactive';",
51
+ "createSearch": "export { createSearch } from './reactive';",
54
52
  "ScoutIndex": "export type { ScoutIndex } from './scout-index';",
55
53
  "createIndex": "export { createIndex } from './scout-index';",
56
54
  "segmentWords": "export { segmentWords } from './segment';",
57
- "CreateSearchOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
58
- "FieldDef": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
59
- "FieldMatch": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
60
- "HighlightPart": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
61
- "ScoutEvent": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
62
- "ScoutIndexOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
63
- "SearchConstraints": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
64
- "SearchResult": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
65
- "SearchSnapshot": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
66
- "SearchState": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
67
- "SearchSubscribeOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';"
55
+ "CreateSearchOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
56
+ "FieldDef": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
57
+ "FieldMatch": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
58
+ "HighlightPart": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
59
+ "ScoutIndexOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
60
+ "SearchConstraints": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
61
+ "SearchResult": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
62
+ "SearchSnapshot": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
63
+ "SearchState": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
64
+ "SearchSubscribeOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';"
68
65
  }
69
66
  }