@svgrid/mcp 3.0.27 → 3.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/data.js CHANGED
@@ -2483,7 +2483,7 @@ export const examples = [
2483
2483
  "id": "430-selection-bar",
2484
2484
  "path": "examples/src/demos/430-selection-bar.svelte",
2485
2485
  "title": "Selection Bar",
2486
- "category": "Selection & Clipboard",
2486
+ "category": "Misc",
2487
2487
  "blurb": "430. Bulk-action bar over the selection Tick some rows and a bar floats over the grid with the count, the actions that apply to the whole selection, and a way to clear it.",
2488
2488
  "source": "<script lang=\"ts\">\n /**\n * 430. Bulk-action bar over the selection\n * ---------------------------------------\n * Tick some rows and a bar floats over the grid with the count, the actions\n * that apply to the whole selection, and a way to clear it.\n *\n * selectionBar={true} count + Clear, nothing else\n * selectionBar={[...]} built-in keys and/or your own buttons\n * selectionBar={{ ... }} also position / maxVisible / hideClear\n *\n * Built-in keys need no wiring: 'selectAll' selects the view, 'editFields'\n * opens the bulk-edit DRAWER, and 'separator' draws a divider.\n *\n * The drawer is the same SvDrawer + SvForm used for single-row editing, and\n * it edits ONE OR MORE fields across ONE OR MORE rows at once. Only fields\n * you actually change are written: a field the selection already agrees on\n * opens showing that value, one they disagree on opens blank and labelled\n * \"Multiple values\", and leaving either alone keeps every row's own value.\n *\n * The bar reserves its own strip: the grid shrinks by the bar height while\n * a selection is live, so it never covers the rows you are acting on.\n *\n * Your own actions get `{ rows, ids }` for the selection in DISPLAY order,\n * and `hidden` / `disabled` are re-checked every render - which is what lets\n * Merge appear only at 2+ rows and Mark done grey out once everything picked\n * is already closed.\n *\n * Compare with demo 23, which hand-rolls the same idea from\n * `onRowSelectionChange` and a toolbar of your own. This is that pattern\n * built in.\n *\n * The PROP is free; the bar is Pro. Without @svgrid/enterprise the grid shows\n * an upsell note in its place.\n */\n import {\n SvGrid,\n tableFeatures,\n rowSortingFeature,\n rowSelectionFeature,\n columnFilteringFeature,\n type GridColumns,\n type SelectionBarAction,\n type SvGridApi,\n } from '@svgrid/grid'\n import { installEnterprise } from '@svgrid/enterprise'\n\n // The bar is a Pro renderer. installEnterprise() registers it (along with the\n // rest of the Pro surface) the moment the grid hands us its api.\n\n type Task = {\n id: number\n key: string\n title: string\n assignee: string\n status: Status\n priority: Priority\n labels: string[]\n points: number\n due: string\n }\n\n type Status = 'Open' | 'In progress' | 'In review' | 'Done'\n type Priority = 'Low' | 'Medium' | 'High' | 'Urgent'\n\n const PEOPLE = ['A. Osei', 'R. Vance', 'M. Iqbal', 'J. Lindqvist', 'D. Okonkwo']\n const STATUSES: Status[] = ['Open', 'In progress', 'In review', 'Done']\n const PRIORITIES: Priority[] = ['Low', 'Medium', 'High', 'Urgent']\n const LABELS = ['perf', 'infra', 'billing', 'a11y', 'tech-debt', 'security', 'ui']\n const TITLES = [\n 'Virtualize the audit log',\n 'Retry webhook delivery',\n 'Cache the tenant lookup',\n 'Fix timezone drift on export',\n 'Batch the settings writes',\n 'Debounce the search input',\n 'Backfill missing invoice ids',\n 'Split the migration runner',\n 'Trim the bundle preamble',\n 'Harden the CSV importer',\n ]\n\n /** Deterministic so the demo reads the same on every load and in snapshots. */\n const dayOffset = (i: number, span: number) => ((i * 7) % span) - Math.floor(span / 3)\n const iso = (days: number) => {\n const d = new Date(2026, 8, 15)\n d.setDate(d.getDate() + days)\n return d.toISOString().slice(0, 10)\n }\n\n const start = (): Task[] =>\n Array.from({ length: 24 }, (_, i) => ({\n id: i + 1,\n key: `PLAT-${412 + i}`,\n title: TITLES[i % TITLES.length],\n assignee: PEOPLE[i % PEOPLE.length],\n status: STATUSES[i % STATUSES.length],\n priority: PRIORITIES[(i * 3) % PRIORITIES.length],\n // One or two labels, so the chips column has some variety of width.\n labels: i % 3 === 0\n ? [LABELS[i % LABELS.length], LABELS[(i + 3) % LABELS.length]]\n : [LABELS[i % LABELS.length]],\n points: [1, 2, 3, 5, 8][i % 5],\n due: iso(dayOffset(i, 30)),\n }))\n\n let tasks = $state<Task[]>(start())\n let api = $state<SvGridApi<typeof features, Task> | null>(null)\n let position = $state<'bottom' | 'top'>('bottom')\n let lastAction = $state('')\n\n const note = (line: string) => (lastAction = line)\n\n function patch(ids: string[], change: Partial<Task>) {\n const set = new Set(ids)\n tasks = tasks.map((t) => (set.has(String(t.id)) ? { ...t, ...change } : t))\n }\n\n const features = tableFeatures({ rowSortingFeature, rowSelectionFeature, columnFilteringFeature })\n\n // Strings are built-ins, objects are this app's own. An issue tracker's bar\n // is mostly the former.\n // Strings are built-ins, objects are this app own.\n //\n // Order matters: the overflow menu takes the TAIL, so the actions that\n // belong on the bar go first. Select all / Edit fields / Delete are the ones\n // a user reaches for on any list; Mark done, Merge and Export are this\n // tracker specific extras, so they sit behind the \"...\" menu rather than\n // pushing the essentials off the bar.\n const actions: Array<SelectionBarAction<Task> | 'selectAll' | 'editFields' | 'separator'> = [\n 'selectAll',\n 'editFields',\n 'separator',\n {\n key: 'delete',\n label: 'Delete',\n icon: 'M3 6h18M8 6V4h8v2m-1 0v14H9V6',\n danger: true,\n action: ({ ids }) => {\n const set = new Set(ids)\n tasks = tasks.filter((t) => !set.has(String(t.id)))\n api?.selectRows([])\n note(`Deleted ${ids.length} task${ids.length === 1 ? '' : 's'}`)\n },\n },\n {\n key: 'done',\n label: 'Mark done',\n icon: 'M20 6 9 17l-5-5',\n disabled: ({ rows }) => rows.every((t) => t.status === 'Done'),\n action: ({ rows, ids }) => {\n patch(ids, { status: 'Done' })\n note(`Marked ${rows.length} done`)\n },\n },\n {\n key: 'merge',\n label: 'Merge',\n icon: 'M7 3v12a4 4 0 0 0 4 4h6M17 15l3 4-3 4',\n hidden: ({ ids }) => ids.length < 2,\n action: ({ ids }) => note(`Merged ${ids.length} tasks into ${ids[0]}`),\n },\n {\n key: 'export',\n label: 'Export',\n icon: 'M12 3v12m0 0 4-4m-4 4-4-4M4 21h16',\n action: ({ ids }) => note(`Exported ${ids.length} to CSV`),\n },\n ]\n\n // Widths total ~975px so the set FITS a normal demo pane; `fitColumns` then\n // scales them up to fill it exactly. It only grows - size them past the pane\n // and you get a horizontal scrollbar and a clipped last column instead.\n const columns: GridColumns<Task> = [\n // Read-only: an issue key is not something anyone bulk-edits, and an\n // editable column shows up in the drawer.\n { field: 'key', header: 'Key', width: 80, editable: false },\n { field: 'title', header: 'Summary', width: 220 },\n {\n field: 'status',\n header: 'Status',\n width: 118,\n editorType: 'list',\n editorOptions: STATUSES.map((v) => ({ value: v, label: v })),\n // A value-driven class is all a status pill needs - no cell renderer.\n cellClass: ({ row }) => `cell-status cell-status-${String(row.original.status).toLowerCase().replace(/ /g, '-')}`,\n },\n {\n field: 'priority',\n header: 'Priority',\n width: 100,\n editorType: 'list',\n editorOptions: PRIORITIES.map((v) => ({ value: v, label: v })),\n cellClass: ({ row }) => `cell-prio cell-prio-${String(row.original.priority).toLowerCase()}`,\n },\n {\n field: 'assignee',\n header: 'Assignee',\n width: 125,\n editorType: 'list',\n editorOptions: PEOPLE.map((v) => ({ value: v, label: v })),\n },\n {\n // Chips render as tokens outside editing, and the drawer offers the same\n // picker - so labels are bulk-editable like anything else.\n field: 'labels',\n header: 'Labels',\n width: 165,\n editorType: 'chips',\n editorMultiple: true,\n editorOptions: LABELS.map((v) => ({ value: v, label: v })),\n },\n {\n field: 'due',\n header: 'Due',\n width: 105,\n cellDataType: 'dateString',\n // Overdue and still open is the one thing worth colouring in a backlog.\n cellClass: ({ row }) =>\n row.original.status !== 'Done' && row.original.due < iso(0) ? 'overdue' : '',\n },\n { field: 'points', header: 'Points', width: 90, align: 'right', editorType: 'number' },\n ]\n</script>\n\n<section class=\"wrap\">\n <header class=\"chrome\">\n <p class=\"hint\">\n Tick a row, then use the bar. <strong>Edit fields</strong> opens the drawer - change several\n fields at once and they apply to every selected row. This tracker&rsquo;s own extras (Mark done,\n Merge, Export) sit behind the <em>&middot;&middot;&middot;</em> menu.\n </p>\n <div class=\"controls\">\n {#if lastAction}\n <span class=\"pill\">{lastAction}</span>\n {/if}\n <div class=\"seg\" role=\"group\" aria-label=\"Bar position\">\n <button class:on={position === 'bottom'} onclick={() => (position = 'bottom')}>Bottom</button>\n <button class:on={position === 'top'} onclick={() => (position = 'top')}>Top</button>\n </div>\n <button\n class=\"ghost\"\n onclick={() => { tasks = start(); lastAction = ''; api?.selectRows([]) }}\n >Reset</button>\n </div>\n </header>\n\n <div class=\"grid-host\">\n <SvGrid responsive={true}\n data={tasks}\n columns={columns}\n features={features}\n getRowId={(t) => String(t.id)}\n showRowSelection\n editable\n selectionBar={{ actions, position, maxVisible: 3 }}\n filterMode=\"row\"\n rowHeight={38}\n containerHeight=\"100%\"\n fitColumns\n onApiReady={(next) => (api = installEnterprise(next))}\n />\n </div>\n</section>\n\n<style>\n .wrap {\n display: flex;\n flex-direction: column;\n flex: 1;\n min-height: 0;\n gap: 12px;\n }\n\n /* One row of chrome instead of a wall of KPI cards and a side rail - this\n demo is about the bar, so the grid gets the space. */\n .chrome {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n flex-wrap: wrap;\n flex: none;\n }\n .hint {\n margin: 0;\n font-size: 13px;\n line-height: 1.5;\n color: var(--sg-muted, #64748b);\n max-width: 62ch;\n }\n .hint strong { color: var(--sg-fg, #0f172a); font-weight: 600; }\n\n .controls { display: flex; align-items: center; gap: 8px; }\n\n .pill {\n padding: 4px 10px;\n border-radius: 999px;\n background: color-mix(in srgb, var(--sg-accent, #6366f1) 12%, transparent 88%);\n color: var(--sg-accent, #6366f1);\n font-size: 12px;\n font-weight: 600;\n white-space: nowrap;\n }\n\n .seg {\n display: inline-flex;\n border: 1px solid var(--sg-border, #cbd5e1);\n border-radius: 7px;\n overflow: hidden;\n }\n .seg button {\n border: 0;\n background: var(--sg-bg, #fff);\n color: var(--sg-muted, #64748b);\n padding: 5px 12px;\n font: inherit;\n font-size: 12px;\n font-weight: 600;\n cursor: pointer;\n }\n .seg button.on { background: var(--sg-accent, #6366f1); color: var(--sg-on-accent, #fff); }\n\n .ghost {\n border: 1px solid var(--sg-border, #cbd5e1);\n border-radius: 7px;\n background: var(--sg-bg, #fff);\n color: var(--sg-fg, #0f172a);\n padding: 5px 12px;\n font: inherit;\n font-size: 12px;\n font-weight: 600;\n cursor: pointer;\n }\n .ghost:hover { background: var(--sg-row-hover-bg, rgb(148 163 184 / 12%)); }\n\n .grid-host { flex: 1; min-height: 0; }\n\n /*\n * Status / priority / due styling.\n *\n * `cellClass` puts the class on the cell, so these have to be :global - the\n * grid renders the cell, not this component, and Svelte would otherwise\n * scope the selector away.\n *\n * Backgrounds are color-mix over the theme tokens rather than fixed hexes,\n * so a status pill still reads on every one of the 20 preset themes instead\n * of only the one it was designed against.\n */\n .grid-host :global(.cell-status) { font-weight: 600; }\n .grid-host :global(.cell-status-open) { color: var(--sg-muted, #64748b); }\n .grid-host :global(.cell-status-in-progress) { color: var(--sg-accent, #6366f1); }\n .grid-host :global(.cell-status-in-review) { color: #d97706; }\n .grid-host :global(.cell-status-done) { color: #16a34a; }\n\n .grid-host :global(.cell-prio) { font-weight: 600; }\n .grid-host :global(.cell-prio-low) { color: var(--sg-muted, #64748b); }\n .grid-host :global(.cell-prio-medium) { color: var(--sg-fg, #0f172a); }\n .grid-host :global(.cell-prio-high) { color: #d97706; }\n .grid-host :global(.cell-prio-urgent) { color: var(--sg-danger, #dc2626); }\n\n /* Overdue AND unfinished. A past due date on a closed item is not a problem,\n so colouring it would be noise. */\n .grid-host :global(.overdue) {\n color: var(--sg-danger, #dc2626);\n font-weight: 600;\n }\n\n @media (max-width: 720px) {\n .chrome { align-items: flex-start; }\n .controls { width: 100%; justify-content: space-between; }\n }\n</style>\n"
2489
2489
  },
@@ -4047,6 +4047,30 @@ export const examples = [
4047
4047
  "blurb": "700. An AI agent and your team, one table A support inbox in SvGrid Base, its tickets in a real Postgres database (PGlite, Postgres compiled to WebAssembly, running in this page).",
4048
4048
  "source": "<script lang=\"ts\">\n /**\n * 700. An AI agent and your team, one table\n * -----------------------------------------\n * A support inbox in SvGrid Base, its tickets in a real Postgres database\n * (PGlite, Postgres compiled to WebAssembly, running in this page).\n *\n * \"Run the triage agent\" writes to the database, not to the page: for each\n * new ticket an UPDATE sets its category, priority, a draft reply, Review\n * to \"Needs review\", and `modified_by` to the agent. The log under the base\n * lists each statement. The base hears of the writes through the source's\n * `realtime` hook (with Supabase, `createSupabaseRealtime`), reads the\n * table again, and shows what moved:\n * - the cells the agent changed are tinted, and the row has a dot, until\n * someone opens the record;\n * - the view bar says \"10 changed by Triage agent\"; a click marks them seen;\n * - the record's Activity says \"Triage agent changed Priority\", with the\n * value before, crossed out, and the value now. Who made a change is read\n * from the row's \"last modified by\" field (`modified_by`).\n *\n * Then people review it. \"Needs review\" is a view filtered on Review. The\n * agent gets one wrong on purpose: \"can't wait for Excel export\" is a\n * feature request, not an urgent login problem. Set it right; your edit is\n * written with `modified_by` = you. Approve runs an automation that sets\n * Review to Approved, and the record leaves the view.\n *\n * The agent here is a stand-in: keyword rules, so the demo runs without a\n * model or a key. A real one (Claude Code with the Supabase MCP server, a\n * worker calling a model) writes the same UPDATE, and the base shows it the\n * same way.\n */\n import { onMount } from 'svelte'\n import { PGlite } from '@electric-sql/pglite'\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, baseSource, enableBase, setFieldUsers, type BaseAutomation, type BaseTable, type FieldUser } from '@svgrid/enterprise/base'\n import { createSqlDataSource, type EntitySchema } from '@svgrid/enterprise'\n import { PEOPLE, usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n // The agent is a person the base can name: its id is what it writes to modified_by.\n const BOT = `data:image/svg+xml,${encodeURIComponent('<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 40 40\"><rect width=\"40\" height=\"40\" rx=\"20\" fill=\"#0f766e\"/><rect x=\"10\" y=\"13\" width=\"20\" height=\"16\" rx=\"5\" fill=\"#ccfbf1\"/><circle cx=\"16\" cy=\"21\" r=\"2.4\" fill=\"#0f766e\"/><circle cx=\"24\" cy=\"21\" r=\"2.4\" fill=\"#0f766e\"/><rect x=\"18.5\" y=\"7\" width=\"3\" height=\"6\" rx=\"1.5\" fill=\"#ccfbf1\"/></svg>')}`\n const AGENT: FieldUser = { id: 'agent', name: 'Triage agent', avatarUrl: BOT }\n\n // ---- The database -----------------------------------------------------------\n\n const TICKETS: Array<[string, string, string]> = [\n ['Charged twice for October', 'mira@northwind.example', 'My card shows two charges for the October invoice.'],\n [\"Can't log in after a password reset\", 'tom@contoso.example', 'The reset link worked, but the new password is refused.'],\n ['Export to PDF cuts off the last column', 'li@fabrikam.example', 'Wide tables lose their last column in the PDF.'],\n ['Please add dark mode to the mobile app', 'sara@litware.example', 'Our team works night shifts.'],\n ['Invoice shows the wrong VAT number', 'jon@adatum.example', 'The VAT number on invoice 2291 is our old one.'],\n [\"Love the new export, can't wait for Excel export\", 'eva@tailspin.example', 'CSV works great for us. Any plans for .xlsx?'],\n ['The site is down for our whole team', 'raj@woodgrove.example', 'Every page returns an error since 9:10.'],\n ['How do I add a teammate?', 'ana@proseware.example', 'We hired someone and want to give them access.'],\n ['Refund for unused seats', 'kim@fourth.example', 'We removed 5 seats mid-month.'],\n ['Dashboard is slow with 50k rows', 'ola@wingtip.example', 'It takes several seconds to open since we imported last year.'],\n ]\n\n const SCHEMA = `\n create table tickets (\n id text primary key,\n subject text not null default '',\n customer text,\n message text,\n received timestamptz,\n category text,\n priority text,\n reply text,\n review text,\n assignee text,\n modified_by text\n );\n insert into tickets (id, subject, customer, message, received, priority, modified_by) values\n ${TICKETS.map(([s, c, m], i) => `('k${i + 1}', '${s.replace(/'/g, \"''\")}', '${c}', '${m.replace(/'/g, \"''\")}', now() - interval '${(i + 1) * 17} minutes', 'Normal', 'u2')`).join(',\\n ')};\n `\n const schema: EntitySchema = {\n name: 'tickets',\n idField: 'id',\n fields: [\n { field: 'id', type: 'text', primaryKey: true },\n ...['subject', 'customer', 'message', 'category', 'priority', 'reply', 'review', 'assignee', 'modified_by'].map((field) => ({ field, type: 'text' as const })),\n { field: 'received', type: 'datetime' },\n ],\n }\n\n let db: PGlite\n let ready = $state(false)\n let failed = $state('')\n\n // Every statement the agent ran, for the log.\n type Entry = { n: number; sql: string; params: unknown[] }\n let log = $state<Entry[]>([])\n let n = 0\n async function run(sql: string, params: unknown[] = [], who: 'base' | 'agent' = 'base') {\n const res = await db.query(sql, params)\n if (who === 'agent') log = [{ n: ++n, sql, params }, ...log].slice(0, 30)\n return res.rows as Record<string, unknown>[]\n }\n\n // The realtime feed: a write that reaches the database tells every base listening.\n const listeners = new Set<() => void>()\n const realtime = (onChange: () => void) => {\n listeners.add(onChange)\n return () => listeners.delete(onChange)\n }\n\n // ---- The base ------------------------------------------------------------------\n\n const CATEGORY = [\n { value: 'Billing', color: '#7c3aed' },\n { value: 'Bug', color: '#dc2626' },\n { value: 'Account', color: '#2563eb' },\n { value: 'Feature request', color: '#0d9488' },\n ]\n const PRIORITY = [\n { value: 'Urgent', color: '#dc2626' },\n { value: 'High', color: '#ea580c' },\n { value: 'Normal', color: '#2563eb' },\n { value: 'Low', color: '#64748b' },\n ]\n const REVIEW = [\n { value: 'Needs review', color: '#d97706' },\n { value: 'Approved', color: '#16a34a' },\n ]\n\n const AUTOMATIONS: BaseAutomation[] = [\n {\n id: 'approve',\n name: 'Approve the triage',\n enabled: true,\n trigger: { type: 'button', field: 'approve' },\n actions: [\n { type: 'updateRecord', values: { review: 'Approved' } },\n { type: 'notify', message: 'Approved: {Subject}', severity: 'success' },\n ],\n },\n ]\n\n const needsReview = { kind: 'fieldFilter' as const, conjunction: 'and' as const, conditions: [{ column: 'review', kind: 'select' as const, op: 'is' as const, value: 'Needs review' }] }\n\n function build(): BaseTable[] {\n return [\n {\n id: 'tickets',\n name: 'Tickets',\n primaryField: 'subject',\n data: [],\n columns: [\n { field: 'subject', header: 'Subject', width: 260, fieldType: 'text' },\n { field: 'category', header: 'Category', width: 140, fieldType: 'singleSelect', fieldProps: { options: CATEGORY } },\n { field: 'priority', header: 'Priority', width: 110, fieldType: 'singleSelect', fieldProps: { options: PRIORITY } },\n { field: 'review', header: 'Review', width: 130, fieldType: 'singleSelect', fieldProps: { options: REVIEW } },\n { field: 'approve', header: 'Approve', width: 100, fieldType: 'button', fieldProps: { label: 'Approve', color: '#16a34a' } },\n { field: 'reply', header: 'Draft reply', width: 300, fieldType: 'longText' },\n { field: 'modified_by', header: 'Last changed by', width: 160, fieldType: 'lastModifiedBy' },\n { field: 'customer', header: 'Customer', width: 200, fieldType: 'email' },\n { field: 'message', header: 'Message', width: 300, fieldType: 'longText' },\n { field: 'assignee', header: 'Assignee', width: 150, fieldType: 'user' },\n { field: 'received', header: 'Received', width: 170, fieldType: 'date', fieldProps: { dateFormat: 'friendly', time: true } },\n ],\n views: [\n { id: 'inbox', name: 'Inbox', type: 'grid', color: { mode: 'field', field: 'priority' }, state: { sorting: [{ id: 'received', desc: true }] } },\n { id: 'review', name: 'Needs review', type: 'grid', color: { mode: 'field', field: 'priority' }, state: { advancedFilter: needsReview } },\n { id: 'board', name: 'By priority', type: 'kanban', stackBy: 'priority' },\n ],\n source: baseSource(\n createSqlDataSource({ schema, table: 'tickets', dialect: { placeholders: '$', ilike: true }, execute: (text, params) => run(text, params) }),\n { realtime },\n ),\n automations: AUTOMATIONS,\n props: { rowAdder: false },\n },\n ]\n }\n let tables = $state.raw<BaseTable[]>([])\n // A new base for Reset: the marks and activity start over with the tickets.\n let generation = $state(0)\n\n async function start() {\n ready = false\n log = []\n db = new PGlite()\n await db.exec(SCHEMA)\n tables = build()\n generation += 1\n ready = true\n }\n\n onMount(async () => {\n // After the shared people: the agent is one more user the base can name.\n setFieldUsers([...PEOPLE, AGENT])\n try {\n await start()\n } catch (e) {\n failed = e instanceof Error ? e.message : String(e)\n }\n })\n\n // ---- The agent -------------------------------------------------------------------\n // Keyword rules standing in for a model, checked in order. The \"can't\" rule\n // is the one a person has to correct: it reads a happy customer as locked out.\n\n const RULES: Array<{ match: RegExp; category: string; priority: string; reply: string }> = [\n { match: /down|error/i, category: 'Bug', priority: 'Urgent', reply: 'We are on it and will update you within the hour.' },\n { match: /can't|cannot|log in/i, category: 'Account', priority: 'Urgent', reply: 'Sorry you are locked out. We have reset your sign-in; try again now.' },\n { match: /charged|refund|invoice|vat/i, category: 'Billing', priority: 'High', reply: 'Thanks for flagging this. Billing will correct it and email you a new invoice.' },\n { match: /slow|cuts off|wrong/i, category: 'Bug', priority: 'High', reply: 'Thanks for the report. We reproduced it and a fix is scheduled.' },\n { match: /how do i|teammate/i, category: 'Account', priority: 'Normal', reply: 'Open Settings, then Team, then Invite: they get an email to join.' },\n { match: /please add|plans for/i, category: 'Feature request', priority: 'Low', reply: 'Thanks for the idea. We have added it to the roadmap.' },\n ]\n const classify = (text: string) => RULES.find((r) => r.match.test(text)) ?? { category: 'Feature request', priority: 'Normal', reply: 'Thanks for writing. We will get back to you soon.' }\n\n let running = $state(false)\n let progress = $state('')\n async function runAgent() {\n if (running) return\n running = true\n try {\n const todo = await run(`select id, subject, message from tickets where review is null order by received`)\n for (const [i, t] of todo.entries()) {\n progress = `Triaging ${i + 1} of ${todo.length}`\n const r = classify(`${t.subject} ${t.message}`)\n // Billing tickets go to Ben; the rest stay unassigned for the team.\n await run(\n `update tickets set category = $1, priority = $2, reply = $3, review = 'Needs review', assignee = $4, modified_by = 'agent' where id = $5`,\n [r.category, r.priority, r.reply, r.category === 'Billing' ? 'u2' : null, t.id],\n 'agent',\n )\n for (const on of listeners) on()\n await new Promise((res) => setTimeout(res, 450))\n }\n progress = todo.length ? `Triaged ${todo.length} tickets` : 'No new tickets'\n } finally {\n running = false\n }\n }\n\n const paramsText = (p: unknown[]) => p.map((v) => (typeof v === 'string' ? `'${v.length > 28 ? `${v.slice(0, 28)}...` : v}'` : v === null ? 'null' : String(v))).join(', ')\n</script>\n\n<section class=\"aitri\">\n {#if failed}\n <p class=\"aitri-error\">The database did not start: {failed}</p>\n {:else if !ready}\n <p class=\"aitri-wait\">Starting Postgres in the page…</p>\n {:else}\n <div class=\"aitri-base\">\n {#key generation}\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n showRowSelection={false}\n expandRows\n rowHeight={34}\n containerHeight=\"100%\"\n columnAdder={false}\n fieldMenu\n />\n {/key}\n </div>\n <div class=\"aitri-agent\">\n <div class=\"aitri-bar\">\n <button type=\"button\" class=\"aitri-run\" onclick={() => void runAgent()} disabled={running}>\n <img src={BOT} alt=\"\" width=\"18\" height=\"18\" />Run the triage agent\n </button>\n <span class=\"aitri-progress\" aria-live=\"polite\">{progress}</span>\n <button type=\"button\" class=\"aitri-reset\" onclick={() => void start()} disabled={running}>Reset</button>\n </div>\n <ol class=\"aitri-log\" aria-label=\"SQL the agent ran\">\n {#each log as e (e.n)}\n <li><code>{e.sql}</code><span class=\"aitri-params\">[{paramsText(e.params)}]</span></li>\n {:else}\n <li class=\"aitri-none\">The agent writes to the database with SQL, never to the page. Its statements show here.</li>\n {/each}\n </ol>\n </div>\n {/if}\n <SvToaster />\n</section>\n\n<style>\n .aitri { display: flex; flex-direction: column; flex: 1; min-height: 0; gap: 10px; }\n .aitri-base { flex: 1 1 auto; min-height: 380px; display: flex; flex-direction: column; }\n .aitri-wait, .aitri-error { margin: 0; padding: 24px 0; color: var(--sg-muted, #64748b); }\n .aitri-error { color: var(--sg-danger, #dc2626); }\n .aitri-agent {\n flex: 0 0 auto; display: flex; flex-direction: column; gap: 8px; padding: 10px 12px;\n border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius-lg, 10px);\n background: var(--sg-header-bg, var(--sg-bg, #fff)); color: var(--sg-fg, #0f172a);\n }\n .aitri-bar { display: flex; align-items: center; gap: 10px; font-size: 13px; }\n .aitri-run {\n display: inline-flex; align-items: center; gap: 8px; height: 32px; padding: 0 14px; border: 0; border-radius: var(--sg-radius, 6px);\n background: var(--sg-accent, #2563eb); color: var(--sg-accent-fg, #fff); font: inherit; font-weight: 600; cursor: pointer;\n }\n .aitri-run img { border-radius: 50%; }\n .aitri-run:disabled, .aitri-reset:disabled { opacity: 0.6; cursor: default; }\n .aitri-progress { color: var(--sg-muted, #64748b); }\n .aitri-reset {\n margin-inline-start: auto; height: 30px; padding: 0 12px; border: 1px solid var(--sg-border, #cbd5e1); border-radius: var(--sg-radius, 6px);\n background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); font: inherit; cursor: pointer;\n }\n .aitri-log {\n list-style: none; margin: 0; padding: 0; height: 120px; overflow: auto;\n font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n }\n .aitri-log li { display: flex; gap: 10px; align-items: baseline; padding: 3px 0; border-top: 1px solid var(--sg-border, #e2e8f0); }\n .aitri-log li:first-child { border-top: 0; }\n .aitri-log code { flex: 1; min-width: 0; overflow-wrap: anywhere; }\n .aitri-params { color: var(--sg-muted, #64748b); overflow-wrap: anywhere; max-width: 40%; }\n .aitri-none { color: var(--sg-muted, #64748b); font-family: inherit; }\n @media (max-width: 640px) { .aitri-params { display: none; } }\n</style>\n"
4049
4049
  },
4050
+ {
4051
+ "id": "701-enterprise-grid-filters",
4052
+ "path": "examples/src/demos/701-enterprise-grid-filters.svelte",
4053
+ "title": "Enterprise Grid Filters",
4054
+ "category": "Misc",
4055
+ "blurb": "701. Review queue: overdue, labels and a row count Four @svgrid/enterprise additions to the grid's filtering and sorting, each switched on once and then used through ordinary column options:",
4056
+ "source": "<script lang=\"ts\">\n /**\n * 701. Review queue: overdue, labels and a row count\n * ---------------------------------------------------\n * Four @svgrid/enterprise additions to the grid's filtering and sorting,\n * each switched on once and then used through ordinary column options:\n *\n * enableRelativeDateFilters() Due's filter menu gains Today, Before\n * today, After today, Next 7 days and Last\n * 7 days. No value to type: pick one and it\n * filters. A server data source receives\n * the dates they mean, not the operator.\n * enableFilterLabels() Status is stored as APPROVED /\n * MARKED_AS_FAILED; its filter checklist\n * lists \"Approved\" and \"Failed\", as the\n * cells show them.\n * enableRowCount() statusBar={{ rows: true }} shows \"24\n * rows\", or \"6 of 24 rows\" under a filter.\n * sortComparator: blanksLast() Reviews with no due date stay at the\n * bottom whichever way Due sorts.\n *\n * The accessor of every column stays the raw value, so Reviews sorts\n * 0, 1, 2, 10 and Due sorts by date, while the cells and the checklist read\n * as words.\n */\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n import {\n blanksLast,\n enableFilterLabels,\n enableRelativeDateFilters,\n enableRowCount,\n } from '@svgrid/enterprise'\n\n enableRelativeDateFilters()\n enableFilterLabels()\n enableRowCount()\n\n type Status = 'APPROVED' | 'MARKED_AS_FAILED' | 'UNDECIDED'\n type Review = {\n id: number\n name: string\n version: string\n status: Status\n reviews: number\n reviewer: string\n due: string | null\n }\n\n const STATUS_TEXT: Record<Status, string> = {\n APPROVED: 'Approved',\n MARKED_AS_FAILED: 'Failed',\n UNDECIDED: 'Undecided',\n }\n const STATUSES: Status[] = ['UNDECIDED', 'APPROVED', 'UNDECIDED', 'MARKED_AS_FAILED']\n const NAMES = [\n 'kernel-image', 'web-gateway', 'postgres-operator', 'metrics-agent', 'auth-service',\n 'snap-store-proxy', 'log-shipper', 'dns-resolver', 'object-store', 'build-runner',\n 'queue-broker', 'edge-cache',\n ]\n const REVIEWERS = ['A. Osei', 'R. Vance', 'M. Iqbal', 'J. Lindqvist', '']\n\n // Due dates are relative to today so Overdue and Next 7 days always have\n // something to show. Every fifth review has no due date.\n const OFFSETS = [-9, -2, 0, 3, 6, 12, -1, 5, 21, 1, -15, 8]\n const isoFromToday = (days: number) => {\n const d = new Date()\n d.setDate(d.getDate() + days)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n\n const reviews: Review[] = Array.from({ length: 24 }, (_, i) => ({\n id: i + 1,\n name: NAMES[i % NAMES.length],\n version: `${1 + (i % 3)}.${(i * 7) % 12}.${i % 5}`,\n status: STATUSES[(i * 5) % STATUSES.length],\n // 0 through 12, so a text sort would put 10 before 2.\n reviews: (i * 7) % 13,\n reviewer: REVIEWERS[i % REVIEWERS.length],\n due: i % 5 === 4 ? null : isoFromToday(OFFSETS[i % OFFSETS.length]),\n }))\n\n const columns: GridColumns<Review> = [\n { field: 'name', header: 'Artifact', width: 190 },\n { field: 'version', header: 'Version', width: 100 },\n {\n field: 'status',\n header: 'Status',\n width: 130,\n cell: ({ getValue }) => STATUS_TEXT[getValue() as Status] ?? '',\n },\n { field: 'reviews', header: 'Reviews', width: 100, cellDataType: 'number' },\n { field: 'reviewer', header: 'Reviewer', width: 140 },\n {\n field: 'due',\n header: 'Due',\n width: 150,\n cellDataType: 'dateString',\n format: { type: 'date', options: { dateStyle: 'medium' } },\n sortComparator: blanksLast('date'),\n },\n ]\n\n let api = $state<SvGridApi<{}, Review> | null>(null)\n let preset = $state<'all' | 'beforeToday' | 'today' | 'next7Days'>('all')\n\n const PRESETS = [\n { id: 'all', label: 'All' },\n { id: 'beforeToday', label: 'Overdue' },\n { id: 'today', label: 'Due today' },\n { id: 'next7Days', label: 'Next 7 days' },\n ] as const\n\n // The same operators the Due column's filter menu offers.\n function pick(id: (typeof PRESETS)[number]['id']) {\n preset = id\n api?.setFilter('due', id === 'all' ? null : { operator: id })\n }\n</script>\n\n<section class=\"wrap\">\n <header class=\"chrome\">\n <p class=\"hint\">\n Open the filter on <strong>Due</strong> for the days-from-today operators, or on\n <strong>Status</strong> for a checklist that reads as the cells do. Sort Due either way:\n reviews with no date stay last.\n </p>\n <div class=\"seg\" role=\"group\" aria-label=\"Due date\">\n {#each PRESETS as p (p.id)}\n <button class:on={preset === p.id} aria-pressed={preset === p.id} onclick={() => pick(p.id)}>\n {p.label}\n </button>\n {/each}\n </div>\n </header>\n\n <div class=\"grid-host\">\n <SvGrid\n responsive={true}\n data={reviews}\n {columns}\n getRowId={(r) => String(r.id)}\n sortable\n filterable\n filterMode=\"menu\"\n initialSorting={[{ id: 'due', desc: false }]}\n statusBar={{ rows: true, aggregates: [] }}\n rowHeight={36}\n containerHeight=\"100%\"\n fitColumns\n onApiReady={(next) => (api = next)}\n onFiltersChange={(f) => {\n // Due set from its menu to something the buttons do not name: no button is on.\n const op = f.columns.find((c) => c.id === 'due')?.operator\n if (!PRESETS.some((p) => p.id === op)) preset = 'all'\n }}\n />\n </div>\n</section>\n\n<style>\n .wrap {\n display: flex;\n flex-direction: column;\n flex: 1;\n min-height: 0;\n gap: 12px;\n }\n\n .chrome {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n flex-wrap: wrap;\n flex: none;\n }\n .hint {\n margin: 0;\n font-size: 13px;\n line-height: 1.5;\n color: var(--sg-muted, #64748b);\n max-width: 62ch;\n }\n .hint strong { color: var(--sg-fg, #0f172a); font-weight: 600; }\n\n .seg {\n display: inline-flex;\n border: 1px solid var(--sg-border, #cbd5e1);\n border-radius: 8px;\n overflow: hidden;\n }\n .seg button {\n border: 0;\n padding: 6px 12px;\n font: inherit;\n font-size: 13px;\n background: var(--sg-bg, #fff);\n color: var(--sg-muted, #64748b);\n cursor: pointer;\n }\n .seg button + button { border-left: 1px solid var(--sg-border, #cbd5e1); }\n .seg button.on { background: var(--sg-accent, #6366f1); color: var(--sg-on-accent, #fff); }\n .seg button:focus-visible { outline: 2px solid var(--sg-focus-ring, #6366f1); outline-offset: -2px; }\n\n .grid-host {\n flex: 1;\n min-height: 0;\n display: flex;\n flex-direction: column;\n }\n</style>\n"
4057
+ },
4058
+ {
4059
+ "id": "702-change-review",
4060
+ "path": "examples/src/demos/702-change-review.svelte",
4061
+ "title": "Change Review",
4062
+ "category": "Misc",
4063
+ "blurb": "702. Change review: an agent's edits, accepted by group A customer table with the dirt a CRM export carries. Run the cleanup agent and its edits arrive as proposals, not writes: each changed cell",
4064
+ "source": "<script lang=\"ts\">\n /**\n * 702. Change review: an agent's edits, accepted by group\n * --------------------------------------------------------\n * A customer table with the dirt a CRM export carries. Run the cleanup\n * agent and its edits arrive as proposals, not writes: each changed cell\n * shows the proposed value with the old one struck through beside it, and\n * the panel groups them by what they do.\n *\n * Trim spaces, Change to Title Case, Reformat Phone,\n * Divide Revenue by 100 rule groups: every member follows the rule\n * Country: 5 values -> ... a mapping table, one decision\n * Fill empty Region split by value; the low-confidence fills\n * (two of them wrong) lead the sample\n *\n * Accept a group and one setRows call writes it; Ctrl+Z in the grid puts it\n * back. Edit a cell that has a proposal, then accept: the proposal is\n * marked stale and your value stays. Import the CRM update and one cell gets\n * a second, different proposal: a conflict, decided in the panel.\n *\n * The agent here is a few fixed rules standing in for a model, so the demo\n * runs without a key. With one, reviewSmartFill / reviewClassify feed the\n * same review from the AI helpers.\n */\n import { SvButton, SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n import { createReview, fromRows, SvReviewPanel, type ProposalInput } from '@svgrid/enterprise/review'\n\n type Customer = {\n id: string\n company: string\n contact: string\n phone: string\n country: string\n region: string\n revenue: number\n }\n\n const COMPANIES = ['Acme Corp', 'Globex', 'Initech', 'Umbrella Labs', 'Hooli', 'Vandelay Imports', 'Stark Industries',\n 'Wayne Holdings', 'Tyrell Systems', 'Cyberdyne', 'Aperture Science', 'Soylent Foods', 'Oscorp', 'Wonka Partners',\n 'Gringotts', 'Monarch Group', 'Pied Piper', 'Dunder Paper', 'Prestige Worldwide', 'Massive Dynamic']\n const PEOPLE = ['maria silva', 'wei chen', 'aisha khan', 'carlos ruiz', 'emma berg', 'liam novak', 'sofia rossi',\n 'noah okafor', 'yuki tanaka', 'omar haddad']\n const COUNTRIES = ['United States', 'usa', 'Germany', 'U.S.', 'Japan', 'US', 'United Kingdom', 'United States of America', 'Brazil', 'U.S.A.']\n const REGION_OF: Record<string, string> = { 'United States': 'AMER', Brazil: 'AMER', Germany: 'EMEA', 'United Kingdom': 'EMEA', Japan: 'APAC' }\n const US = new Set(['usa', 'U.S.', 'US', 'United States of America', 'U.S.A.'])\n\n const seed = (): Customer[] =>\n COMPANIES.map((name, i) => {\n const country = COUNTRIES[i % COUNTRIES.length]\n const a = 200 + ((i * 37) % 700)\n const b = 100 + ((i * 53) % 800)\n const c = 1000 + ((i * 271) % 9000)\n return {\n id: `c${i + 1}`,\n company: i % 3 === 0 ? `${name} ` : i % 7 === 1 ? ` ${name}` : name,\n contact: i % 2 === 0 ? PEOPLE[i % PEOPLE.length].toUpperCase() : titleCase(PEOPLE[i % PEOPLE.length]),\n phone: i % 4 === 3 ? `${a}-${b}-${c}` : `(${a}) ${b}-${c}`,\n country,\n region: i % 3 === 1 ? '' : REGION_OF[US.has(country) ? 'United States' : country] ?? '',\n // Six rows came in from the old billing system, in cents.\n revenue: i % 3 === 2 ? (40 + i * 13) * 1000 * 100 : (40 + i * 13) * 1000,\n }\n })\n\n function titleCase(s: string) {\n return s.replace(/\\b\\p{Ll}/gu, (ch) => ch.toUpperCase())\n }\n\n let rows = $state(seed())\n let api = $state<SvGridApi<any, Customer> | null>(null)\n const review = createReview<Customer>({ api: () => api, setRows: (next) => (rows = next) })\n\n const columns: GridColumns<Customer> = [\n { field: 'company', header: 'Company', width: 190, editable: true },\n { field: 'contact', header: 'Contact', width: 150, editable: true },\n { field: 'phone', header: 'Phone', width: 140, editable: true },\n { field: 'country', header: 'Country', width: 170, editable: true },\n { field: 'region', header: 'Region', width: 100, editable: true },\n { field: 'revenue', header: 'Revenue', width: 130, editable: true, editorType: 'number', format: { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } } },\n ]\n\n /** A few fixed rules standing in for a cleanup model. */\n function runAgent() {\n const proposals: ProposalInput[] = []\n for (const r of rows) {\n const add = (field: keyof Customer, after: unknown, extra: Partial<ProposalInput> = {}) => {\n if (r[field] !== after) proposals.push({ rowId: r.id, field, before: r[field], after, ...extra })\n }\n add('company', r.company.trim())\n add('contact', titleCase(r.contact.toLowerCase()))\n const digits = r.phone.replace(/\\D/g, '')\n add('phone', `${digits.slice(0, 3)}-${digits.slice(3, 6)}-${digits.slice(6)}`)\n const country = US.has(r.country) ? 'United States' : r.country\n add('country', country)\n if (!r.region) {\n // Two guesses are wrong, and the agent says it is unsure of them.\n // c5 is in Japan and c11 in the United States.\n const guess = r.id === 'c5' ? 'EMEA' : r.id === 'c11' ? 'APAC' : null\n const unsure = guess !== null\n add('region', guess ?? REGION_OF[country], {\n confidence: unsure ? 0.42 : 0.93,\n reason: unsure ? 'guessed from the company name' : `from Country (${country})`,\n })\n }\n if (r.revenue >= 1_000_000) add('revenue', r.revenue / 100, { reason: 'billing export was in cents' })\n }\n review.add({ source: { kind: 'agent', id: 'cleanup', label: 'Cleanup agent' }, proposals })\n }\n\n /** The CRM sends its own region for one customer, different from the agent's. */\n function runImport() {\n if (!api) return\n const set = fromRows<Customer>([{ id: 'c2', region: 'EMEA' }, { id: 'c8', region: 'EMEA' }], {\n api,\n key: 'id',\n source: { kind: 'import', id: 'crm-update.csv', label: 'crm-update.csv' },\n })\n review.add(set)\n }\n\n function reset() {\n review.clear()\n rows = seed()\n }\n\n const pending = $derived(review.pending().length)\n\n // A phone has no room for both side by side, and the demo stage has a fixed\n // height: show one at a time. The grid stays mounted, so its api does too.\n let narrow = $state(false)\n let view = $state<'grid' | 'review'>('grid')\n $effect(() => {\n const mq = window.matchMedia('(max-width: 860px)')\n const sync = () => (narrow = mq.matches)\n sync()\n mq.addEventListener('change', sync)\n return () => mq.removeEventListener('change', sync)\n })\n</script>\n\n<div class=\"cr-demo\">\n <div class=\"cr-bar\">\n <SvButton size=\"sm\" onclick={runAgent}>Run cleanup agent</SvButton>\n <SvButton size=\"sm\" variant=\"outline\" onclick={runImport}>Import crm-update.csv</SvButton>\n <SvButton size=\"sm\" variant=\"ghost\" onclick={reset}>Reset</SvButton>\n <span class=\"cr-note\">{pending ? `${pending} proposed, nothing written yet` : 'The data is as loaded'}</span>\n </div>\n {#if narrow}\n <div class=\"cr-bar\" role=\"group\" aria-label=\"Show\">\n <SvButton size=\"sm\" variant={view === 'grid' ? 'secondary' : 'ghost'} onclick={() => (view = 'grid')}>Grid</SvButton>\n <SvButton size=\"sm\" variant={view === 'review' ? 'secondary' : 'ghost'} onclick={() => (view = 'review')}>Review ({pending})</SvButton>\n </div>\n {/if}\n <div class=\"cr-split\">\n <div class=\"cr-grid\" class:cr-hidden={narrow && view === 'review'}>\n <SvGrid\n data={rows}\n columns={review.columns(columns)}\n getRowId={(r) => r.id}\n conditionalFormats={review.formats}\n editable\n containerHeight={460}\n onApiReady={(a) => (api = a)}\n />\n </div>\n <div class=\"cr-panel\" class:cr-hidden={narrow && view === 'grid'}>\n <SvReviewPanel {review} title=\"Review the agent's changes\" />\n </div>\n </div>\n</div>\n\n<style>\n .cr-demo {\n display: flex;\n flex-direction: column;\n gap: 10px;\n font-family: var(--sg-font, inherit);\n color: var(--sg-fg);\n }\n .cr-bar {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 8px;\n }\n .cr-note {\n color: var(--sg-muted);\n font-size: 13px;\n }\n .cr-split {\n display: grid;\n grid-template-columns: minmax(0, 1fr) 340px;\n gap: 12px;\n align-items: start;\n }\n .cr-grid,\n .cr-panel {\n min-width: 0;\n }\n /* The stage has a fixed height: the panel scrolls within the grid's. */\n .cr-panel {\n max-height: 460px;\n overflow: auto;\n }\n .cr-hidden {\n display: none;\n }\n @media (max-width: 860px) {\n .cr-split {\n grid-template-columns: minmax(0, 1fr);\n }\n }\n</style>\n"
4065
+ },
4066
+ {
4067
+ "id": "704-agent-review-desk",
4068
+ "path": "examples/src/demos/704-agent-review-desk.svelte",
4069
+ "title": "Agent Review Desk",
4070
+ "category": "App Templates",
4071
+ "blurb": "704. Agent review desk (app template) A CRM agent cleans a customer table, and nothing it does lands until a person says so. The agent works through the same tools a real model would",
4072
+ "source": "<script lang=\"ts\">\n /**\n * 704. Agent review desk (app template)\n * -------------------------------------\n * A CRM agent cleans a customer table, and nothing it does lands until a\n * person says so. The agent works through the same tools a real model would\n * get from createGridTools:\n *\n * grid_describe what the table holds and what it may edit\n * grid_query_rows the rows, with their row ids\n * grid_propose_edits edits, each with a reason and a confidence\n *\n * Every step it takes shows in the strip under the header with the tool\n * call it made. Its edits arrive as proposals: the cell shows the proposed\n * value with the old one struck through, and the review panel groups them\n * by what they do, the risky groups first. Two of its region guesses are\n * wrong, and it says it is unsure of them.\n *\n * Accept or reject a group; one Ctrl+Z in the grid undoes it. Edit a cell\n * before accepting its proposal and your value stays. The Log tab lists\n * every decision (onDecision, where an app writes its audit trail). Revert\n * run proposes undoing what was accepted (revertSet); Copy for approver\n * puts the review on the clipboard as JSON for someone else to merge.\n *\n * The agent is a script standing in for a model, so the demo runs offline.\n *\n * Grid, buttons: @svgrid/grid. Change review, agent tools: @svgrid/enterprise.\n */\n import { onMount } from 'svelte'\n import { SvGrid, SvButton, renderSnippet, type GridColumns, type SvGridApi } from '@svgrid/grid'\n import {\n createReview,\n createGridTools,\n SvReviewPanel,\n type GridTool,\n type ReviewDecision,\n } from '@svgrid/enterprise/review'\n\n type Customer = {\n id: string\n company: string\n contact: string\n email: string\n phone: string\n country: string\n region: string\n segment: string\n arr: number\n }\n\n // ---- data -------------------------------------------------------------\n\n const NAMES = ['Acme Robotics', 'Bluefin Labs', 'Cobalt Freight', 'Driftwood Media', 'Ember Analytics', 'Fjord Outdoor',\n 'Granite Health', 'Harbor Logistics', 'Ion Energy', 'Juniper Foods', 'Kestrel Air', 'Lumen Optics', 'Mosaic Retail',\n 'Nimbus Cloud', 'Orchid Beauty', 'Pinecone Games', 'Quarry Steel', 'Radiant Solar', 'Saffron Spices', 'Tundra Gear',\n 'Umbra Security', 'Vertex Bio', 'Willow Insurance', 'Xenon Motors', 'Yarrow Pharma', 'Zephyr Travel', 'Atlas Mapping',\n 'Beacon Schools', 'Cypress Legal', 'Delta Dental', 'Echo Audio', 'Falcon Drones', 'Garnet Jewels', 'Helix Genomics',\n 'Indigo Textiles', 'Jade Ceramics']\n const PEOPLE = ['maria lopez', 'wei zhang', 'aisha bello', 'tom fischer', 'emma dubois', 'liam walsh', 'sofia ricci',\n 'noah park', 'yuki sato', 'omar nasser', 'lena berg', 'ravi iyer']\n const COUNTRIES = ['United States', 'usa', 'Germany', 'U.S.', 'Japan', 'US', 'United Kingdom', 'United States of America',\n 'Brazil', 'France', 'U.S.A.', 'India']\n const US = new Set(['usa', 'U.S.', 'US', 'United States of America', 'U.S.A.'])\n const REGION: Record<string, string> = { 'United States': 'AMER', Brazil: 'AMER', Germany: 'EMEA', 'United Kingdom': 'EMEA', France: 'EMEA', Japan: 'APAC', India: 'APAC' }\n const titleCase = (s: string) => s.replace(/\\b\\p{Ll}/gu, (c) => c.toUpperCase())\n\n function seed(): Customer[] {\n return NAMES.map((name, i) => {\n const person = PEOPLE[i % PEOPLE.length]!\n const country = COUNTRIES[i % COUNTRIES.length]!\n const domain = name.split(' ')[0]!.toLowerCase()\n const [a, b, c] = [200 + ((i * 37) % 700), 100 + ((i * 53) % 800), 1000 + ((i * 271) % 9000)]\n const arr = (18 + ((i * 47) % 160)) * 1000\n return {\n id: `cus-${1001 + i}`,\n company: i % 4 === 0 ? `${name} ` : i % 9 === 2 ? ` ${name}` : name,\n contact: i % 3 === 0 ? person.toUpperCase() : titleCase(person),\n email: i % 2 === 0 ? `${titleCase(person).replace(' ', '.')}@${titleCase(domain)}.COM` : `${person.replace(' ', '.')}@${domain}.com`,\n phone: i % 5 === 4 ? `${a}-${b}-${c}` : i % 3 === 1 ? `${a}.${b}.${c}` : `(${a}) ${b}-${c}`,\n country,\n region: i % 4 === 1 ? '' : REGION[US.has(country) ? 'United States' : country] ?? '',\n segment: '',\n // Seven accounts came over from the old billing system in cents.\n arr: i % 5 === 2 ? arr * 100 : arr,\n }\n })\n }\n\n let rows = $state(seed())\n let api = $state<SvGridApi<any, Customer> | null>(null)\n\n // ---- review -------------------------------------------------------------\n\n type LogEntry = { id: number; at: number; text: string; tone: 'accept' | 'reject' | 'undo' }\n let log = $state<LogEntry[]>([])\n let logSeq = 0\n const FIELD_LABEL: Record<string, string> = { company: 'Company', contact: 'Contact', email: 'Email', phone: 'Phone', country: 'Country', region: 'Region', segment: 'Segment', arr: 'ARR' }\n\n function describeDecision(d: ReviewDecision): LogEntry {\n const fields = [...new Set(d.proposals.map((p) => FIELD_LABEL[p.field] ?? p.field))].join(', ')\n const n = d.proposals.length\n const what = `${n} ${n === 1 ? 'change' : 'changes'} to ${fields}`\n const text =\n d.action === 'accept' ? `Accepted ${what}`\n : d.action === 'reject' ? `Rejected ${what}`\n : d.action === 'undo' ? `Undid the ${d.of} of ${what}`\n : `Redid the ${d.of} of ${what}`\n return { id: ++logSeq, at: d.at, text, tone: d.action === 'accept' || (d.action === 'redo' && d.of === 'accept') ? 'accept' : d.action === 'reject' ? 'reject' : 'undo' }\n }\n\n const review = createReview<Customer>({\n api: () => api,\n setRows: (next) => (rows = next),\n user: 'You',\n onDecision: (d) => (log = [describeDecision(d), ...log]),\n })\n\n const AGENT = { kind: 'agent' as const, id: 'crm-agent', label: 'CRM agent' }\n const tools = createGridTools({\n review,\n api: () => api,\n source: AGENT,\n fields: ['company', 'contact', 'email', 'phone', 'country', 'region', 'segment', 'arr'],\n })\n const tool = (name: string) => tools.find((t) => t.name === name) as GridTool\n\n // ---- the agent --------------------------------------------------------\n\n type Step = { id: number; title: string; call: string; result: string; state: 'running' | 'done' }\n let steps = $state<Step[]>([])\n const SHORT: Record<string, string> = {\n 'Read the customer table': 'Read the table',\n 'Trim stray spaces in company names': 'Trim spaces',\n 'Put contact names in title case': 'Title-case names',\n 'Lower-case email addresses': 'Lower-case emails',\n 'Use one phone format': 'One phone format',\n 'Map country spellings to one name': 'Map countries',\n 'Fill missing regions': 'Fill regions',\n 'Convert ARR booked in cents': 'ARR from cents',\n 'Tag each account with a segment': 'Tag segments',\n }\n // The newest step stays in view as the strip grows.\n let stepsEl = $state<HTMLOListElement | null>(null)\n $effect(() => {\n void steps.length\n queueMicrotask(() => stepsEl?.scrollTo({ left: stepsEl.scrollWidth, behavior: 'smooth' }))\n })\n let agentState = $state<'idle' | 'running' | 'done'>('idle')\n let runToken = 0\n\n const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n type Edit = { rowId: string; field: string; value: unknown; reason?: string; confidence?: number }\n\n async function step(title: string, call: string, work: () => Promise<string>, token: number) {\n if (token !== runToken) return false\n const s: Step = { id: steps.length + 1, title, call, result: '', state: 'running' }\n steps = [...steps, s]\n await sleep(650)\n if (token !== runToken) return false\n const result = await work()\n steps = steps.map((x) => (x.id === s.id ? { ...x, result, state: 'done' } : x))\n return true\n }\n\n async function propose(title: string, edits: Edit[]) {\n const out = (await tool('grid_propose_edits').execute({ title, edits })) as { proposed: number }\n return `${out.proposed} proposed`\n }\n\n async function runAgent() {\n const token = ++runToken\n steps = []\n agentState = 'running'\n let table: Customer[] = []\n const ok = await step('Read the customer table', 'grid_describe() · grid_query_rows()', async () => {\n const d = (await tool('grid_describe').execute({})) as { rowCount: number; columns: unknown[] }\n table = ((await tool('grid_query_rows').execute({})) as { rows: Array<Customer & { rowId: string }> }).rows.map((r) => ({ ...r, id: r.rowId }))\n return `${d.rowCount} rows, ${d.columns.length} columns`\n }, token)\n if (!ok) return\n const each = (fn: (r: Customer) => Edit | null) => table.map(fn).filter((e): e is Edit => e !== null)\n\n const plan: Array<[string, string, () => Edit[]]> = [\n ['Trim stray spaces in company names', 'company', () =>\n each((r) => (r.company !== r.company.trim() ? { rowId: r.id, field: 'company', value: r.company.trim() } : null))],\n ['Put contact names in title case', 'contact', () =>\n each((r) => (r.contact === r.contact.toUpperCase() ? { rowId: r.id, field: 'contact', value: titleCase(r.contact.toLowerCase()) } : null))],\n ['Lower-case email addresses', 'email', () =>\n each((r) => (r.email !== r.email.toLowerCase() ? { rowId: r.id, field: 'email', value: r.email.toLowerCase() } : null))],\n ['Use one phone format', 'phone', () =>\n each((r) => {\n const d = r.phone.replace(/\\D/g, '')\n const v = `${d.slice(0, 3)}-${d.slice(3, 6)}-${d.slice(6)}`\n return v !== r.phone ? { rowId: r.id, field: 'phone', value: v } : null\n })],\n ['Map country spellings to one name', 'country', () =>\n each((r) => (US.has(r.country) ? { rowId: r.id, field: 'country', value: 'United States', reason: `\"${r.country}\" is the United States` } : null))],\n ['Fill missing regions', 'region', () =>\n each((r) => {\n if (r.region) return null\n const country = US.has(r.country) ? 'United States' : r.country\n // Two guesses come from the company name, and the agent says so.\n if (r.id === 'cus-1006') return { rowId: r.id, field: 'region', value: 'APAC', confidence: 0.38, reason: 'guessed from the company name' }\n if (r.id === 'cus-1018') return { rowId: r.id, field: 'region', value: 'EMEA', confidence: 0.44, reason: 'guessed from the company name' }\n return { rowId: r.id, field: 'region', value: REGION[country], confidence: 0.94, reason: `from Country (${country})` }\n })],\n ['Convert ARR booked in cents', 'arr', () =>\n each((r) => (r.arr >= 1_000_000 ? { rowId: r.id, field: 'arr', value: r.arr / 100, reason: 'imported from billing in cents' } : null))],\n ['Tag each account with a segment', 'segment', () =>\n each((r) => {\n const arr = r.arr >= 1_000_000 ? r.arr / 100 : r.arr\n return { rowId: r.id, field: 'segment', value: arr >= 120_000 ? 'Enterprise' : arr >= 60_000 ? 'Mid-market' : 'SMB', confidence: 0.86, reason: 'from ARR bands' }\n })],\n ]\n for (const [title, field, build] of plan) {\n const edits = build()\n const done = await step(title, `grid_propose_edits(${edits.length} × ${field})`, () => propose(title, edits), token)\n if (!done) return\n }\n if (token === runToken) agentState = 'done'\n }\n\n function runAgain() {\n review.clear()\n rows = seed()\n log = []\n void runAgent()\n }\n\n // ---- after review -------------------------------------------------------\n\n let note = $state('')\n function revertRun() {\n let n = 0\n for (const s of review.sets()) {\n if (s.source.id !== AGENT.id) continue\n const set = review.revertSet(s.id)\n if (set) n += set.proposals.length\n }\n note = n ? `${n} reverts proposed: review them like any other change` : 'Nothing accepted to revert'\n }\n async function copyForApprover() {\n const json = JSON.stringify(review.toJSON())\n try {\n await navigator.clipboard.writeText(json)\n note = `Copied ${review.sets().length} sets (${Math.round(json.length / 1024)} KB of JSON) for an approver to merge`\n } catch {\n note = 'The browser blocked the clipboard'\n }\n }\n\n // ---- derived chrome -----------------------------------------------------\n\n const tally = $derived.by(() => {\n const t = { proposed: 0, pending: 0, accepted: 0, rejected: 0 }\n for (const p of review.proposals()) {\n t.proposed++\n if (p.status === 'pending' || p.status === 'conflict') t.pending++\n else if (p.status === 'accepted') t.accepted++\n else if (p.status === 'rejected' || p.status === 'stale') t.rejected++\n }\n return t\n })\n const status = $derived(\n agentState === 'running' ? { text: 'Agent working', tone: 'info' }\n : tally.pending ? { text: 'Waiting for review', tone: 'warning' }\n : tally.proposed ? { text: 'All reviewed', tone: 'success' }\n : { text: 'Idle', tone: 'muted' },\n )\n\n let side = $state<'review' | 'log'>('review')\n let narrow = $state(false)\n let view = $state<'grid' | 'side'>('grid')\n\n onMount(() => {\n const mq = window.matchMedia('(max-width: 860px)')\n const sync = () => (narrow = mq.matches)\n sync()\n mq.addEventListener('change', sync)\n const t = setTimeout(() => void runAgent(), 500)\n return () => {\n mq.removeEventListener('change', sync)\n clearTimeout(t)\n runToken++\n }\n })\n\n const time = (at: number) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })\n\n const SEGMENT_TONE: Record<string, string> = { Enterprise: '#7c3aed', 'Mid-market': '#0e7490', SMB: '#64748b' }\n const columns: GridColumns<Customer> = [\n { field: 'company', header: 'Company', width: 180, editable: true },\n { field: 'contact', header: 'Contact', width: 140, editable: true },\n { field: 'email', header: 'Email', width: 220, editable: true },\n { field: 'phone', header: 'Phone', width: 130, editable: true },\n { field: 'country', header: 'Country', width: 150, editable: true },\n { field: 'region', header: 'Region', width: 90, editable: true },\n { field: 'segment', header: 'Segment', width: 120, editable: true, cell: (ctx) => renderSnippet(segmentCell, { value: ctx.getValue() as string }) },\n { field: 'arr', header: 'ARR', width: 120, editable: true, editorType: 'number', format: { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } } },\n ]\n</script>\n\n{#snippet segmentCell({ value }: { value: string })}\n {#if value}<span class=\"ard-seg\" style:--seg={SEGMENT_TONE[value] ?? '#64748b'}>{value}</span>{/if}\n{/snippet}\n\n<div class=\"ard\">\n <header class=\"ard-head\">\n <div class=\"ard-title\">\n <span class=\"ard-logo\" aria-hidden=\"true\">\n <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\"><path d=\"M4 6h16M4 12h10M4 18h7\" /><path d=\"M16 16l2 2 4-4\" /></svg>\n </span>\n <div>\n <h2>Customer master data</h2>\n <p>Northbeam CRM · cleanup by <strong>CRM agent</strong> · {rows.length} accounts</p>\n </div>\n <span class=\"ard-status is-{status.tone}\"><span class=\"ard-dot\" aria-hidden=\"true\"></span>{status.text}</span>\n </div>\n <dl class=\"ard-stats\">\n <div><dt>Proposed</dt><dd>{tally.proposed}</dd></div>\n <div><dt>Pending</dt><dd>{tally.pending}</dd></div>\n <div><dt>Accepted</dt><dd class=\"is-good\">{tally.accepted}</dd></div>\n <div><dt>Rejected</dt><dd>{tally.rejected}</dd></div>\n </dl>\n </header>\n\n <div class=\"ard-agent\" aria-live=\"polite\">\n <ol class=\"ard-steps\" bind:this={stepsEl}>\n {#each steps as s (s.id)}\n <li class=\"ard-step is-{s.state}\" title=\"{s.title}: {s.call}\">\n <span class=\"ard-step-icon\" aria-hidden=\"true\">\n {#if s.state === 'running'}<span class=\"ard-spin\"></span>{:else}<svg viewBox=\"0 0 24 24\" width=\"12\" height=\"12\"><path d=\"M5 12.5l4.5 4.5L19 7.5\" /></svg>{/if}\n </span>\n <span class=\"ard-step-text\">\n <span class=\"ard-step-title\">{SHORT[s.title] ?? s.title}</span>\n <code>{s.call}</code>\n </span>\n {#if s.result}<span class=\"ard-step-result\">{s.result}</span>{/if}\n </li>\n {:else}\n <li class=\"ard-step is-idle\">The agent starts in a moment…</li>\n {/each}\n </ol>\n <div class=\"ard-actions\">\n <SvButton size=\"sm\" variant=\"outline\" disabled={agentState === 'running'} onclick={runAgain}>Run again</SvButton>\n <SvButton size=\"sm\" variant=\"ghost\" disabled={!tally.accepted} onclick={revertRun}>Revert run</SvButton>\n <SvButton size=\"sm\" variant=\"ghost\" disabled={!tally.proposed} onclick={copyForApprover}>Copy for approver</SvButton>\n </div>\n </div>\n {#if note}<p class=\"ard-note\" role=\"status\">{note}</p>{/if}\n\n {#if narrow}\n <div class=\"ard-tabs\" role=\"tablist\" aria-label=\"Show\">\n <button type=\"button\" role=\"tab\" aria-selected={view === 'grid'} onclick={() => (view = 'grid')}>Table</button>\n <button type=\"button\" role=\"tab\" aria-selected={view === 'side'} onclick={() => (view = 'side')}>Review ({tally.pending})</button>\n </div>\n {/if}\n\n <div class=\"ard-body\">\n <div class=\"ard-grid\" class:ard-hidden={narrow && view !== 'grid'}>\n <SvGrid\n data={rows}\n columns={review.columns(columns)}\n getRowId={(r) => r.id}\n conditionalFormats={review.formats}\n editable\n rowHeight={34}\n initialColumnPinning={{ left: ['company'] }}\n containerHeight={narrow ? 300 : 430}\n onApiReady={(a) => (api = a)}\n />\n </div>\n <aside class=\"ard-side\" class:ard-hidden={narrow && view !== 'side'}>\n <div class=\"ard-tabs\" role=\"tablist\" aria-label=\"Side panel\">\n <button type=\"button\" role=\"tab\" aria-selected={side === 'review'} onclick={() => (side = 'review')}>Review</button>\n <button type=\"button\" role=\"tab\" aria-selected={side === 'log'} onclick={() => (side = 'log')}>{log.length ? `Log (${log.length})` : 'Log'}</button>\n </div>\n <div class=\"ard-side-body\">\n {#if side === 'review'}\n <SvReviewPanel {review} title=\"The agent's changes\" />\n {:else}\n <ol class=\"ard-log\">\n {#each log as e (e.id)}\n <li class=\"is-{e.tone}\">\n <span class=\"ard-log-dot\" aria-hidden=\"true\"></span>\n <span class=\"ard-log-text\">{e.text}</span>\n <time>{time(e.at)}</time>\n </li>\n {:else}\n <li class=\"is-empty\">Decisions show up here, newest first, with who made them: what an app writes to its audit trail from onDecision.</li>\n {/each}\n </ol>\n {/if}\n </div>\n </aside>\n </div>\n</div>\n\n<style>\n .ard {\n display: flex;\n flex-direction: column;\n border: 1px solid var(--sg-border, #e5e7eb);\n border-radius: 12px;\n overflow: hidden;\n background: var(--sg-bg, #fff);\n color: var(--sg-fg, #0f172a);\n font-family: var(--sg-font, inherit);\n font-size: 13px;\n }\n .ard-head {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n flex-wrap: wrap;\n padding: 14px 18px;\n border-bottom: 1px solid var(--sg-border, #e5e7eb);\n }\n .ard-title { display: flex; align-items: center; gap: 12px; min-width: 0; flex-wrap: wrap; }\n .ard-logo {\n display: grid;\n place-items: center;\n width: 34px;\n height: 34px;\n flex: none;\n border-radius: 9px;\n background: var(--sg-fg, #0f172a);\n color: var(--sg-bg, #fff);\n }\n .ard-logo svg { fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }\n .ard-title h2 { margin: 0; font-size: 16px; font-weight: 650; letter-spacing: -0.01em; }\n .ard-title p { margin: 2px 0 0; font-size: 12px; color: var(--sg-muted, #64748b); }\n .ard-title strong { color: var(--sg-fg, #0f172a); font-weight: 600; }\n .ard-status {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 3px 10px;\n border-radius: 999px;\n font-size: 11.5px;\n font-weight: 650;\n --tone: var(--sg-muted, #64748b);\n color: color-mix(in srgb, var(--tone) 80%, var(--sg-fg, #0f172a));\n background: color-mix(in srgb, var(--tone) 13%, transparent);\n }\n .ard-status.is-info { --tone: var(--sg-info, #0284c7); }\n .ard-status.is-warning { --tone: var(--sg-warning, #d97706); }\n .ard-status.is-success { --tone: var(--sg-success, #16a34a); }\n .ard-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--tone); }\n .ard-status.is-info .ard-dot { animation: ard-pulse 1.1s ease-in-out infinite; }\n @keyframes ard-pulse { 50% { opacity: 0.3; } }\n\n .ard-stats { display: flex; gap: 22px; margin: 0; }\n .ard-stats div { display: flex; flex-direction: column; align-items: flex-end; }\n .ard-stats dt { font-size: 11px; color: var(--sg-muted, #64748b); }\n .ard-stats dd { margin: 0; font-size: 18px; font-weight: 650; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; }\n .ard-stats dd.is-good { color: var(--sg-success, #16a34a); }\n\n .ard-agent {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 18px;\n border-bottom: 1px solid var(--sg-border, #e5e7eb);\n background: var(--sg-bg-subtle, var(--sg-header-bg, #f8fafc));\n }\n .ard-steps {\n flex: 1;\n min-width: 0;\n display: flex;\n gap: 6px;\n margin: 0;\n padding: 2px 0;\n list-style: none;\n overflow-x: auto;\n scrollbar-width: thin;\n }\n .ard-step {\n display: flex;\n align-items: center;\n gap: 7px;\n flex: none;\n max-width: 260px;\n padding: 5px 10px 5px 7px;\n border: 1px solid var(--sg-border, #e5e7eb);\n border-radius: 8px;\n background: var(--sg-bg, #fff);\n animation: ard-in 0.25s ease-out;\n }\n @keyframes ard-in { from { opacity: 0; transform: translateY(3px); } }\n .ard-step.is-idle { color: var(--sg-muted, #64748b); border-style: dashed; animation: none; }\n .ard-step-icon {\n display: grid;\n place-items: center;\n width: 18px;\n height: 18px;\n flex: none;\n border-radius: 50%;\n color: var(--sg-bg, #fff);\n background: var(--sg-success, #16a34a);\n }\n .ard-step-icon svg { fill: none; stroke: currentColor; stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }\n .ard-step.is-running .ard-step-icon { background: none; }\n .ard-spin {\n width: 14px;\n height: 14px;\n border-radius: 50%;\n border: 2px solid color-mix(in srgb, var(--sg-info, #0284c7) 25%, transparent);\n border-top-color: var(--sg-info, #0284c7);\n animation: ard-rot 0.7s linear infinite;\n }\n @keyframes ard-rot { to { transform: rotate(360deg); } }\n .ard-step-text { display: flex; flex-direction: column; min-width: 0; }\n .ard-step-title { font-size: 12px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .ard-step code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: 10.5px;\n color: var(--sg-muted, #64748b);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .ard-step-result { font-size: 11.5px; font-weight: 650; font-variant-numeric: tabular-nums; white-space: nowrap; }\n .ard-actions { display: flex; gap: 6px; flex: none; }\n .ard-note { margin: 0; padding: 7px 18px; font-size: 12px; color: var(--sg-muted, #64748b); border-bottom: 1px solid var(--sg-border, #e5e7eb); }\n\n .ard-body { display: grid; grid-template-columns: minmax(0, 1fr) 360px; min-height: 0; }\n .ard-grid { min-width: 0; padding: 12px 0 12px 12px; }\n .ard-side { min-width: 0; display: flex; flex-direction: column; border-left: 1px solid var(--sg-border, #e5e7eb); margin-left: 12px; }\n .ard-side-body { max-height: 430px; overflow: auto; padding: 0 12px 12px; }\n .ard-side-body :global(.sv-review) { border: 0; padding: 0; }\n .ard-tabs { display: flex; gap: 2px; padding: 8px 12px 0; border-bottom: 1px solid var(--sg-border, #e5e7eb); }\n .ard-tabs button {\n padding: 6px 10px;\n margin-bottom: -1px;\n font: inherit;\n font-size: 12.5px;\n font-weight: 550;\n color: var(--sg-muted, #64748b);\n background: none;\n border: 0;\n border-bottom: 2px solid transparent;\n cursor: pointer;\n }\n .ard-tabs button[aria-selected='true'] { color: var(--sg-fg, #0f172a); border-bottom-color: var(--sg-fg, #0f172a); }\n .ard-tabs button:focus-visible { outline: 2px solid var(--sg-focus-ring, var(--sg-accent, #2563eb)); outline-offset: -2px; }\n\n .ard-log { list-style: none; margin: 0; padding: 10px 0 0; display: flex; flex-direction: column; }\n .ard-log li { display: grid; grid-template-columns: 10px minmax(0, 1fr) auto; align-items: baseline; gap: 8px; padding: 7px 0; border-bottom: 1px solid var(--sg-border, #e5e7eb); }\n .ard-log li.is-empty { display: block; color: var(--sg-muted, #64748b); border: 0; line-height: 1.5; }\n .ard-log-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--sg-muted, #94a3b8); transform: translateY(-1px); }\n .ard-log .is-accept .ard-log-dot { background: var(--sg-success, #16a34a); }\n .ard-log .is-reject .ard-log-dot { background: var(--sg-danger, #dc2626); }\n .ard-log time { font-size: 11px; color: var(--sg-muted, #64748b); font-variant-numeric: tabular-nums; }\n\n /* Data palette: segment pills carry their own colours. */\n .ard-seg {\n display: inline-block;\n padding: 1px 8px;\n border-radius: 999px;\n font-size: 11.5px;\n font-weight: 600;\n color: var(--seg);\n background: color-mix(in srgb, var(--seg) 12%, transparent);\n }\n .ard-hidden { display: none; }\n\n @media (max-width: 860px) {\n .ard-head { padding: 12px 14px; gap: 10px; }\n .ard-logo { display: none; }\n .ard-stats { gap: 14px; }\n .ard-stats dd { font-size: 15px; }\n .ard-side-body { max-height: 340px; }\n .ard-agent { flex-direction: column; align-items: stretch; padding: 10px 14px; }\n .ard-body { grid-template-columns: minmax(0, 1fr); }\n .ard-grid { padding: 10px; }\n .ard-side { margin-left: 0; border-left: 0; }\n }\n @media (prefers-reduced-motion: reduce) {\n .ard-step, .ard-spin, .ard-status.is-info .ard-dot { animation: none; }\n }\n</style>\n"
4073
+ },
4050
4074
  {
4051
4075
  "id": "71-submit-validation",
4052
4076
  "path": "examples/src/demos/71-submit-validation.svelte",
@@ -4179,7 +4203,7 @@ export const examples = [
4179
4203
  "id": "88-staged-editing",
4180
4204
  "path": "examples/src/demos/88-staged-editing.svelte",
4181
4205
  "title": "Staged Editing",
4182
- "category": "Editing",
4206
+ "category": "Misc",
4183
4207
  "blurb": "88. Staged / batch editing - compensation review (Pro) Real-world scenario: comp review cycle. HR opens the grid with proposed salary + bonus + level changes. Each edit goes into a",
4184
4208
  "source": "<script lang=\"ts\">\n /**\n * 88. Staged / batch editing - compensation review (Pro)\n * ------------------------------------------------------\n * Real-world scenario: comp review cycle. HR opens the grid with\n * proposed salary + bonus + level changes. Each edit goes into a\n * draft buffer instead of writing through; the right rail shows the\n * pending diff per employee with totals + the cost impact. The user\n * commits the whole batch atomically (one server roundtrip) or\n * reverts to the original snapshot.\n *\n * Built on `createStagedEditing<TData>()` from @svgrid/enterprise. The grid\n * surface is plain SvGrid - the staging engine sits next to it.\n */\n import {\n SvGrid,\n tableFeatures,\n rowSortingFeature,\n columnFilteringFeature,\n type GridColumns,\n type SvGridApi,\n } from '@svgrid/grid'\n import {\n createStagedEditing,\n installEnterprise,\n type EnterpriseGridApi,\n type StagedChange,\n } from '@svgrid/enterprise'\n\n type Level = 'L3' | 'L4' | 'L5' | 'L6' | 'L7'\n type Employee = {\n id: string\n name: string\n team: 'Engineering' | 'Design' | 'Product' | 'Sales' | 'Support'\n level: Level\n salary: number\n bonus: number\n rating: 'Below' | 'Meets' | 'Exceeds' | 'Outstanding'\n promotionReason: string\n }\n\n let rows = $state<Employee[]>([\n { id: 'e01', name: 'Ada Lovelace', team: 'Engineering', level: 'L6', salary: 215_000, bonus: 30_000, rating: 'Outstanding', promotionReason: 'Shipped the new pivot engine; coached two L4s to L5.' },\n { id: 'e02', name: 'Linus Torvalds', team: 'Engineering', level: 'L7', salary: 280_000, bonus: 50_000, rating: 'Outstanding', promotionReason: 'Architected the row-virtualizer rewrite; cut frame time by 60%.' },\n { id: 'e03', name: 'Grace Hopper', team: 'Engineering', level: 'L6', salary: 220_000, bonus: 28_000, rating: 'Exceeds', promotionReason: '' },\n { id: 'e04', name: 'Margaret Hamilton',team: 'Engineering', level: 'L5', salary: 185_000, bonus: 18_000, rating: 'Exceeds', promotionReason: 'Owned the editor pipeline rewrite.' },\n { id: 'e05', name: 'Don Knuth', team: 'Engineering', level: 'L7', salary: 295_000, bonus: 45_000, rating: 'Outstanding', promotionReason: '' },\n { id: 'e06', name: 'Edsger Dijkstra', team: 'Engineering', level: 'L6', salary: 225_000, bonus: 32_000, rating: 'Meets', promotionReason: '' },\n { id: 'e07', name: 'Barbara Liskov', team: 'Engineering', level: 'L7', salary: 290_000, bonus: 48_000, rating: 'Exceeds', promotionReason: '' },\n { id: 'e08', name: 'Tim Berners-Lee', team: 'Product', level: 'L6', salary: 200_000, bonus: 25_000, rating: 'Meets', promotionReason: '' },\n { id: 'e09', name: 'Yukihiro Matsumoto',team: 'Engineering',level: 'L5', salary: 175_000, bonus: 15_000, rating: 'Meets', promotionReason: '' },\n { id: 'e10', name: 'Brendan Eich', team: 'Engineering', level: 'L6', salary: 210_000, bonus: 26_000, rating: 'Below', promotionReason: '' },\n { id: 'e11', name: 'Anders Hejlsberg', team: 'Engineering', level: 'L7', salary: 275_000, bonus: 42_000, rating: 'Exceeds', promotionReason: '' },\n { id: 'e12', name: 'Bjarne Stroustrup',team: 'Engineering', level: 'L7', salary: 285_000, bonus: 44_000, rating: 'Meets', promotionReason: '' },\n ])\n\n const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n let api = $state<EnterpriseGridApi<typeof features, Employee> | null>(null)\n const stage = createStagedEditing<Employee>()\n\n // Tick to refresh the panel after each record / drop. The stage\n // buffer is plain JS state outside Svelte's reactivity.\n let tick = $state(0)\n const pending = $derived.by(() => { void tick; return stage.changes() })\n const grouped = $derived.by(() => { void tick; return stage.changesByRow() })\n const dirty = $derived.by(() => { void tick; return stage.isDirty() })\n\n // Cost impact preview: sum of staged salary deltas + bonus deltas.\n const costImpact = $derived.by(() => {\n void tick\n let salaryDelta = 0\n let bonusDelta = 0\n for (const c of stage.changes()) {\n const before = Number(c.original) || 0\n const after = Number(c.staged) || 0\n if (c.columnId === 'salary') salaryDelta += after - before\n else if (c.columnId === 'bonus') bonusDelta += after - before\n }\n return { salaryDelta, bonusDelta, total: salaryDelta + bonusDelta }\n })\n\n let committing = $state(false)\n let lastResult = $state<string | null>(null)\n\n async function commit() {\n committing = true\n lastResult = null\n try {\n await stage.commit(async () => {\n await new Promise((r) => setTimeout(r, 700)) // simulate /api/comp/batch\n })\n lastResult = `Committed ${pending.length} change${pending.length === 1 ? '' : 's'}`\n } catch (e) {\n lastResult = `Commit failed: ${String(e)}`\n } finally {\n committing = false\n tick++\n }\n }\n\n function revert() {\n if (!api) return\n const n = pending.length\n stage.revert((rowIndex, columnId, original) => {\n api!.setCellValue(rowIndex, columnId, original)\n })\n tick++\n lastResult = `Reverted ${n} change${n === 1 ? '' : 's'}`\n }\n\n function dropChange(c: StagedChange<Employee>) {\n if (!api) return\n api.setCellValue(c.rowIndex, c.columnId, c.original)\n stage.drop(c.rowId, c.columnId)\n tick++\n }\n\n const fmtMoney = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 })\n function fmtCellValue(c: StagedChange<Employee>, which: 'original' | 'staged'): string {\n const v = which === 'original' ? c.original : c.staged\n if (v == null || v === '') return '-'\n if (c.columnId === 'salary' || c.columnId === 'bonus') return fmtMoney.format(Number(v))\n return String(v)\n }\n function fmtColumn(id: string): string {\n return ({\n name: 'Name', team: 'Team', level: 'Level', salary: 'Salary',\n bonus: 'Bonus', rating: 'Rating', promotionReason: 'Reason',\n } as Record<string, string>)[id] ?? id\n }\n\n const columns: GridColumns<Employee> = [\n { field: 'name', header: 'Employee', editable: false, width: 170, tooltip: 'Read-only - change through HRIS' },\n { field: 'team', header: 'Team', editable: false, width: 120 },\n { field: 'level', header: 'Level',\n editorType: 'select', editorOptions: ['L3', 'L4', 'L5', 'L6', 'L7'], width: 100 },\n { field: 'rating', header: 'Rating',\n editorType: 'rich-select',\n editorOptions: ['Below', 'Meets', 'Exceeds', 'Outstanding'], width: 140 },\n { field: 'salary', header: 'Salary',\n editorType: 'number',\n format: { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } }, width: 140 },\n { field: 'bonus', header: 'Bonus',\n editorType: 'number',\n format: { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } }, width: 130 },\n { field: 'promotionReason', header: 'Promotion reason',\n editorType: 'textarea', width: 280,\n tooltip: 'Required when raising level. Multi-line; press Tab or Ctrl+Enter to commit.' },\n ]\n</script>\n\n<section class=\"staged-shell flex flex-col flex-1 min-h-0 gap-3\">\n <!-- Header strip -->\n <header class=\"staged-head shrink-0\">\n <div class=\"head-left\">\n <span class=\"head-badge\">Pro</span>\n <div>\n <h2>2026 Comp review · Engineering</h2>\n <p>Edit any cell - changes stage as a draft until you Commit.</p>\n </div>\n </div>\n <div class=\"head-actions\">\n <button type=\"button\" class=\"ghost\"\n disabled={committing || !dirty}\n onclick={revert}>\n ↺ Revert all\n </button>\n <button type=\"button\" class=\"primary\"\n disabled={committing || !dirty}\n onclick={commit}>\n {#if committing}\n Committing…\n {:else}\n ✓ Commit {pending.length} change{pending.length === 1 ? '' : 's'}\n {/if}\n </button>\n </div>\n </header>\n\n <!-- KPI strip -->\n <div class=\"kpi-row shrink-0\">\n <div class=\"kpi\">\n <div class=\"kpi-label\">Employees</div>\n <div class=\"kpi-value\">{rows.length}</div>\n </div>\n <div class=\"kpi\" class:kpi-pending={pending.length > 0}>\n <div class=\"kpi-label\">Pending edits</div>\n <div class=\"kpi-value\">{pending.length}</div>\n <div class=\"kpi-sub\">{grouped.length} employee{grouped.length === 1 ? '' : 's'} affected</div>\n </div>\n <div class=\"kpi\" class:kpi-up={costImpact.salaryDelta > 0} class:kpi-down={costImpact.salaryDelta < 0}>\n <div class=\"kpi-label\">Salary delta</div>\n <div class=\"kpi-value\">{costImpact.salaryDelta >= 0 ? '+' : ''}{fmtMoney.format(costImpact.salaryDelta)}</div>\n </div>\n <div class=\"kpi\" class:kpi-up={costImpact.bonusDelta > 0} class:kpi-down={costImpact.bonusDelta < 0}>\n <div class=\"kpi-label\">Bonus delta</div>\n <div class=\"kpi-value\">{costImpact.bonusDelta >= 0 ? '+' : ''}{fmtMoney.format(costImpact.bonusDelta)}</div>\n </div>\n <div class=\"kpi kpi-accent\">\n <div class=\"kpi-label\">Total impact</div>\n <div class=\"kpi-value\">{costImpact.total >= 0 ? '+' : ''}{fmtMoney.format(costImpact.total)}</div>\n <div class=\"kpi-sub\">annualised</div>\n </div>\n </div>\n\n {#if lastResult}\n <div class=\"result-banner shrink-0\">{lastResult}</div>\n {/if}\n\n <div class=\"layout flex-1 min-h-0\">\n <!-- Grid -->\n <div class=\"grid-card min-h-0\">\n <SvGrid responsive={true}\n columnResize\n data={rows}\n columns={columns}\n features={features}\n filterMode=\"menu\"\n selectionMode=\"cell\"\n enableInlineEditing={true}\n enableCellSelection={true}\n rowHeight={40}\n containerHeight=\"100%\"\n fitColumns={true}\n onApiReady={(next) => (api = installEnterprise(next))}\n onCellValueChange={(e) => { stage.record(e); tick++ }}\n />\n </div>\n\n <!-- Right rail: pending changes per row -->\n <aside class=\"stage-rail\">\n <header>\n <strong>Pending changes</strong>\n {#if dirty}<span class=\"badge\">{pending.length}</span>{/if}\n </header>\n {#if !dirty}\n <div class=\"empty\">\n <div class=\"empty-icon\">✎</div>\n <p><strong>No pending changes.</strong></p>\n <p>Edit any cell - level, rating, salary, bonus, or reason - and the diff lands here.</p>\n </div>\n {:else}\n <div class=\"rail-body\">\n {#each grouped as g (g.rowId)}\n {@const emp = rows.find((r) => r.id === g.rowId)}\n <article class=\"emp-card\">\n <header class=\"emp-head\">\n <div class=\"emp-id\">\n <span class=\"emp-avatar\" aria-hidden=\"true\">{(emp?.name ?? '?').split(' ').map((w) => w[0]).slice(0, 2).join('')}</span>\n <div>\n <div class=\"emp-name\">{emp?.name ?? g.rowId}</div>\n <div class=\"emp-meta\">{emp?.team} · {emp?.level}</div>\n </div>\n </div>\n <span class=\"emp-cnt\">{g.cells.length} change{g.cells.length === 1 ? '' : 's'}</span>\n </header>\n <ul class=\"emp-diffs\">\n {#each g.cells as c (c.columnId)}\n <li>\n <span class=\"diff-col\">{fmtColumn(c.columnId)}</span>\n <span class=\"diff-from\">{fmtCellValue(c, 'original')}</span>\n <span class=\"diff-arrow\">→</span>\n <span class=\"diff-to\">{fmtCellValue(c, 'staged')}</span>\n <button type=\"button\" class=\"diff-drop\"\n aria-label=\"Discard this change\"\n title=\"Discard\"\n onclick={() => dropChange(c)}>×</button>\n </li>\n {/each}\n </ul>\n </article>\n {/each}\n </div>\n {/if}\n </aside>\n </div>\n</section>\n\n<style>\n .staged-shell {\n font-family: inherit;\n /* Diff colours carry meaning (removed vs added) rather than brand, so they\n stay red/green under every preset - only their lightness tracks the mode\n so they stay legible on a dark ground. */\n --diff-neg: #b91c1c;\n --diff-pos: #047857;\n }\n :global([data-theme=\"dark\"]) .staged-shell {\n --diff-neg: #f87171;\n --diff-pos: #34d399;\n }\n\n /* ---- Header ---- */\n .staged-head {\n display: flex; align-items: center; justify-content: space-between;\n gap: 16px; flex-wrap: wrap;\n padding: 14px 16px;\n border: 1px solid var(--sg-border, #e2e8f0);\n background: var(--sg-bg-subtle, var(--sg-header-bg, #f8fafc));\n border-radius: 10px;\n }\n .head-left { display: flex; align-items: center; gap: 12px; min-width: 0; }\n .head-badge {\n display: inline-block;\n background: var(--sg-accent, #6366f1);\n color: var(--sg-on-accent, #fff); font-size: 10px; font-weight: 700; letter-spacing: 0.08em;\n padding: 4px 10px; border-radius: 999px; text-transform: uppercase;\n }\n .staged-head h2 { margin: 0; font-size: 16px; font-weight: 700; color: var(--sg-fg, #0f172a); }\n .staged-head p { margin: 2px 0 0; font-size: 12.5px; color: var(--sg-muted, #64748b); }\n .head-actions { display: inline-flex; gap: 8px; align-items: center; }\n .head-actions .ghost {\n background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a);\n border: 1px solid var(--sg-border, #cbd5e1);\n border-radius: 6px; padding: 7px 14px;\n font-size: 12.5px; font-weight: 600; cursor: pointer;\n }\n .head-actions .ghost:hover:not(:disabled) { background: var(--sg-row-hover-bg, rgba(148, 163, 184, 0.10)); }\n .head-actions .ghost:disabled { opacity: 0.4; cursor: default; }\n .head-actions .primary {\n background: #047857; color: #fff; border: 0; border-radius: 6px;\n padding: 7px 16px; font-size: 12.5px; font-weight: 700; cursor: pointer;\n box-shadow: 0 2px 8px rgba(4, 120, 87, 0.18);\n }\n .head-actions .primary:hover:not(:disabled) { background: #065f46; }\n .head-actions .primary:disabled { background: var(--sg-row-hover-bg, #e2e8f0); color: var(--sg-muted, #94a3b8); cursor: default; box-shadow: none; }\n\n /* ---- KPI strip ---- */\n .kpi-row {\n display: grid;\n grid-template-columns: repeat(5, minmax(0, 1fr));\n gap: 10px;\n }\n .kpi {\n border: 1px solid var(--sg-border, #e2e8f0);\n background: var(--sg-bg, #fff);\n border-radius: 10px;\n padding: 10px 14px;\n display: flex; flex-direction: column; gap: 2px;\n }\n .kpi-label { font-size: 10.5px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--sg-muted, #64748b); font-weight: 600; }\n .kpi-value { font-size: 20px; font-weight: 700; font-variant-numeric: tabular-nums; color: var(--sg-fg, #0f172a); line-height: 1.1; }\n .kpi-sub { font-size: 11px; color: var(--sg-muted, #94a3b8); }\n .kpi-pending { border-left: 3px solid #f59e0b; }\n .kpi-up { border-left: 3px solid #10b981; }\n .kpi-up .kpi-value { color: var(--diff-pos, #047857); }\n .kpi-down { border-left: 3px solid #ef4444; }\n .kpi-down .kpi-value { color: var(--diff-neg, #b91c1c); }\n .kpi-accent { border-left: 3px solid var(--sg-accent, #6366f1); background: linear-gradient(135deg, color-mix(in srgb, var(--sg-accent, #6366f1) 6%, transparent), transparent); }\n .kpi-accent .kpi-value { color: var(--sg-accent, #4338ca); }\n\n .result-banner {\n padding: 8px 14px;\n background: rgba(16, 185, 129, 0.10);\n color: var(--diff-pos, #047857);\n border: 1px solid rgba(16, 185, 129, 0.25);\n border-radius: 8px;\n font-size: 12.5px; font-weight: 600;\n }\n\n /* ---- Layout ---- */\n .layout {\n display: grid;\n grid-template-columns: minmax(0, 1fr) 360px;\n gap: 12px;\n min-height: 0;\n }\n .grid-card {\n border: 1px solid var(--sg-border, #e2e8f0);\n background: var(--sg-bg, #fff);\n border-radius: 10px;\n overflow: hidden;\n min-width: 0;\n }\n\n /* ---- Right rail ---- */\n .stage-rail {\n display: flex; flex-direction: column; min-height: 0;\n border: 1px solid var(--sg-border, #e2e8f0);\n background: var(--sg-bg, #fff);\n border-radius: 10px; overflow: hidden;\n }\n .stage-rail header {\n display: flex; align-items: center; justify-content: space-between;\n padding: 10px 14px; border-bottom: 1px solid var(--sg-border, #e2e8f0);\n background: var(--sg-header-bg, #f8fafc);\n }\n .stage-rail header strong { font-size: 13px; color: var(--sg-fg, #0f172a); }\n .stage-rail .badge {\n background: var(--sg-accent, #4338ca); color: var(--sg-on-accent, #fff);\n font-size: 11px; font-weight: 700;\n padding: 2px 8px; border-radius: 999px;\n }\n\n .empty {\n display: flex; flex-direction: column; align-items: center; justify-content: center;\n flex: 1; padding: 24px; text-align: center; gap: 4px;\n color: var(--sg-muted, #94a3b8);\n }\n .empty-icon {\n width: 48px; height: 48px;\n border-radius: 999px;\n background: color-mix(in srgb, var(--sg-muted, #94a3b8) 12%, transparent);\n display: grid; place-items: center;\n color: var(--sg-muted, #94a3b8);\n font-size: 22px;\n margin-bottom: 6px;\n }\n .empty p { margin: 0; font-size: 13px; line-height: 1.45; max-width: 240px; }\n .empty p strong { color: var(--sg-fg, #0f172a); }\n\n .rail-body {\n overflow-y: auto;\n padding: 10px;\n display: flex; flex-direction: column; gap: 8px;\n min-height: 0;\n }\n\n .emp-card {\n border: 1px solid var(--sg-border, #e2e8f0);\n background: var(--sg-bg, #fff);\n border-radius: 8px;\n overflow: hidden;\n }\n .emp-head {\n display: flex; align-items: center; justify-content: space-between;\n gap: 6px;\n padding: 8px 10px;\n background: var(--sg-bg-subtle, var(--sg-header-bg, #f8fafc));\n border-bottom: 1px solid var(--sg-border, #e2e8f0);\n }\n .emp-id { display: inline-flex; align-items: center; gap: 8px; min-width: 0; }\n .emp-avatar {\n width: 28px; height: 28px; border-radius: 999px;\n background: var(--sg-accent, #6366f1);\n color: var(--sg-on-accent, #fff); font-size: 11px; font-weight: 700;\n display: grid; place-items: center;\n flex-shrink: 0;\n }\n .emp-name { font-size: 13px; font-weight: 600; color: var(--sg-fg, #0f172a); }\n .emp-meta { font-size: 10.5px; color: var(--sg-muted, #64748b); }\n .emp-cnt { font-size: 10.5px; color: var(--sg-muted, #64748b); }\n\n .emp-diffs { list-style: none; margin: 0; padding: 4px 0; }\n .emp-diffs li {\n display: grid;\n grid-template-columns: 90px 1fr 14px 1fr 22px;\n align-items: center;\n gap: 6px;\n padding: 4px 10px;\n font-size: 12px;\n }\n .emp-diffs li + li { border-top: 1px dashed var(--sg-border, rgba(148, 163, 184, 0.20)); }\n .diff-col { font-size: 10.5px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--sg-muted, #64748b); font-weight: 600; }\n .diff-from { color: var(--diff-neg, #b91c1c); text-decoration: line-through; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .diff-arrow { color: var(--sg-muted, #94a3b8); text-align: center; }\n .diff-to { color: var(--diff-pos, #047857); font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .diff-drop {\n background: transparent; border: 0;\n color: var(--sg-muted, #94a3b8);\n width: 22px; height: 22px; border-radius: 4px;\n cursor: pointer; font-size: 14px; line-height: 1;\n }\n .diff-drop:hover { background: rgba(239, 68, 68, 0.10); color: var(--diff-neg, #b91c1c); }\n /* Phone: content-sized rows so the pending-changes rail is not clipped under the grid. */\n @media (max-width: 639px), (max-height: 500px) and (pointer: coarse) {\n .layout { grid-auto-rows: max-content; }\n .stage-rail { max-height: 60vh; overflow-y: auto; }\n }\n</style>\n"
4185
4209
  },
@@ -4405,7 +4429,7 @@ export const docs = [
4405
4429
  "path": "docs/enterprise/README.md",
4406
4430
  "title": "Enterprise feature pack",
4407
4431
  "section": "Enterprise tier",
4408
- "markdown": "# Enterprise feature pack\n\n`@svgrid/enterprise` is a paid add-on for `@svgrid/grid`. It bolts onto\nthe same `<SvGrid>` you already have and adds five feature areas: the\nserver-side row model, data export, data import, pivot tables, and the\nKanban, Scheduler and Spreadsheet views of the same grid. (The AI helpers\nare built in and **free** in `@svgrid/grid` - see\n[AI assistant](../help/ai.md).)\n\n![The @svgrid/enterprise pack bolts data export, data import, and pivot tables onto the same SvGrid you already have.](/docs-media/enterprise-pack.svg)\n\n```bash\npnpm add @svgrid/enterprise\n```\n\n```ts\nimport { installEnterprise, setLicenseKey } from '@svgrid/enterprise'\n\nsetLicenseKey('YOUR-LICENSE-KEY') // once, at app startup\nconst pro = installEnterprise(api) // wraps a SvGridApi with Enterprise methods\n```\n\nThat's the whole integration. Every Enterprise helper hangs off the api object\nyou already have; the grid component stays Community.\n\n## What ships in Enterprise\n\n### [Data export](../help/export.md)\n\n`pro.exportData(opts)` writes the current view to Excel (xlsx), PDF,\nCSV, TSV, or HTML from a single call.\n\n**CSV, TSV and JSON export do not need Enterprise** - they are free in\n`@svgrid/grid`, along with copy-to-clipboard. What Enterprise adds is\nxlsx, PDF, styled HTML and XML, plus the unified entry point with\ncolumn resolution and group handling. See\n[the export page](../help/export.md) for the exact split.\n\nThe xlsx writer honours:\n\n- **Cell + row styles** via `opts.styles` - read the same `--sg-*`\n tokens the grid renders with so the file matches the theme.\n- **Page header + footer** lines with text or embedded images\n (`opts.header`, `opts.footer`).\n- **Embedded images** from cell values when columns are listed in\n `opts.imageFields`.\n- **Multiple sheets** in one workbook via `opts.sheets`.\n- **Printable view** via `pro.print(opts)` - opens a new window with\n repeat-on-page headers, cover page, page-size + orientation.\n\nDemos: [56 theme-matched](../../examples/src/demos/56-export-theme-matched.svelte),\n[57 header + footer + logo](../../examples/src/demos/57-export-header-footer-logo.svelte),\n[58 images](../../examples/src/demos/58-export-with-images.svelte),\n[59 multi-sheet](../../examples/src/demos/59-export-multi-sheet.svelte).\n\n### [Data import](../help/import.md)\n\n`pro.importData(opts)` reads an Excel / CSV / TSV / JSON file (or\ninline text), maps columns to your row shape, validates each row, and\nreturns a typed `ImportResult` with `rows`, `errors`, and a `summary`.\nYou decide whether to commit the rows into the grid or preview first.\n\nDemo: [53 Excel import](../../examples/src/demos/53-excel-import.svelte).\n\n### AI assistant - now built-in + free\n\nThe natural-language filter, smart-fill, summarise, classify, chart-this,\nfind-anomalies and natural-language-export helpers moved into the free\n`@svgrid/grid` package. Import them from `@svgrid/grid` and register a provider\nwith `setAIProvider(yourAdapter)` (no model client is bundled - you bring\nOpenAI / Anthropic / Ollama / local). See [AI assistant](../help/ai.md). The\nonly enterprise touch-point is `aiExport`'s write step, which uses this pack's\nexport engine for xlsx / pdf.\n\nDemo: [51 AI assistant](../../examples/src/demos/51-ai-assistant.svelte).\n\n### [Pivot tables](../help/pivot.md)\n\n`createPivotModel(data, config)` (or `pro.pivot.build(config)` against\nthe live api) returns `{ rows, columns }` you feed to a separate\n`<SvGrid>` instance. Supports row + column axes, eight built-in\naggregators (sum/avg/min/max/count/countDistinct/first/last) or\ncustom, grand-total row + column, subtotals, custom axis sort.\n\nDemo: [52 pivot table + designer](../../examples/src/demos/52-pivot-table.svelte).\n\n### [Server-Side Row Model](../help/server/server-grouping.md)\n\n`createServerRowModel(source, options)` runs over the free datasource\ncontract (`ServerDataSource.getRows`) and hands the grid one `rowModel`\nprop: lazy grouping and tree data one level at a time with a block cache\nper level, aggregates, child counts and grand totals, server-side pivot\nwith `SvPivotDesigner` in server mode, transactions on loaded rows,\npaging over the tree, and a selection kept as a rule so select-all\nreaches rows the grid never loaded, with a bulk edit by rule. Flat paging\nand infinite scroll stay free in `@svgrid/grid`.\n\nDemos: [467 one million rows](../../examples/src/demos/467-server-row-model-1m.svelte),\n[468 server pivot](../../examples/src/demos/468-server-pivot.svelte),\n[469 tree data](../../examples/src/demos/469-server-tree-data.svelte),\n[470 transactions](../../examples/src/demos/470-server-transactions.svelte),\n[471 selection by rule](../../examples/src/demos/471-server-selection.svelte),\n[472 request to SQL](../../examples/src/demos/472-server-sql-planner.svelte),\n[473 grouping rules](../../examples/src/demos/473-server-grouping-rules.svelte),\n[482 CRUD with a version check](../../examples/src/demos/482-server-crud.svelte),\n[483 master-detail](../../examples/src/demos/483-server-master-detail.svelte),\n[500 queries in a Web Worker](../../examples/src/demos/500-worker-data-source.svelte).\n\n### Views of the same grid\n\nThe `board` and `scheduler` props and their config types are free in\n`@svgrid/grid`; what Enterprise ships is the renderer behind each,\nregistered once with `enableBoardView()` or `enableSchedulerView()`\n(`installEnterprise(api)` calls both). The same rows, columns, sort and\nfilter feed every one of them. A [Gantt view](../help/rows/gantt.md) of the\nsame grid is in progress and due on 1 November 2026.\n\n- [Kanban board](../help/rows/kanban-board.md) - cards in lanes, drag-and-drop,\n swimlanes, WIP limits, a card drawer.\n- [Scheduler / calendar](../help/rows/scheduler.md) - month, week, day, agenda\n and timeline views with resources, recurrence and booking rules.\n- [The spreadsheet shell](../help/cells/spreadsheet-shell.md) - `<SvSheet />`\n wraps the grid in a ribbon, formula bar, gutter and sheet tabs over the\n [formula engine](../help/spreadsheet-formulas.md).\n\n## Licensing\n\nYou can evaluate the pack without asking for a key. Until a valid\nlicense key is set, everything still functions, and loading the\nEnterprise module displays a watermark on the grid and a console message\nabout the Enterprise package. Set a key once at app startup and both\ndisappear:\n\n```ts\nimport { setLicenseKey } from '@svgrid/enterprise'\nsetLicenseKey('YOUR-LICENSE-KEY') // the key from your order\n```\n\nThe pack comes in two editions, both covering unlimited production apps.\n**Grid** is everything on this page except the spreadsheet, SvGrid Base and Studio;\n**Suite** is all of it. The Indie license is the Grid edition at a lower\nprice for freelancers and companies under $1M revenue, without support.\nA key names its edition, and a key that predates\neditions reads as Suite. A Grid key that opens `<SvSheet>` or `<SvBase>` is treated the\nsame way as an unlicensed build: the feature runs, with the watermark and a\nconsole notice naming the edition that covers it.\n\nPricing and the OEM tier for redistribution: <https://svgrid.com/pricing/>.\nSee also [licensing](./licensing.md).\n\n## How Enterprise integrates\n\n```ts\nimport { SvGrid, type SvGridApi } from '@svgrid/grid'\nimport { installEnterprise, setLicenseKey, type EnterpriseGridApi } from '@svgrid/enterprise'\n\nsetLicenseKey(import.meta.env.VITE_SVPRO_KEY)\n\nlet api = $state<EnterpriseGridApi<typeof features, Order> | null>(null)\n```\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onApiReady={(next: SvGridApi<typeof features, Order>) => {\n api = installEnterprise(next)\n }}\n/>\n\n<button onclick={() => api?.exportData({ format: 'xlsx', filename: 'orders' })}>\n Export to Excel\n</button>\n```\n\n`installEnterprise` mutates and returns the same api object - existing\nreferences keep working. The `EnterpriseGridApi` type extends `SvGridApi` so\nthe grid's existing methods are still there alongside the new ones.\n\n## Tree-shaking\n\nEach Enterprise module is a separate subpath export:\n\n```ts\nimport { exportGrid } from '@svgrid/enterprise/export' // export only\nimport { importData } from '@svgrid/enterprise/import' // import only\nimport { createPivotModel } from '@svgrid/enterprise/pivot' // pivot only\n// AI helpers are free + built in: import { aiFilter } from '@svgrid/grid'\n```\n\nIf you only need export, the AI provider plumbing, pivot engine, and\nimport parser don't ship. The `@svgrid/enterprise` barrel import is\nconvenient; the subpaths are smaller.\n\n## Peer dependencies\n\n| Feature | Peer dep | Optional? |\n| ------- | -------------------- | ------------------------------------------ |\n| xlsx | `jszip` | Yes - only loaded when xlsx is exported. |\n| pdf | `pdfmake` | Yes - only loaded when pdf is exported. |\n| import | `jszip` (xlsx only) | Yes - only for xlsx import. |\n| AI | - | -. You bring your own provider client. |\n| pivot | - | -. Pure TypeScript, no runtime deps. |\n\nInstall only what you need:\n\n```bash\npnpm add @svgrid/enterprise jszip # community + Enterprise + xlsx\npnpm add @svgrid/enterprise jszip pdfmake # also pdf\n```\n\n## See also\n\n- [Getting started](../getting-started.md) - if you haven't seen the\n Community walkthrough yet.\n- [Help index](../help/index.md) - all topic pages including the\n Enterprise pages.\n- [Missing features](../help/missing-features.md) - the honest gap list.\n"
4432
+ "markdown": "# Enterprise feature pack\n\n`@svgrid/enterprise` is a paid add-on for `@svgrid/grid`. It bolts onto\nthe same `<SvGrid>` you already have and adds five feature areas: the\nserver-side row model, data export, data import, pivot tables, and the\nKanban, Scheduler and Spreadsheet views of the same grid. (The AI helpers\nare built in and **free** in `@svgrid/grid` - see\n[AI assistant](../help/ai.md).)\n\n![The @svgrid/enterprise pack bolts data export, data import, and pivot tables onto the same SvGrid you already have.](/docs-media/enterprise-pack.svg)\n\n```bash\npnpm add @svgrid/enterprise\n```\n\n```ts\nimport { installEnterprise, setLicenseKey } from '@svgrid/enterprise'\n\nsetLicenseKey('YOUR-LICENSE-KEY') // once, at app startup\nconst pro = installEnterprise(api) // wraps a SvGridApi with Enterprise methods\n```\n\nThat's the whole integration. Every Enterprise helper hangs off the api object\nyou already have; the grid component stays Community.\n\n## What ships in Enterprise\n\n### [Data export](../help/export.md)\n\n`pro.exportData(opts)` writes the current view to Excel (xlsx), PDF,\nCSV, TSV, or HTML from a single call.\n\n**CSV, TSV and JSON export do not need Enterprise** - they are free in\n`@svgrid/grid`, along with copy-to-clipboard. What Enterprise adds is\nxlsx, PDF, styled HTML and XML, plus the unified entry point with\ncolumn resolution and group handling. See\n[the export page](../help/export.md) for the exact split.\n\nThe xlsx writer honours:\n\n- **Cell + row styles** via `opts.styles` - read the same `--sg-*`\n tokens the grid renders with so the file matches the theme.\n- **Page header + footer** lines with text or embedded images\n (`opts.header`, `opts.footer`).\n- **Embedded images** from cell values when columns are listed in\n `opts.imageFields`.\n- **Multiple sheets** in one workbook via `opts.sheets`.\n- **Printable view** via `pro.print(opts)` - opens a new window with\n repeat-on-page headers, cover page, page-size + orientation.\n\nDemos: [56 theme-matched](../../examples/src/demos/56-export-theme-matched.svelte),\n[57 header + footer + logo](../../examples/src/demos/57-export-header-footer-logo.svelte),\n[58 images](../../examples/src/demos/58-export-with-images.svelte),\n[59 multi-sheet](../../examples/src/demos/59-export-multi-sheet.svelte).\n\n### [Data import](../help/import.md)\n\n`pro.importData(opts)` reads an Excel / CSV / TSV / JSON file (or\ninline text), maps columns to your row shape, validates each row, and\nreturns a typed `ImportResult` with `rows`, `errors`, and a `summary`.\nYou decide whether to commit the rows into the grid or preview first.\n\nDemo: [53 Excel import](../../examples/src/demos/53-excel-import.svelte).\n\n### AI assistant - now built-in + free\n\nThe natural-language filter, smart-fill, summarise, classify, chart-this,\nfind-anomalies and natural-language-export helpers moved into the free\n`@svgrid/grid` package. Import them from `@svgrid/grid` and register a provider\nwith `setAIProvider(yourAdapter)` (no model client is bundled - you bring\nOpenAI / Anthropic / Ollama / local). See [AI assistant](../help/ai.md). The\nonly enterprise touch-point is `aiExport`'s write step, which uses this pack's\nexport engine for xlsx / pdf.\n\nDemo: [51 AI assistant](../../examples/src/demos/51-ai-assistant.svelte).\n\n### [Pivot tables](../help/pivot.md)\n\n`createPivotModel(data, config)` (or `pro.pivot.build(config)` against\nthe live api) returns `{ rows, columns }` you feed to a separate\n`<SvGrid>` instance. Supports row + column axes, eight built-in\naggregators (sum/avg/min/max/count/countDistinct/first/last) or\ncustom, grand-total row + column, subtotals, custom axis sort.\n\nDemo: [52 pivot table + designer](../../examples/src/demos/52-pivot-table.svelte).\n\n### [Server-Side Row Model](../help/server/server-grouping.md)\n\n`createServerRowModel(source, options)` runs over the free datasource\ncontract (`ServerDataSource.getRows`) and hands the grid one `rowModel`\nprop: lazy grouping and tree data one level at a time with a block cache\nper level, aggregates, child counts and grand totals, server-side pivot\nwith `SvPivotDesigner` in server mode, transactions on loaded rows,\npaging over the tree, and a selection kept as a rule so select-all\nreaches rows the grid never loaded, with a bulk edit by rule. Flat paging\nand infinite scroll stay free in `@svgrid/grid`.\n\nDemos: [467 one million rows](../../examples/src/demos/467-server-row-model-1m.svelte),\n[468 server pivot](../../examples/src/demos/468-server-pivot.svelte),\n[469 tree data](../../examples/src/demos/469-server-tree-data.svelte),\n[470 transactions](../../examples/src/demos/470-server-transactions.svelte),\n[471 selection by rule](../../examples/src/demos/471-server-selection.svelte),\n[472 request to SQL](../../examples/src/demos/472-server-sql-planner.svelte),\n[473 grouping rules](../../examples/src/demos/473-server-grouping-rules.svelte),\n[482 CRUD with a version check](../../examples/src/demos/482-server-crud.svelte),\n[483 master-detail](../../examples/src/demos/483-server-master-detail.svelte),\n[500 queries in a Web Worker](../../examples/src/demos/500-worker-data-source.svelte).\n\n### Views of the same grid\n\nThe `board` and `scheduler` props and their config types are free in\n`@svgrid/grid`; what Enterprise ships is the renderer behind each,\nregistered once with `enableBoardView()` or `enableSchedulerView()`\n(`installEnterprise(api)` calls both). The same rows, columns, sort and\nfilter feed every one of them. A [Gantt view](../help/rows/gantt.md) of the\nsame grid is in progress and due on 1 November 2026.\n\n- [Kanban board](../help/rows/kanban-board.md) - cards in lanes, drag-and-drop,\n swimlanes, WIP limits, a card drawer.\n- [Scheduler / calendar](../help/rows/scheduler.md) - month, week, day, agenda\n and timeline views with resources, recurrence and booking rules.\n- [The spreadsheet shell](../help/cells/spreadsheet-shell.md) - `<SvSheet />`\n wraps the grid in a ribbon, formula bar, gutter and sheet tabs over the\n [formula engine](../help/spreadsheet-formulas.md).\n\n### Grid filter and sort additions\n\nFour additions to the grid's own filtering and sorting, each switched on once\n(`installEnterprise(api)` runs the three `enable` calls) and then used through\nordinary column options. They plug into small grid seams, so a grid without\nthem carries none of their code.\n\n```ts\nimport {\n enableRelativeDateFilters,\n enableFilterLabels,\n enableRowCount,\n blanksLast,\n} from '@svgrid/enterprise'\n\nenableRelativeDateFilters() // Today, Before today, After today, Next 7 days, Last 7 days\nenableFilterLabels() // the filter checklist reads as the cells do\nenableRowCount() // statusBar={{ rows: true }}: \"12 of 250 rows\"\n\nconst columns = [\n { field: 'due', header: 'Due', cellDataType: 'dateString', sortComparator: blanksLast('date') },\n]\n```\n\n- [Relative date operators](../help/filtering/date-filter.md#today-overdue-next-7-days-enterprise)\n take no value; a server data source receives the dates they mean.\n `resolveRelativeDateFilter(filter)` does the same for an `externalFilter` query.\n- [Checklist labels](../help/filtering/set-filter.md#labels-from-the-cells-enterprise)\n come from a `cell` that returns text, static `editorOptions`, or the\n `formatter`; the filter still matches the stored value.\n- [The row count](../help/status-bar.md#row-count-enterprise) sits outside the\n bar's live region; `getRowCounts(api)` returns `{ total, filtered }`.\n- [`blanksLast` / `blanksFirst`](../help/rows/row-sorting.md#keep-blanks-at-one-end-enterprise)\n hold blank cells at one end whichever way the column sorts.\n\nDemo 701 shows all four on a review queue.\n\n## Licensing\n\nYou can evaluate the pack without asking for a key. Until a valid\nlicense key is set, everything still functions, and loading the\nEnterprise module displays a watermark on the grid and a console message\nabout the Enterprise package. Set a key once at app startup and both\ndisappear:\n\n```ts\nimport { setLicenseKey } from '@svgrid/enterprise'\nsetLicenseKey('YOUR-LICENSE-KEY') // the key from your order\n```\n\nThe pack comes in two editions, both covering unlimited production apps.\n**Grid** is everything on this page except the spreadsheet, SvGrid Base and Studio;\n**Suite** is all of it. The Indie license is the Grid edition at a lower\nprice for freelancers and companies under $1M revenue, without support.\nA key names its edition, and a key that predates\neditions reads as Suite. A Grid key that opens `<SvSheet>` or `<SvBase>` is treated the\nsame way as an unlicensed build: the feature runs, with the watermark and a\nconsole notice naming the edition that covers it.\n\nPricing and the OEM tier for redistribution: <https://svgrid.com/pricing/>.\nSee also [licensing](./licensing.md).\n\n## How Enterprise integrates\n\n```ts\nimport { SvGrid, type SvGridApi } from '@svgrid/grid'\nimport { installEnterprise, setLicenseKey, type EnterpriseGridApi } from '@svgrid/enterprise'\n\nsetLicenseKey(import.meta.env.VITE_SVPRO_KEY)\n\nlet api = $state<EnterpriseGridApi<typeof features, Order> | null>(null)\n```\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onApiReady={(next: SvGridApi<typeof features, Order>) => {\n api = installEnterprise(next)\n }}\n/>\n\n<button onclick={() => api?.exportData({ format: 'xlsx', filename: 'orders' })}>\n Export to Excel\n</button>\n```\n\n`installEnterprise` mutates and returns the same api object - existing\nreferences keep working. The `EnterpriseGridApi` type extends `SvGridApi` so\nthe grid's existing methods are still there alongside the new ones.\n\n## Tree-shaking\n\nEach Enterprise module is a separate subpath export:\n\n```ts\nimport { exportGrid } from '@svgrid/enterprise/export' // export only\nimport { importData } from '@svgrid/enterprise/import' // import only\nimport { createPivotModel } from '@svgrid/enterprise/pivot' // pivot only\n// AI helpers are free + built in: import { aiFilter } from '@svgrid/grid'\n```\n\nIf you only need export, the AI provider plumbing, pivot engine, and\nimport parser don't ship. The `@svgrid/enterprise` barrel import is\nconvenient; the subpaths are smaller.\n\n## Peer dependencies\n\n| Feature | Peer dep | Optional? |\n| ------- | -------------------- | ------------------------------------------ |\n| xlsx | `jszip` | Yes - only loaded when xlsx is exported. |\n| pdf | `pdfmake` | Yes - only loaded when pdf is exported. |\n| import | `jszip` (xlsx only) | Yes - only for xlsx import. |\n| AI | - | -. You bring your own provider client. |\n| pivot | - | -. Pure TypeScript, no runtime deps. |\n\nInstall only what you need:\n\n```bash\npnpm add @svgrid/enterprise jszip # community + Enterprise + xlsx\npnpm add @svgrid/enterprise jszip pdfmake # also pdf\n```\n\n## See also\n\n- [Getting started](../getting-started.md) - if you haven't seen the\n Community walkthrough yet.\n- [Help index](../help/index.md) - all topic pages including the\n Enterprise pages.\n- [Missing features](../help/missing-features.md) - the honest gap list.\n"
4409
4433
  },
4410
4434
  {
4411
4435
  "slug": "enterprise/evaluation",
@@ -5308,7 +5332,7 @@ export const docs = [
5308
5332
  "path": "docs/help/columns/column-spanning.md",
5309
5333
  "title": "Column & row spanning (merged cells)",
5310
5334
  "section": "Columns",
5311
- "markdown": "# Column & row spanning (merged cells)\n\nSpanning lets a single body cell cover **multiple columns** and/or **rows** -\nmerged report headers, grouped labels, financial statements. SvGrid does this\nwith a real `colspan` / `rowspan` merge engine; there are three ways to drive\nit, and the first is the one to reach for on a new grid.\n\n<div data-docs-demo=\"170-cell-merging\" data-height=\"480\"></div>\n\n## 0. The `mergedCells` prop (the renderer's own)\n\nThe grid draws merges itself from a list of origins with their spans, in\ndisplay indices:\n\n```svelte\n<SvGrid\n {data} {columns}\n mergedCells={[\n { rowIndex: 0, colIndex: 0, rowSpan: 1, colSpan: 4 }, // a title across A1:D1\n { rowIndex: 3, colIndex: 1, rowSpan: 3, colSpan: 1 }, // B4:B6 as one cell\n ]}\n/>\n```\n\nThe origin's td takes the `rowspan` / `colspan` and shows the origin's\nvalue; the covered cells are not drawn at all, so there is nothing to\nhide after the fact. A selection grows to whole merges (a merged cell is\none cell), the active cell inside a merge is its origin, the arrow keys\nstep over a merge as one cell, and `api.getMergedCells()` reads the list\nback. Under row virtualization a merge whose origin has scrolled out of\nthe rendered window is drawn from its first rendered row with the rows\nthat remain, and one that crosses the frozen boundary is drawn in two\nparts; nothing needs the covered rows mounted. The grid does not write\ninto covered cells on its own; a consumer that merges keeps them empty or\nmarks them read-only through the column's `editable`, which is what the\nspreadsheet shell's Merge & Center does.\n\n## 1. Explicit merges (spreadsheet-style, DOM action)\n\nDeclare exact merges as `MergeSpec[]` and apply them with the\n`spreadsheetLayout` action, which works on a grid you do not own the\nrender of (it edits the table after each paint). Prefer `mergedCells`\nwhere you can. The origin cell `(rowIndex, columnId)` spans\n`colspan` columns right and `rowspan` rows down; covered cells are hidden.\n\n```svelte\n<script lang=\"ts\">\n import { spreadsheetLayout, type MergeSpec } from '@svgrid/grid'\n\n const merges: MergeSpec[] = [\n { rowIndex: 0, columnId: 'A', colspan: 6 }, // title bar\n { rowIndex: 14, columnId: 'A', colspan: 3 }, // \"Total\" label\n ]\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\nSee [demos/170-cell-merging.svelte](../../../examples/src/demos/170-cell-merging.svelte).\n\n## 2. Declarative `colSpan` / `rowSpan` (value-driven)\n\nFor data-driven spanning - \"merge each run of equal values\", \"this cell spans 2\ncolumns when X\" - put `colSpan` / `rowSpan` callbacks on the column and turn\nthem into merges with `spansToMerges`. This runs on the **same** merge engine\nas option 1 (no separate code path).\n\n```svelte\n<script lang=\"ts\">\n // `SpanColumn` rather than `ColumnDef`: `spansToMerges` needs `id` to be\n // present, and on a ColumnDef it is optional.\n import { spreadsheetLayout, spansToMerges, type SpanColumn } from '@svgrid/grid'\n\n const columns: SpanColumn<Row>[] = [\n { id: 'region', field: 'region',\n // merge each vertical run of equal regions\n rowSpan: ({ data, rowIndex }) => {\n if (rowIndex > 0 && rows[rowIndex - 1].region === data.region) return 1 // covered\n let n = 1\n while (rows[rowIndex + n]?.region === data.region) n += 1\n return n\n } },\n { id: 'country', field: 'country' },\n { id: 'amount', field: 'amount' },\n ]\n\n // Recompute after sort / filter - indexes are display-row indexes.\n const merges = $derived(spansToMerges(rows, columns))\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\n`colSpan` / `rowSpan` receive `CellSpanParams` (`{ data, rowIndex, columnId,\nvalue }`) and return the span count (1 = no span). `spansToMerges` handles\ncovered-cell bookkeeping so overlapping spans never double-emit.\n\n## Virtualization note\n\nThe declarative `rowSpan` and the `spreadsheetLayout` action use real\n`rowspan` and need the covered rows mounted in the render window. For very\nlarge spanning grids on those two, keep spans modest or disable row\nvirtualization (`virtualization={false}`) so the origin cell stays mounted\nwhile its covered rows are on screen. The `mergedCells` prop has no such\nlimit: it clamps every span to the rendered window and continues a merge\nfrom its first rendered row.\n\n## More examples\n\n### Budget report: merged headers\n\nA half-year budget report laid out with merged cells the way Excel lays one out: a title merged across the page, Q1 / Q2 / H1 group headers merged over their months, a Line corner merged down two rows, a notes paragraph merged into one wrapped block. A merge is one cell to the grid: click inside Q1 and the Name Box says B2, Merge & Center lights, the arrows step over it and its column letters are shaded. Unmerge and merge again from the ribbon; Ctrl+Z each step.\n\n<div data-docs-demo=\"463-merged-report-headers\" data-height=\"560\"></div>\n\n## See also\n\n- [Cell merging demo](../../../examples/src/demos/170-cell-merging.svelte)\n- [Row spanning](../rows/row-spanning.md)\n"
5335
+ "markdown": "# Column & row spanning (merged cells)\n\nSpanning lets a single body cell cover **multiple columns** and/or **rows** -\nmerged report headers, grouped labels, financial statements. SvGrid does this\nwith a real `colspan` / `rowspan` merge engine; there are three ways to drive\nit, and the first is the one to reach for on a new grid.\n\n<div data-docs-demo=\"170-cell-merging\" data-height=\"480\"></div>\n\n## 0. The `mergedCells` prop (the renderer's own)\n\nThe grid draws merges itself from a list of origins with their spans, in\ndisplay indices:\n\n```svelte\n<SvGrid\n {data} {columns}\n mergedCells={[\n { rowIndex: 0, colIndex: 0, rowSpan: 1, colSpan: 4 }, // a title across A1:D1\n { rowIndex: 3, colIndex: 1, rowSpan: 3, colSpan: 1 }, // B4:B6 as one cell\n ]}\n/>\n```\n\nThe origin's td takes the `rowspan` / `colspan` and shows the origin's\nvalue; the covered cells are not drawn at all, so there is nothing to\nhide after the fact. A selection grows to whole merges (a merged cell is\none cell), the active cell inside a merge is its origin, the arrow keys\nstep over a merge as one cell, and `api.getMergedCells()` reads the list\nback. Under row virtualization a merge whose origin has scrolled out of\nthe rendered window is drawn from its first rendered row with the rows\nthat remain, and one that crosses the frozen boundary is drawn in two\nparts; nothing needs the covered rows mounted. The grid does not write\ninto covered cells on its own; a consumer that merges keeps them empty or\nmarks them read-only through the column's `editable`, which is what the\nspreadsheet shell's Merge & Center does.\n\nThe merge code loads with the first `mergedCells`, not with every grid, so\ngrids that never merge do not carry it. Until it lands the cells draw\nunmerged: one frame in the browser, and server-rendered HTML shows them\nunmerged until the page hydrates.\n\n## 1. Explicit merges (spreadsheet-style, DOM action)\n\nDeclare exact merges as `MergeSpec[]` and apply them with the\n`spreadsheetLayout` action, which works on a grid you do not own the\nrender of (it edits the table after each paint). Prefer `mergedCells`\nwhere you can. The origin cell `(rowIndex, columnId)` spans\n`colspan` columns right and `rowspan` rows down; covered cells are hidden.\n\n```svelte\n<script lang=\"ts\">\n import { spreadsheetLayout, type MergeSpec } from '@svgrid/grid'\n\n const merges: MergeSpec[] = [\n { rowIndex: 0, columnId: 'A', colspan: 6 }, // title bar\n { rowIndex: 14, columnId: 'A', colspan: 3 }, // \"Total\" label\n ]\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\nSee [demos/170-cell-merging.svelte](../../../examples/src/demos/170-cell-merging.svelte).\n\n## 2. Declarative `colSpan` / `rowSpan` (value-driven)\n\nFor data-driven spanning - \"merge each run of equal values\", \"this cell spans 2\ncolumns when X\" - put `colSpan` / `rowSpan` callbacks on the column and turn\nthem into merges with `spansToMerges`. This runs on the **same** merge engine\nas option 1 (no separate code path).\n\n```svelte\n<script lang=\"ts\">\n // `SpanColumn` rather than `ColumnDef`: `spansToMerges` needs `id` to be\n // present, and on a ColumnDef it is optional.\n import { spreadsheetLayout, spansToMerges, type SpanColumn } from '@svgrid/grid'\n\n const columns: SpanColumn<Row>[] = [\n { id: 'region', field: 'region',\n // merge each vertical run of equal regions\n rowSpan: ({ data, rowIndex }) => {\n if (rowIndex > 0 && rows[rowIndex - 1].region === data.region) return 1 // covered\n let n = 1\n while (rows[rowIndex + n]?.region === data.region) n += 1\n return n\n } },\n { id: 'country', field: 'country' },\n { id: 'amount', field: 'amount' },\n ]\n\n // Recompute after sort / filter - indexes are display-row indexes.\n const merges = $derived(spansToMerges(rows, columns))\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\n`colSpan` / `rowSpan` receive `CellSpanParams` (`{ data, rowIndex, columnId,\nvalue }`) and return the span count (1 = no span). `spansToMerges` handles\ncovered-cell bookkeeping so overlapping spans never double-emit.\n\n## Virtualization note\n\nThe declarative `rowSpan` and the `spreadsheetLayout` action use real\n`rowspan` and need the covered rows mounted in the render window. For very\nlarge spanning grids on those two, keep spans modest or disable row\nvirtualization (`virtualization={false}`) so the origin cell stays mounted\nwhile its covered rows are on screen. The `mergedCells` prop has no such\nlimit: it clamps every span to the rendered window and continues a merge\nfrom its first rendered row.\n\n## More examples\n\n### Budget report: merged headers\n\nA half-year budget report laid out with merged cells the way Excel lays one out: a title merged across the page, Q1 / Q2 / H1 group headers merged over their months, a Line corner merged down two rows, a notes paragraph merged into one wrapped block. A merge is one cell to the grid: click inside Q1 and the Name Box says B2, Merge & Center lights, the arrows step over it and its column letters are shaded. Unmerge and merge again from the ribbon; Ctrl+Z each step.\n\n<div data-docs-demo=\"463-merged-report-headers\" data-height=\"560\"></div>\n\n## See also\n\n- [Cell merging demo](../../../examples/src/demos/170-cell-merging.svelte)\n- [Row spanning](../rows/row-spanning.md)\n"
5312
5336
  },
5313
5337
  {
5314
5338
  "slug": "help/columns/column-state",
@@ -5497,7 +5521,7 @@ export const docs = [
5497
5521
  "path": "docs/help/filtering/date-filter.md",
5498
5522
  "title": "Date filter",
5499
5523
  "section": "Filtering",
5500
- "markdown": "# Date filter\n\nA column with `editorType: 'date'` (or `'datetime'`) gets the **date**\nfilter operator set: `equals`, `lessThan`, `greaterThan`,\n**`between`**, `isBlank`.\n<div data-docs-demo=\"64-filter-between-operator\" data-height=\"540\"></div>\n\n```ts\nconst columns: GridColumns<Person> = [\n {\n field: 'joinedAt',\n header: 'Joined',\n editorType: 'date',\n format: { type: 'date', pattern: 'y-m-d' },\n },\n]\n```\n\n## Value format\n\nStore dates as **ISO date strings** (`YYYY-MM-DD`) or as `Date`\nobjects. The grid compares them via `Date.parse()` so both forms work,\nbut stick to one for sort stability.\n\nFor `'datetime'`, use full ISO 8601: `2026-05-27T14:32:00Z`.\n\n## Date range\n\nBoth surfaces use the same controls: a date picker for the single-value\noperators, and one range field for **Between** - two-month calendar, both ends\nin a single gesture. A range needs both ends before it filters anything.\n\nPick **Between** in the column menu's operator picker. The wrapper\nrenders two date inputs (From / To); both endpoints are **inclusive**.\n\n```ts\napi.setFilter('joinedAt', {\n operator: 'between',\n value: '2026-01-01',\n valueTo: '2026-12-31',\n})\n```\n\nThe headless filter helper works the same:\n\n```ts\nimport { applyExcelFilter } from '@svgrid/grid'\n\napplyExcelFilter('2026-05-27', {\n id: 'joinedAt',\n operator: 'between',\n value: '2026-01-01',\n valueTo: '2026-12-31',\n})\n// → true\n```\n\nThe filter is inactive until both endpoints are non-empty.\n\n## Today / yesterday / last 7 days\n\nNot built in. Apply via the imperative API:\n\n```ts\nfunction lastNDays(api: SvGridApi<{}, Person>, columnId: string, n: number) {\n const cutoff = new Date(Date.now() - n * 86_400_000).toISOString().slice(0, 10)\n api.setFilter(columnId, { operator: 'greaterThan', value: cutoff })\n}\n\nlastNDays(api, 'joinedAt', 7)\n```\n\n## Timezones\n\nThe grid does not adjust dates for the user's timezone. If you store\n`'2026-05-27'` and the user is in UTC-08, the cell displays as\n`2026-05-27` (no shift), and a `greaterThan: '2026-05-26'` filter matches.\nThat is usually what people want for **calendar** dates. For timezone-\nsensitive datetimes, store with `Z` suffix and use the `datetime` editor\ntype.\n\n## Date operators\n\nDeclare the column a date and the filter menu offers before / after / between\ninstead of the string comparisons. Without `cellDataType` an ISO string is just\ntext, and \"after 2020\" becomes a substring match.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n joined: string\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000, joined: '2021-03-01' },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000, joined: '2019-07-15' },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000, joined: '2020-01-20' },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000, joined: '2022-09-05' },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000, joined: '2018-11-11' },\n ]\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 190 },\n { field: 'joined', header: 'Joined', width: 160, cellDataType: 'dateString',\n format: { type: 'date', options: { dateStyle: 'medium' } } },\n ]\n</script>\n\n<SvGrid data={people} {columns} filterable filterMode=\"menu\" sortable />\n```\n\n\n## Filtering a date from code\n\n`setFilter` takes the same operators the menu uses, so a \"this year\" shortcut\nand the menu end up in one state rather than fighting.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n joined: string\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000, joined: '2021-03-01' },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000, joined: '2019-07-15' },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000, joined: '2020-01-20' },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000, joined: '2022-09-05' },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000, joined: '2018-11-11' },\n ]\n\n let api = $state<SvGridApi<{}, Person> | null>(null)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 190 },\n { field: 'joined', header: 'Joined', width: 160, cellDataType: 'dateString',\n format: { type: 'date', options: { dateStyle: 'medium' } } },\n ]\n</script>\n\n<div>\n <button type=\"button\" onclick={() => api?.setFilter('joined', { operator: 'greaterThan', value: '2020-12-31' })}>\n Joined after 2020\n </button>\n <button type=\"button\" onclick={() => api?.setFilter('joined', null)}>Clear</button>\n</div>\n\n<SvGrid data={people} {columns} filterable filterMode=\"menu\" onApiReady={(next) => (api = next)} />\n```\n\n## See also\n\n- [Filter conditions](./filter-conditions.md)\n- [Date editor](../editing/provided-editors.md#date-editor)\n"
5524
+ "markdown": "# Date filter\n\nA column with `editorType: 'date'` (or `'datetime'`) gets the **date**\nfilter operator set: `equals`, `lessThan`, `greaterThan`,\n**`between`**, `isBlank`. `@svgrid/enterprise` adds days-from-today\noperators (below).\n<div data-docs-demo=\"64-filter-between-operator\" data-height=\"540\"></div>\n\n```ts\nconst columns: GridColumns<Person> = [\n {\n field: 'joinedAt',\n header: 'Joined',\n editorType: 'date',\n format: { type: 'date', pattern: 'y-m-d' },\n },\n]\n```\n\n## Value format\n\nStore dates as **ISO date strings** (`YYYY-MM-DD`) or as `Date`\nobjects. The grid compares them via `Date.parse()` so both forms work,\nbut stick to one for sort stability.\n\nFor `'datetime'`, use full ISO 8601: `2026-05-27T14:32:00Z`.\n\n## Date range\n\nBoth surfaces use the same controls: a date picker for the single-value\noperators, and one range field for **Between** - two-month calendar, both ends\nin a single gesture. A range needs both ends before it filters anything.\n\nPick **Between** in the column menu's operator picker. The wrapper\nrenders two date inputs (From / To); both endpoints are **inclusive**.\n\n```ts\napi.setFilter('joinedAt', {\n operator: 'between',\n value: '2026-01-01',\n valueTo: '2026-12-31',\n})\n```\n\nThe headless filter helper works the same:\n\n```ts\nimport { applyExcelFilter } from '@svgrid/grid'\n\napplyExcelFilter('2026-05-27', {\n id: 'joinedAt',\n operator: 'between',\n value: '2026-01-01',\n valueTo: '2026-12-31',\n})\n// → true\n```\n\nThe filter is inactive until both endpoints are non-empty.\n\n## Today, overdue, next 7 days (Enterprise)\n\n`@svgrid/enterprise` adds five operators to every date column's filter menu\nonce `enableRelativeDateFilters()` has run (`installEnterprise` runs it too;\n[setup](../../enterprise/README.md#grid-filter-and-sort-additions)). They count whole days from today, in the user's\nlocal time, and take no value, so picking one in the menu filters at once:\n\n| Operator | Menu label | Keeps |\n| ------------- | ------------ | -------------------------------------------- |\n| `today` | Today | today |\n| `beforeToday` | Before today | every earlier day: overdue items |\n| `afterToday` | After today | every later day |\n| `next7Days` | Next 7 days | today through the same weekday next week |\n| `last7Days` | Last 7 days | the same weekday last week through today |\n\nBlank cells never match. A bare `'2026-05-27'` counts as that day in local\ntime, not UTC midnight. From code they are ordinary operators:\n\n```ts\napi.setFilter('due', { operator: 'beforeToday' })\n```\n\n\"Today\" is read when the filter is applied, so a page left open past midnight\nkeeps the old day until the filter changes.\n\n**Server-side data.** A server data source never receives these operators.\nThe grid sends the absolute filter they mean at request time: `beforeToday` as\n`lessThan` today's date, `next7Days` as `between` today and a week out, dates as\nlocal `YYYY-MM-DD`. Under `externalFilter`, `onFiltersChange` passes the\nrelative operator through, so a saved view still means \"overdue\" tomorrow;\n`resolveRelativeDateFilter(filter)` from `@svgrid/enterprise` turns it into\ndates when you build the query. Demo 701 shows the operators on a review\nqueue.\n\nThe grid side is the extension's `filterOperators` seam: a module can add an\noperator for any column type, with its own test and the filter a server gets in\nits place.\n\n## Timezones\n\nThe grid does not adjust dates for the user's timezone. If you store\n`'2026-05-27'` and the user is in UTC-08, the cell displays as\n`2026-05-27` (no shift), and a `greaterThan: '2026-05-26'` filter matches.\nThat is usually what people want for **calendar** dates. For timezone-\nsensitive datetimes, store with `Z` suffix and use the `datetime` editor\ntype.\n\n## Date operators\n\nDeclare the column a date and the filter menu offers before / after / between\ninstead of the string comparisons. Without `cellDataType` an ISO string is just\ntext, and \"after 2020\" becomes a substring match.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n joined: string\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000, joined: '2021-03-01' },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000, joined: '2019-07-15' },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000, joined: '2020-01-20' },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000, joined: '2022-09-05' },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000, joined: '2018-11-11' },\n ]\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 190 },\n { field: 'joined', header: 'Joined', width: 160, cellDataType: 'dateString',\n format: { type: 'date', options: { dateStyle: 'medium' } } },\n ]\n</script>\n\n<SvGrid data={people} {columns} filterable filterMode=\"menu\" sortable />\n```\n\n\n## Filtering a date from code\n\n`setFilter` takes the same operators the menu uses, so a \"this year\" shortcut\nand the menu end up in one state rather than fighting.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n joined: string\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000, joined: '2021-03-01' },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000, joined: '2019-07-15' },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000, joined: '2020-01-20' },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000, joined: '2022-09-05' },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000, joined: '2018-11-11' },\n ]\n\n let api = $state<SvGridApi<{}, Person> | null>(null)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 190 },\n { field: 'joined', header: 'Joined', width: 160, cellDataType: 'dateString',\n format: { type: 'date', options: { dateStyle: 'medium' } } },\n ]\n</script>\n\n<div>\n <button type=\"button\" onclick={() => api?.setFilter('joined', { operator: 'greaterThan', value: '2020-12-31' })}>\n Joined after 2020\n </button>\n <button type=\"button\" onclick={() => api?.setFilter('joined', null)}>Clear</button>\n</div>\n\n<SvGrid data={people} {columns} filterable filterMode=\"menu\" onApiReady={(next) => (api = next)} />\n```\n\n## More examples\n\n### Overdue filters, cell labels and a row count\n\nEnterprise filter and sort additions on a review queue. Due's filter menu offers Today, Before today, Next 7 days and the rest, with nothing to type; Status is stored as codes and its checklist reads Approved and Failed, as the cells do; the status bar counts rows, \"6 of 24 rows\" under a filter; and reviews with no due date stay last whichever way Due sorts.\n\n<div data-docs-demo=\"701-enterprise-grid-filters\" data-height=\"460\"></div>\n\n## See also\n\n- [Filter conditions](./filter-conditions.md)\n- [Date editor](../editing/provided-editors.md#date-editor)\n"
5501
5525
  },
5502
5526
  {
5503
5527
  "slug": "help/filtering/filter-api",
@@ -5539,7 +5563,7 @@ export const docs = [
5539
5563
  "path": "docs/help/filtering/set-filter.md",
5540
5564
  "title": "Set filter",
5541
5565
  "section": "Filtering",
5542
- "markdown": "# Set filter\n\nA \"set filter\" (a.k.a. value filter, list filter) shows a checklist of all distinct values in a column and lets the user pick which to include. It's what you reach for to filter `status` to \"active OR pending\", or `department` to a few specific teams.\n\n![An Excel-style set filter: a per-column checklist of distinct values with a Select all row, search, and a facet count, applying an IN filter to the grid.](/docs-media/grid-set-filter.svg)\n\n<div data-docs-demo=\"111-set-filter-advanced\" data-height=\"640\"></div>\n\nThree patterns are supported, all wired through the imperative `api.setFacetFilter(columnId, values | null)`:\n\n| Mode | UI | Built-in? | When to use |\n| --- | --- | --- | --- |\n| **Excel-style** | Column-menu Values tab | Yes | Most columns. Distinct values are enumerated from the loaded data; search box + select-all + clear ship out of the box. |\n| **Async** | Side panel that loads values from a server endpoint | User-land (one screen of code) | The column has too many distinct values to list at full data load. Lazy-fetch on demand. |\n| **Tree-list** | Hierarchical checkboxes (parent ↔ descendants) | User-land (cascade logic) | Nested taxonomies: Region → Country → City; Department → Team → Employee. |\n\n## 1. Excel-style (built-in)\n\nThe column menu's Values tab is the default set filter. Click the funnel icon on any header to open it.\n\nWhat you get without writing any code:\n\n- Distinct values from the current dataset.\n- Type-ahead search.\n- Select-all / clear toggle.\n- Mixed-state preserved as the user scrolls.\n\nProgrammatic equivalent for \"remember and restore\":\n\n```ts\n// Capture the current set\nconst filters = api.getFilters() // includes selectedValues per column\n\n// Restore later (e.g. saved view, URL persistence)\napi.setFacetFilter('status', ['active', 'pending'])\napi.setFacetFilter('status', null) // clear\n```\n\n## 2. Async values (server-loaded)\n\nWhen a column has tens of thousands of distinct values, you don't want to pre-render them all. Pattern: render a side panel beside the grid, load values from the server on first open, drive the grid via `api.setFacetFilter`:\n\n```ts\nlet state = $state<{\n status: 'idle' | 'loading' | 'ready' | 'error'\n values: string[]\n}>({ status: 'idle', values: [] })\nlet selected = $state<Set<string>>(new Set())\n\nasync function loadValues() {\n state = { status: 'loading', values: [] }\n const res = await fetch('/api/orders/customers')\n const values = await res.json()\n state = { status: 'ready', values }\n}\n\nfunction toggle(value: string) {\n const next = new Set(selected)\n if (next.has(value)) next.delete(value); else next.add(value)\n selected = next\n api.setFacetFilter('customer', next.size === 0 ? null : Array.from(next))\n}\n```\n\nKey benefits vs the Excel tab:\n\n- **Lazy load** - no client-side enumeration for millions of distinct values.\n- **Server can apply policy** - hide values the current user shouldn't see.\n- **Static label / dynamic value** - the panel can show pretty labels while the filter applies on the underlying id.\n\nSee demo 111 (\"Async values\" card) for a complete implementation with loading state, retry, and search.\n\n## 3. Tree-list (hierarchical)\n\nFor nested taxonomies, render a tree of checkboxes. Parent checked = all descendants checked. Some descendants checked = parent shows the \"indeterminate\" state. On any change, compute the leaf set and apply it to the column.\n\n```ts\n// Taxonomy: Region → Country → City\nconst GEO = {\n Americas: { 'United States': ['New York', 'San Francisco'], Canada: ['Toronto'] },\n EMEA: { Germany: ['Berlin', 'Munich'], France: ['Paris'] },\n}\n\nlet selectedCities = $state<Set<string>>(new Set())\n\nfunction toggleNode(node: TreeNode, on: boolean) {\n const next = new Set(selectedCities)\n for (const city of node.cities) { // pre-computed leaf set\n if (on) next.add(city); else next.delete(city)\n }\n selectedCities = next\n api.setFacetFilter('city', next.size === 0 ? null : Array.from(next))\n}\n\nfunction isChecked(node: TreeNode): boolean {\n return node.cities.every((c) => selectedCities.has(c))\n}\nfunction isPartial(node: TreeNode): boolean {\n const hits = node.cities.filter((c) => selectedCities.has(c)).length\n return hits > 0 && hits < node.cities.length\n}\n```\n\nThe grid is unaware of the hierarchy - it just receives a flat list of allowed leaf values. The hierarchy lives in your panel UI.\n\nSee demo 111 (\"Tree\" card) and [demo 102: Tree checkbox cascade](#/demos/102-tree-checkbox-cascade) for the cascade-logic recipe.\n\n## API surface\n\n```ts {nocheck}\ntype SvGridApi<…> = {\n // Set a multi-select set filter. Pass null or [] to clear.\n setFacetFilter(columnId: string, values: ReadonlyArray<string> | null): void\n\n // Read the current filters (includes the facet selection per column).\n getFilters(): Record<string, { operator: ..., selectedValues?: string[] }>\n\n // Snapshot of the rows the grid currently displays - useful when your\n // filter UI needs to count matches without re-running the search.\n getDisplayedRows(): ReadonlyArray<TData>\n}\n```\n\n## Filtering to a set of values\n\nA set filter is a checklist of the distinct values in the column, which is\nthe right shape when the domain is small and closed - a department, a status, a\ncountry. Typing an operator for those is slower than ticking a box.\n\nThree things the checklist does on its own:\n\n- **It counts.** Each row shows how many rows that value would keep, so you can\n see the shape of the column before touching it.\n- **It offers only what is reachable.** The values are taken from the rows that\n pass every *other* column's filters, not from the whole dataset - narrow\n Country to Germany and the City list stops offering cities that would leave\n you with an empty grid. The column's own filter is excluded, so unticking one\n value never makes the rest of the list move.\n- **Search then \"select all\" means the results.** With a query typed the row\n reads *(Select all results)* and applies to the matches only, leaving the\n rest of your selection alone.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, renderSnippet, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n active: boolean\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000, active: true },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000, active: true },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000, active: false },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000, active: true },\n ]\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 180 },\n { field: 'department', header: 'Department', width: 170 },\n { field: 'city', header: 'City', width: 150 },\n ]\n</script>\n\n<SvGrid data={people} {columns} filterable filterMode=\"menu\" />\n```\n\n\n## Building the value list yourself\n\nWhen the choices should come from your domain rather than from whatever\nhappens to be loaded, derive them and filter the array. A set the user can see\nbut not currently reach is often the point - it tells them the value exists.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, renderSnippet, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n active: boolean\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000, active: true },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000, active: true },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000, active: false },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000, active: true },\n ]\n\n const DEPARTMENTS = ['Engineering', 'Platform', 'Networking', 'Design'] as const\n\n let picked = $state<string[]>([])\n\n const shown = $derived(\n picked.length === 0 ? people : people.filter((p) => picked.includes(p.department)),\n )\n\n function toggle(d: string) {\n picked = picked.includes(d) ? picked.filter((x) => x !== d) : [...picked, d]\n }\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 180 },\n { field: 'department', header: 'Department', width: 170 },\n ]\n</script>\n\n<div>\n {#each DEPARTMENTS as d}\n <label><input type=\"checkbox\" checked={picked.includes(d)} onchange={() => toggle(d)} /> {d}</label>\n {/each}\n</div>\n\n<SvGrid data={shown} {columns} />\n```\n\n## See also\n\n- Demo 111: [Set filter - tree / async / Excel mode](#/demos/111-set-filter-advanced)\n- Demo 102: [Tree checkbox cascade](#/demos/102-tree-checkbox-cascade) - the cascade recipe used inside the tree filter\n- [`api.setFacetFilter`](https://svgrid.com/api/#setfacetfilter)\n- [Filter API overview](./filter-api.md)\n"
5566
+ "markdown": "# Set filter\n\nA \"set filter\" (a.k.a. value filter, list filter) shows a checklist of all distinct values in a column and lets the user pick which to include. It's what you reach for to filter `status` to \"active OR pending\", or `department` to a few specific teams.\n\n![An Excel-style set filter: a per-column checklist of distinct values with a Select all row, search, and a facet count, applying an IN filter to the grid.](/docs-media/grid-set-filter.svg)\n\n<div data-docs-demo=\"111-set-filter-advanced\" data-height=\"640\"></div>\n\nThree patterns are supported, all wired through the imperative `api.setFacetFilter(columnId, values | null)`:\n\n| Mode | UI | Built-in? | When to use |\n| --- | --- | --- | --- |\n| **Excel-style** | Column-menu Values tab | Yes | Most columns. Distinct values are enumerated from the loaded data; search box + select-all + clear ship out of the box. |\n| **Async** | Side panel that loads values from a server endpoint | User-land (one screen of code) | The column has too many distinct values to list at full data load. Lazy-fetch on demand. |\n| **Tree-list** | Hierarchical checkboxes (parent ↔ descendants) | User-land (cascade logic) | Nested taxonomies: Region → Country → City; Department → Team → Employee. |\n\n## 1. Excel-style (built-in)\n\nThe column menu's Values tab is the default set filter. Click the funnel icon on any header to open it.\n\nWhat you get without writing any code:\n\n- Distinct values from the current dataset, labelled the way the cells show\n them.\n- Type-ahead search.\n- Select-all / clear toggle.\n- Mixed-state preserved as the user scrolls.\n\n### Labels from the cells (Enterprise)\n\nThe free grid lists the stored values. With `@svgrid/enterprise`,\n`enableFilterLabels()` ([setup](../../enterprise/README.md#grid-filter-and-sort-additions)) lists each value under the text its cell shows, and the\nfilter still matches the stored value. The label comes from the first of these\nthe column has:\n\n1. a `cell` renderer that returns a string,\n2. static `editorOptions` (`{ value, label }`),\n3. `formatter` or `format`.\n\nSo a status stored as `MARKED_AS_FAILED` and drawn as \"Failed\" is offered as\n\"Failed\", and the column's accessor can stay the raw value that sorting needs:\n\n```ts\n// after enableFilterLabels() from @svgrid/enterprise has run once\nconst STATUS_TEXT: Record<string, string> = { APPROVED: 'Approved', MARKED_AS_FAILED: 'Failed' }\nconst columns = [\n { field: 'status', header: 'Status', cell: ({ getValue }) => STATUS_TEXT[String(getValue())] },\n { field: 'reviews', header: 'Reviews', cellDataType: 'number' },\n]\n```\n\nText values are ordered by label. Number and date values stay in value order,\nsince \"$1,000\" would collate before \"$200\". A `cell` that renders markup has\nno text to borrow, so its column falls through to the next source. The search\nbox above the list matches the stored values. Demo 701 shows it.\n\nThe grid side is the extension's `facetOptions` hook, which runs in the menu\nchunk, so a grid without the module carries none of it.\n\nProgrammatic equivalent for \"remember and restore\":\n\n```ts\n// Capture the current set\nconst filters = api.getFilters() // includes selectedValues per column\n\n// Restore later (e.g. saved view, URL persistence)\napi.setFacetFilter('status', ['active', 'pending'])\napi.setFacetFilter('status', null) // clear\n```\n\n## 2. Async values (server-loaded)\n\nWhen a column has tens of thousands of distinct values, you don't want to pre-render them all. Pattern: render a side panel beside the grid, load values from the server on first open, drive the grid via `api.setFacetFilter`:\n\n```ts\nlet state = $state<{\n status: 'idle' | 'loading' | 'ready' | 'error'\n values: string[]\n}>({ status: 'idle', values: [] })\nlet selected = $state<Set<string>>(new Set())\n\nasync function loadValues() {\n state = { status: 'loading', values: [] }\n const res = await fetch('/api/orders/customers')\n const values = await res.json()\n state = { status: 'ready', values }\n}\n\nfunction toggle(value: string) {\n const next = new Set(selected)\n if (next.has(value)) next.delete(value); else next.add(value)\n selected = next\n api.setFacetFilter('customer', next.size === 0 ? null : Array.from(next))\n}\n```\n\nKey benefits vs the Excel tab:\n\n- **Lazy load** - no client-side enumeration for millions of distinct values.\n- **Server can apply policy** - hide values the current user shouldn't see.\n- **Static label / dynamic value** - the panel can show pretty labels while the filter applies on the underlying id.\n\nSee demo 111 (\"Async values\" card) for a complete implementation with loading state, retry, and search.\n\n## 3. Tree-list (hierarchical)\n\nFor nested taxonomies, render a tree of checkboxes. Parent checked = all descendants checked. Some descendants checked = parent shows the \"indeterminate\" state. On any change, compute the leaf set and apply it to the column.\n\n```ts\n// Taxonomy: Region → Country → City\nconst GEO = {\n Americas: { 'United States': ['New York', 'San Francisco'], Canada: ['Toronto'] },\n EMEA: { Germany: ['Berlin', 'Munich'], France: ['Paris'] },\n}\n\nlet selectedCities = $state<Set<string>>(new Set())\n\nfunction toggleNode(node: TreeNode, on: boolean) {\n const next = new Set(selectedCities)\n for (const city of node.cities) { // pre-computed leaf set\n if (on) next.add(city); else next.delete(city)\n }\n selectedCities = next\n api.setFacetFilter('city', next.size === 0 ? null : Array.from(next))\n}\n\nfunction isChecked(node: TreeNode): boolean {\n return node.cities.every((c) => selectedCities.has(c))\n}\nfunction isPartial(node: TreeNode): boolean {\n const hits = node.cities.filter((c) => selectedCities.has(c)).length\n return hits > 0 && hits < node.cities.length\n}\n```\n\nThe grid is unaware of the hierarchy - it just receives a flat list of allowed leaf values. The hierarchy lives in your panel UI.\n\nSee demo 111 (\"Tree\" card) and [demo 102: Tree checkbox cascade](#/demos/102-tree-checkbox-cascade) for the cascade-logic recipe.\n\n## API surface\n\n```ts {nocheck}\ntype SvGridApi<…> = {\n // Set a multi-select set filter. Pass null or [] to clear.\n setFacetFilter(columnId: string, values: ReadonlyArray<string> | null): void\n\n // Read the current filters (includes the facet selection per column).\n getFilters(): Record<string, { operator: ..., selectedValues?: string[] }>\n\n // Snapshot of the rows the grid currently displays - useful when your\n // filter UI needs to count matches without re-running the search.\n getDisplayedRows(): ReadonlyArray<TData>\n}\n```\n\n## Filtering to a set of values\n\nA set filter is a checklist of the distinct values in the column, which is\nthe right shape when the domain is small and closed - a department, a status, a\ncountry. Typing an operator for those is slower than ticking a box.\n\nThree things the checklist does on its own:\n\n- **It counts.** Each row shows how many rows that value would keep, so you can\n see the shape of the column before touching it.\n- **It offers only what is reachable.** The values are taken from the rows that\n pass every *other* column's filters, not from the whole dataset - narrow\n Country to Germany and the City list stops offering cities that would leave\n you with an empty grid. The column's own filter is excluded, so unticking one\n value never makes the rest of the list move.\n- **Search then \"select all\" means the results.** With a query typed the row\n reads *(Select all results)* and applies to the matches only, leaving the\n rest of your selection alone.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, renderSnippet, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n active: boolean\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000, active: true },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000, active: true },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000, active: false },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000, active: true },\n ]\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 180 },\n { field: 'department', header: 'Department', width: 170 },\n { field: 'city', header: 'City', width: 150 },\n ]\n</script>\n\n<SvGrid data={people} {columns} filterable filterMode=\"menu\" />\n```\n\n\n## Building the value list yourself\n\nWhen the choices should come from your domain rather than from whatever\nhappens to be loaded, derive them and filter the array. A set the user can see\nbut not currently reach is often the point - it tells them the value exists.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, renderSnippet, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n active: boolean\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000, active: true },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000, active: true },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000, active: false },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000, active: true },\n ]\n\n const DEPARTMENTS = ['Engineering', 'Platform', 'Networking', 'Design'] as const\n\n let picked = $state<string[]>([])\n\n const shown = $derived(\n picked.length === 0 ? people : people.filter((p) => picked.includes(p.department)),\n )\n\n function toggle(d: string) {\n picked = picked.includes(d) ? picked.filter((x) => x !== d) : [...picked, d]\n }\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 180 },\n { field: 'department', header: 'Department', width: 170 },\n ]\n</script>\n\n<div>\n {#each DEPARTMENTS as d}\n <label><input type=\"checkbox\" checked={picked.includes(d)} onchange={() => toggle(d)} /> {d}</label>\n {/each}\n</div>\n\n<SvGrid data={shown} {columns} />\n```\n\n## See also\n\n- Demo 111: [Set filter - tree / async / Excel mode](#/demos/111-set-filter-advanced)\n- Demo 102: [Tree checkbox cascade](#/demos/102-tree-checkbox-cascade) - the cascade recipe used inside the tree filter\n- [`api.setFacetFilter`](https://svgrid.com/api/#setfacetfilter)\n- [Filter API overview](./filter-api.md)\n"
5543
5567
  },
5544
5568
  {
5545
5569
  "slug": "help/filtering/text-filter",
@@ -5877,6 +5901,13 @@ export const docs = [
5877
5901
  "section": "Help",
5878
5902
  "markdown": "# Recipes / Cookbook\n\nQuick patterns for the questions that come up over and over. Each\nrecipe is paired with a live demo or a minimal snippet that runs\nagainst the shipping library.\n\n## Sort, filter, paginate at the same time\n\nThree of the most-asked features wired together against a 5k-row\ndataset. Click any header to sort, open the filter icon to filter,\nuse the pager at the bottom to walk pages:\n\n<div data-docs-demo=\"02-sort-filter-paginate\" data-height=\"440\"></div>\n\nThe implementation: register all three features in one\n`tableFeatures(...)` call and enable the matching props on `<SvGrid>`.\nSee [Filtering overview](./filtering/overview.md) and\n[Row sorting](./rows/row-sorting.md).\n\n## Select rows + copy / paste a range\n\nClick + drag selects a rectangular cell range; Ctrl/Cmd+C copies as\nTSV; pasting back from Excel writes through the same cell-write\npipeline as inline edit:\n\n<div data-docs-demo=\"04-selection-copy-paste\" data-height=\"440\"></div>\n\nThe pattern: enable `enableCellSelection={true}` and let the grid\nhandle the keyboard + paste plumbing. Cell writes go through\n`onCellValueChange` so your validator runs on every pasted value.\n\n## Bulk actions toolbar\n\nThe Gmail / Linear pattern: tick row checkboxes, a sticky toolbar\nreveals \"Mark / Delete / Copy as TSV\":\n\n<div data-docs-demo=\"23-bulk-actions\" data-height=\"440\"></div>\n\nThe trick: subscribe to `onRowSelectionChange` and render your\ntoolbar whenever the count is > 0. The grid doesn't ship a bulk-action\ncomponent on purpose - your design system's button + toast UI is\nbetter than anything we could embed.\n\n## Cascade editing (formula-like dependencies)\n\nEditing qty / price cascades into line totals + a summary card:\n\n<div data-docs-demo=\"18-cascade-editing\" data-height=\"440\"></div>\n\nIn `onCellValueChange`, after writing the cell, recompute the dependent\ncells in the same row (or in the summary state) and let Svelte 5's\nreactivity carry the update through. The pattern is essentially\n\"editable cells + a `$derived` summary\".\n\n## Validation while editing\n\nPer-column rules: invalid commits get rolled back via `setCellValue`,\nand a sidebar logs the rejection so users can audit what was tried:\n\n<div data-docs-demo=\"24-validation\" data-height=\"440\"></div>\n\nUse `onCellValueChange`: validate, and if invalid, call\n`api.setCellValue(rowIndex, columnId, oldValue)` to undo. The grid\nemits a fresh `onCellValueChange` for the undo write that your\nvalidator can recognise and skip.\n\n## Column pinning + freezing\n\nWide 13-column grid: pin Company on the left and Price on the right;\nthe middle scrolls under sticky edges:\n\n<div data-docs-demo=\"25-column-pinning\" data-height=\"440\"></div>\n\nThe user pins via the column menu - no extra wiring needed if\n`columnFilteringFeature` is registered (the menu lives on the same\nheader button). Or set the whole pinning state programmatically with\n`api.setColumnPinning({ left: ['name'], right: ['total'] })` - pass an\nempty array for a side to unpin it. `api.getColumnPinning()` reads it\nback for persistence.\n\n## List + chips editors\n\nThe two built-in multi-select editors:\n\n<div data-docs-demo=\"26-list-chips-editors\" data-height=\"440\"></div>\n\nAdd `editorType: 'list'` for a single `<select>` or `editorType: 'chips'`\nwith `editorMultiple={true}` for removable tokens. Pass static\n`editorOptions` or a `(row) => options` callback for cascading lists\n(e.g. City options depend on Country).\n\n## Spreadsheet ribbon\n\nAn Excel-style Ribbon UI driving the grid via `SvGridApi`: bold + colour\n+ number format + insert/delete row + sort, plus a live SUM/AVG/COUNT\nstatus bar:\n\n<div data-docs-demo=\"27-spreadsheet-ribbon\" data-height=\"500\"></div>\n\nThe ribbon is a regular Svelte component; every button calls\n`api.setCellValue`, `api.addRow`, `api.setSort`, etc. Status bar\nreads `getDisplayedRows()` for the live aggregate.\n\n## Master / detail\n\nA hierarchical row that expands to reveal a child grid:\n\n<div data-docs-demo=\"08-tree-and-master-detail\" data-height=\"440\"></div>\n\nSame flatten pattern as [tree rows](./rows/tree-rows.md): a flat\n`visibleRows` derivation, plus a custom cell snippet that renders the\ndetail grid inline when the row is expanded.\n\n## Forms-in-grid (master grid + side form)\n\nClick a row to load it into a tabbed detail form on the right; edits\nflow back to the grid live:\n\n<div data-docs-demo=\"40-forms-master-detail\" data-height=\"500\"></div>\n\nPattern: `onActiveCellChange` -> set `activeRowId` -> `draft = $state.snapshot(activeRow)` -> form\nbinds against `draft`. On save, write `draft` back into the rows array.\n**Use `$state.snapshot()`, not `structuredClone()`**, on Svelte 5 state\nproxies - the latter throws `DataCloneError`.\n\n## Saved views / persistence\n\nPivot-lite with chips + saved views stored in localStorage:\n\n<div data-docs-demo=\"36-reporting-workspace\" data-height=\"500\"></div>\n\nThe pattern: a `view: { groupBy, sortBy, filters, columns }` object\nthat you serialise into localStorage under a versioned key\n(`'my-app:view:v1'`). On load, hydrate the state from the saved view\nand call the matching `api.set*` methods.\n\n## Theming studio\n\nLive token playground: brand color, density, radius, font, dark/light,\nzebra. The CSS snippet at the bottom is copy-ready:\n\n<div data-docs-demo=\"37-theming-studio\" data-height=\"540\"></div>\n\nTheming is `--sg-*` custom properties - see [Tailwind integration](./tailwind.md)\nfor the full token list.\n\n## Localisation + RTL switching\n\nSix locales (en, de, fr-CA, ja, ar, he); headers, currencies, dates,\nand the grid's own scrollbar flip:\n\n<div data-docs-demo=\"38-rtl-i18n\" data-height=\"500\"></div>\n\nSet `<html dir=\"...\">` and `<html lang=\"...\">` based on the locale.\nPer-column `format: { type: 'currency', locales }` overrides the\ndocument locale for specific columns.\n\n## Print + boardroom export\n\nQuarterly P&L print pack: cover page, repeat-on-page headers, page-\nsize + orientation, CSV / HTML download, browser-native PDF:\n\n<div data-docs-demo=\"39-print-board-export\" data-height=\"500\"></div>\n\n`api.print({ title, columns, rows, orientation, pageSize })` opens a\nsandbox window with an isolated HTML document and calls `.print()` on\nit. The popup pattern is what isolates your print stylesheet from your\napp's CSS.\n\n## Healthcare EMR (role-based editing)\n\nInpatient board with vitals sparklines, risk score, code status, allergy\nchips, role-based editing (viewer / nurse / physician / admin):\n\n<div data-docs-demo=\"41-healthcare-emr\" data-height=\"500\"></div>\n\nThe role gate uses `editable: (ctx) => roleCanEdit(currentRole, ctx.column.id)`.\nThat lambda runs per-cell, so you get column + role granularity\nwithout a separate config table.\n\n## Live shipment / fleet board\n\nStreaming-style live update at 2-3 Hz with cell-level flash on change,\nETA delta colors, alert chips:\n\n<div data-docs-demo=\"42-logistics-fleet\" data-height=\"500\"></div>\n\nThe pattern: a `$state` rows array that you mutate from a\nWebSocket/SSE handler. The render component diffs at the data-array\nlevel, so reassigning the array (`rows = updated`) is what triggers\nthe visible repaint.\n\n## Compliance / approval queue\n\nL1 / L2 / L3 approval chain with live SLA timer, role-gated approve /\nreturn / reject buttons, immutable case-history audit panel:\n\n<div data-docs-demo=\"43-compliance-queue\" data-height=\"500\"></div>\n\nThis is the pattern for any \"this row needs a decision; some users can\nmake it, some can't\" workflow. Status changes go through a state\nmachine you own; the grid only renders the current state.\n\n## Field service dispatch\n\nDispatcher board: priority + status + tech editable inline, SLA tone\ngauge, today-timeline cell, tech capacity panel, live status stream:\n\n<div data-docs-demo=\"44-field-service\" data-height=\"500\"></div>\n\nSame `editable: (ctx) => ...` per-cell pattern for tech/status. The\ntoday-timeline cell is a positioned-bar in a single wide cell - see\nthe [pivot doc](./pivot.md) for that pattern.\n\n## Gantt chart in a grid\n\nProject plan with a wide custom Schedule cell: bars positioned by\nstart/end %, phase coloring, progress fill, today line, overdue glow:\n\n<div data-docs-demo=\"45-gantt-chart\" data-height=\"540\"></div>\n\nNo special Gantt mode - it's a single wide cell per row whose snippet\npositions absolute bars by `(start - projectStart) / projectSpan * 100`.\nAxis above the grid uses the same math.\n\nFor a real plan - a work-breakdown tree with rolled-up phases, dependency\narrows and a zoomable axis - use [Gantt chart mode](/help/rows/gantt), the\n`gantt` prop's Enterprise renderer, rather than building on this recipe.\n\n## Scheduler (single-day appointments)\n\nProviders as rows, an hour axis, click any appointment to edit it in\nthe side panel. Now-line ticks live:\n\n<div data-docs-demo=\"46-scheduler\" data-height=\"540\"></div>\n\nSame single-wide-cell pattern as the Gantt. The axis-wrap inside the\ngrid wrapper uses `ResizeObserver` so the axis width matches the\nschedule column - that's what keeps the now-line aligned between the\nheader and the cells.\n\n## Trash truck timeline (animated)\n\nPublic-works dispatcher: each truck glides along its day-long route\nwith spinning wheels, stops, and live fill levels:\n\n<div data-docs-demo=\"47-trash-truck-timeline\" data-height=\"540\"></div>\n\nThe mover uses `transition: left 220ms linear` so the new position\nanimates in. The bounce + wheel spin are CSS keyframes; no JS animation\nloop required.\n\n## CRM - sales pipeline\n\nDeal board with stage chips, weighted forecast bar, inline stage +\nprobability editing, deal detail aside with activity feed:\n\n<div data-docs-demo=\"48-crm-sales-pipeline\" data-height=\"540\"></div>\n\nThis is the canonical example of mixing inline edit + a side panel\nthat mirrors the active row.\n\n## Enterprise admin dashboard\n\nCRUD-heavy users board: inline role / status / MFA edit, bulk\nactivate / deactivate / delete, invite dialog, permissions matrix,\nlive audit log:\n\n<div data-docs-demo=\"49-admin-dashboard\" data-height=\"540\"></div>\n\nThe audit log is the recurring pattern: every mutation appends an\nentry to a `$state` array; the right-side panel renders the array.\nDelete + Invite use simple `<dialog>`-style modals.\n\n## E-commerce seller panel\n\nTabbed Amazon-seller view: catalog with SVG thumbnails, inventory bars\nvs reorder threshold, live orders pipeline, pricing rules:\n\n<div data-docs-demo=\"50-seller-panel\" data-height=\"540\"></div>\n\nThe tab strip is just chip buttons that swap which dataset / columns\nthe grid receives. One grid component, four tabs - share styling and\nbehavior without four separate mounts.\n\n## Long-form recipes\n\nThe recipes above pair a paragraph + a demo. These deeper write-ups\nhave their own pages:\n\n- [Persist column layout to URL](../recipes/persist-column-layout-to-url.md) - sort + filter + page in the URL, with debounced replaceState and restore-on-mount.\n- [Two-grid master / detail](../recipes/two-grid-master-detail.md) - one master grid drives a second detail grid; remount semantics and multi-select union.\n- [Bulk-edit selected rows](../recipes/bulk-edit-selected-rows.md) - the standard back-office workflow: pick a field, pick a value, apply to N selected rows. Includes optimistic + rollback patterns.\n- [Server-side filter with TanStack Query](../recipes/server-side-filter-with-tanstack-query.md) - caching, deduplication, cancellation, retries, optimistic edits via mutations.\n\n## See also\n\n- [Architecture overview](./architecture.md) - the layered model that\n makes these recipes composable.\n- [API reference](../reference/index.md) - every method called in the\n recipes above.\n"
5879
5903
  },
5904
+ {
5905
+ "slug": "help/review/change-review",
5906
+ "path": "docs/help/review/change-review.md",
5907
+ "title": "Change review - Enterprise",
5908
+ "section": "help/review",
5909
+ "markdown": "# Change review - Enterprise\n\nAn AI helper fills 900 empty cells, an agent cleans up a CRM export, an import\nupdates 2,000 rows. None of those writes was typed by the person who owns the\ndata, and none of them should land before someone has looked. Change review\nholds such writes as **proposals**, apart from the data, groups them by what\nthey do, and lets a person accept or reject a group at a time. Only accepted\nvalues are written, and each decision is one Ctrl+Z.\n\n```ts\nimport { createReview, reviewSmartFill, SvReviewPanel } from '@svgrid/enterprise/review'\n```\n\n<div data-docs-demo=\"702-change-review\" data-height=\"620\"></div>\n\nIn the demo, **Run cleanup agent** proposes fixes to a customer table. Nothing\nis written until you accept a group in the panel. Edit a cell that has a\nproposal before accepting it and the proposal is marked stale. **Import\ncrm-update.csv** proposes a different region for two customers the agent also\nfilled, and the panel asks which one to keep.\n\n## A grid with a review\n\n```svelte\n<script lang=\"ts\">\n import { SvGrid, type SvGridApi } from '@svgrid/grid'\n import { createReview, SvReviewPanel } from '@svgrid/enterprise/review'\n\n let rows = $state(customers)\n let api = $state<SvGridApi<any, Customer> | null>(null)\n\n const review = createReview<Customer>({\n api: () => api,\n setRows: (next) => (rows = next),\n onCommit: async (accepted) => {\n await fetch('/api/customers/bulk', { method: 'PATCH', body: JSON.stringify(accepted) })\n },\n })\n</script>\n\n<div class=\"layout\">\n <SvGrid\n data={rows}\n columns={review.columns(columns)}\n getRowId={(r) => r.id}\n conditionalFormats={review.formats}\n onApiReady={(a) => (api = a)}\n />\n <SvReviewPanel {review} />\n</div>\n```\n\nThree things are required:\n\n- **`getRowId` on the grid.** Proposals are keyed by row id, because row\n positions move on sort, filter and insert. `createReview` reads the function\n from the grid and throws a clear error when it is missing.\n- **The app owns the rows.** `setRows` replaces the array the grid is given,\n and it must apply synchronously. Reads go through `api.getData()`, which\n includes the grid's own writes (a paste, a fill, `addRows`), so building the\n next array from it carries those forward.\n- **The grid api**, passed as a getter, because `onApiReady` fires after mount.\n\n## Adding proposals\n\nAnything can add a set of proposals. Each one names the row, the field, the\nvalue it saw (`before`) and the value it proposes (`after`):\n\n```ts\nreview.add({\n source: { kind: 'agent', id: 'crm-cleanup', label: 'Cleanup agent' },\n proposals: [\n { rowId: 'c-104', field: 'company', before: 'Acme Inc.', after: 'Acme Inc' },\n { rowId: 'c-221', field: 'phone', before: '(555) 123-4567', after: '555-123-4567', reason: 'one phone format' },\n ],\n})\n```\n\n`confidence` (0 to 1) and `reason` are optional and show in the panel.\nProposals whose `after` equals `before` are skipped. A newer proposal from the\nsame source for the same cell replaces the older one. Two sources proposing\ndifferent values for one cell is a **conflict**: neither can be accepted by a\ngroup action until a person keeps one.\n\n### From the AI helpers\n\nThe AI helpers in `@svgrid/grid` return predictions keyed by data index.\n`reviewSmartFill` and `reviewClassify` snapshot the data before the call,\nresolve each index to its row id, drop indices the helper was not asked about,\nand add the result:\n\n```ts\nconst result = await reviewSmartFill(review, api, {\n field: 'region',\n examples: [{ input: { country: 'Germany' }, output: 'EMEA' }],\n})\nresult.dropped // predictions that pointed at rows outside the request\n```\n\n`fromSmartFill(result, snapshot, { api })` and `fromClassify` do the same for a\nresult you already have; pass the snapshot you took before calling the helper.\n\n### From an import or a sync\n\n`fromRows` diffs incoming rows against the grid's data by a key field and\nproposes one change per field that differs:\n\n```ts\nconst set = fromRows(imported.rows, {\n api,\n key: 'id',\n source: { kind: 'import', id: file.name, label: file.name },\n})\nreview.add(set)\nset.unmatched // incoming rows with no match; adding rows is not proposed yet\n```\n\n## How proposals are grouped\n\nThe panel never shows 2,000 cells in a list. `review.groups()` puts every\npending proposal in one group by the change it makes. The first four kinds are\n**rule groups**: every member is proven to follow the rule. The rest are\n**judgment groups**, where a person has to look.\n\n| Kind | Rule | Label in the panel |\n|---|---|---|\n| `whitespace` | `after` is `before` trimmed or with spaces collapsed | Trim spaces in Company |\n| `case` | same letters, different case | Change Email to lower case |\n| `format` | same characters apart from punctuation, the same unambiguous date, or text that parses to the number | Reformat Phone as 999-999-9999 |\n| `scale` | `after / before` is one number, 5 or more members | Divide Revenue by 100 |\n| `same-mapping` | several `before` values each mapped to one `after` at least twice | Country: 6 values → United States |\n| `fill-empty` | blank `before`, one group per proposed value | Fill empty Region with EMEA |\n| `constant-target` | many different `before` values, one `after` | Set Status to Closed |\n| `unpatterned` | everything else, per field | Notes: no shared pattern |\n\nA few cases are kept out of the rule groups on purpose. `\"3.5\"` to `\"35\"` keeps\nevery digit but changes the number, so it is not a format change. `03/05/2024`\ncould be March or May, so a reformat of it is never proven. A rule group proves\nthat every member follows its rule, not that the rule is right: an agent that\ndivides by 10 where it should divide by 100 shows up as its own \"Divide Revenue\nby 10\" group, labelled for what it does.\n\nThe panel lists the risky groups first: unpatterned, then one target from many\nvalues, then groups with low confidence, then the rest by size. Each group\ncarries a sample to check: every member below 60% confidence (up to ten), then\nmembers spread across the group. An unpatterned group lists every member.\n`same-mapping` and `constant-target` groups show which `before` values they\nmap, so \"everything became Canada\" is visible at a glance.\n\n## What the grid shows\n\n`review.formats` tints every cell with a pending proposal and draws a dot before\nits value, so the mark is never colour alone. Pass it as `conditionalFormats`,\nconcatenated with your own formats if you have them. Theme the tint with\n`--sg-review-pending-bg`. A cell two sources disagree on gets a red wash and a\n\"!\" instead (`--sg-review-conflict-bg`), so the grid shows where the panel's\nconflicts are.\n\n`review.columns(columns)` draws the proposal inside the cell: the proposed\nvalue, then the current value struck through. It does this by wrapping the\ncolumn's `cell`, and only for columns where that leaves the rest of the column\nas it was: columns with a `cell` of their own, and plain text columns.\nCheckbox, list, chips and boolean columns, and field types with a cell of their\nown, keep their cell as it is and show the proposed value after it (\"→ Closed\").\n\n## Deciding\n\n```ts\nconst outcome = await review.acceptGroup(group.key, group.ids)\n// { accepted: [...], rejected: [], stale: [...], skipped: [...], error? }\n```\n\nOn accept, for each proposal:\n\n1. An open cell editor is committed first, so a value someone just typed wins.\n Under `fullRowEditing`, the row being edited is left pending instead.\n2. If the cell no longer holds `before`, the proposal becomes **stale** and is\n not written.\n3. `onCommit` receives the remaining proposals. Throw or reject to keep them\n pending; nothing is written.\n4. The cells are checked again, because a person could edit one while\n `onCommit` was saving.\n5. One `setRows` call writes every accepted value.\n6. One undo step is recorded. Ctrl+Z in the grid writes the old values back,\n by row id, so it works with paging and filters on, and returns the proposals\n to pending. A cell edited after the accept is left as it is.\n\n`acceptGroup` and `rejectGroup` take the ids that were shown, so a proposal\nthat arrived after the panel rendered is never decided unseen.\n\n### Server row model\n\nWith the server row model there is no app array to replace. Pass the\ncontroller instead of `setRows`; `onCommit` is then required:\n\n```ts\nconst review = createReview({\n api: () => api,\n server: controller,\n onCommit: (accepted) => saveToServer(accepted),\n})\n```\n\nAccept saves through `onCommit` and refreshes the controller. Undo saves the\ninverse (`before` and `after` swapped) and refreshes again. The backend decides\nstaleness there.\n\n## SvReviewPanel\n\n| Prop | Type | Default | |\n|---|---|---|---|\n| `review` | `Review` | required | What `createReview` returned. |\n| `title` | `string` | `'Review changes'` | The panel heading. |\n| `confirmOver` | `number` | `50` | Ask before deciding more than this many at once. |\n| `onDecide` | `(outcome) => void` | | Called after each decision. |\n\n**Accept rule groups** accepts every rule group at once (trims, case changes,\nreformats, one numeric factor), the changes that are proven by their rule, and\nleaves the groups that need a person. It is the panel's primary button, and\nrule groups are the only ones marked, with a \"Rule\" badge. **Accept all** is\nthe primary button only when every group left is a rule group: deciding\neverything unseen is what a review is there to prevent.\n\nA line in an open group names its row, then the change, then the reason and\nconfidence the source gave. The name is the row's first visible text column\n(the company, say), and a line leaves it out when that column is the one being\nchanged, since the old value already names the row. Set `rowLabel` on\n`createReview` to choose it yourself:\n\n```ts\nconst review = createReview<Customer>({\n api: () => api,\n setRows: (next) => (rows = next),\n rowLabel: (row) => `${row.company} (${row.city})`,\n})\n```\n\nA click on a line shows that row in the grid, and the row lights up for a\nmoment so the eye finds it. A value is quoted only where the quotes say\nsomething: around spaces at its ends (shown as dots), or when text reads as a\nnumber or a boolean.\n\nEach line of an open group has its own accept and reject, for a group that is\nmostly right: reject the two wrong guesses, then accept the group. A judgment\ngroup lists its sample first; **Show all** lists every change in it, up to\n200. A decision can move what is left of a group under another heading (two\n\"EMEA\" fills less one is a single fill, pooled with the others), and the open\ngroup follows its remaining changes rather than closing.\n\nIt is a plain panel, not a drawer, so the grid stays usable beside it. Inside\nthe group list, **J** and **K** move between groups, **Enter** opens one, **A**\naccepts it and **R** rejects it. \"Show in grid\" goes to the group's next row\nwithout moving the active cell: with client paging it turns to the row's page\nfirst (`api.getRowPosition`), then scrolls to it. Rows a filter hides are\ncounted, not shown. With grouping, where pages count groups, it stays on the\ncurrent page.\n\n**Only rows with changes** narrows the grid to the rows with a pending or\nconflicting proposal, on top of whatever the user filtered: it adds one\ncondition to the advanced filter with AND, and switching it off takes that\ncondition back out and leaves the rest. Rows leave the view as their\nproposals are decided, like an inbox. From code:\n`review.showPendingOnly(true)`, and `review.pendingOnly` tells whether it is\non. It needs the advanced filter engine, which it turns on itself.\n\n## Agents\n\n`createGridTools` gives an AI agent four tools over the grid's data. None of\nthem writes the data: the agent's edits arrive in the review like any other\nproposals, and a person decides.\n\n<div data-docs-demo=\"704-agent-review-desk\" data-height=\"700\"></div>\n\nIn the demo a scripted CRM agent calls these tools step by step; each step\nshows the tool call it made. The Log tab lists every decision as\n`onDecision` reports it.\n\n| Tool | What it does |\n|---|---|\n| `grid_describe` | The columns (field, header, type), the row count, and which fields the agent may edit. |\n| `grid_query_rows` | Rows matching `where` conditions (`equals`, `contains`, `blank`, `gt`, ...), with their `rowId`, paged and capped at `maxRows`. |\n| `grid_propose_edits` | Adds edits as proposals, with a reason and a confidence. Unknown rows, fields the agent may not edit, and edits that change nothing are skipped and reported. |\n| `grid_review_status` | How many of the agent's proposals are pending, accepted, rejected or stale, so it can learn from the review. |\n\n```ts\nimport { createGridTools, registerWebMcpTools } from '@svgrid/enterprise/review'\n\nconst tools = createGridTools({\n review,\n api: () => api,\n fields: ['region', 'phone'], // what the agent may propose edits to\n source: { kind: 'agent', id: 'crm-agent', label: 'CRM agent' },\n})\n```\n\nEach tool is `{ name, description, inputSchema, execute }`: hand them to the\ntool loop of your LLM SDK, or to an MCP server of your own.\n`registerWebMcpTools(tools)` registers them with the browser's WebMCP API\n(`document.modelContext`), so an agent driving the page can call them. WebMCP\nis a draft; where a browser does not have it, the call returns\n`{ supported: false }` and does nothing.\n\nA model's input is not trusted. One `grid_propose_edits` call carries at most\n`maxEdits` edits (500 by default) and a larger one is refused. A value that\ndoes not fit its column (text for a number, an object for a text cell, a list\nfor a single value) is skipped and reported back, not proposed.\n\n## Audit log and revert\n\n`onDecision` is called after every accept and reject, and after their undo and\nredo, with copies of the proposals it moved and who decided. Write these to\nyour own audit log:\n\n```ts\ncreateReview({\n api: () => api,\n setRows: (next) => (rows = next),\n user: currentUser.email,\n onDecision: (d) => audit.write({ action: d.action, by: d.by, at: d.at, changes: d.proposals }),\n})\n```\n\n`review.log()` lists the decided proposals in this session, in the order they\nwere decided.\n\nIf an undo or redo has to save through `onCommit` and the save fails, nothing\nis written and the decision stands. `onError(error, 'undo' | 'redo')` is\ncalled, `review.lastError` holds it, and the panel says \"Undo not saved\".\n\nCtrl+Z covers the last decisions. To take back a whole set later,\n`review.revertSet(setId)` adds a new set that proposes each accepted value's\nreverse. It is reviewed and accepted like any other, so a cell edited after the\noriginal accept is not overwritten.\n\n## Routing to an approver\n\n`review.toJSON({ setIds })` exports sets with their proposals as plain JSON.\nOn the approver's page, `review.merge(json)` adds them beside what that review\nalready holds. A cell that also has a pending proposal there from another\nsource becomes a conflict. `review.load(json)` replaces everything instead.\n\nAn export can come from another person, another session or an agent, so both\ncheck it first. Something that is not an export (`{ v: 1, sets: [...] }`)\nthrows and leaves the review as it was; a proposal with no id, row, field or a\nknown status is dropped. Both return `{ dropped }`.\n\nA person's own staged edits can take the same route. `fromStaged` turns a\n`createStagedEditing` buffer into proposals. Staged edits have already been\nwritten into the grid, so revert the stage first:\n\n```ts\nconst changes = stage.changes()\nstage.revert((rowIndex, columnId, value) => api.setCellValue(rowIndex, columnId, value))\nreview.add(fromStaged(changes, { api, source: { kind: 'user', id: me.id, label: `${me.name} (staged)` } }))\nconst forApprover = JSON.stringify(review.toJSON({ setIds: [review.sets().at(-1)!.id] }))\n```\n\n## At scale\n\nA test in the package runs 100,000 rows and 20,000 proposals through every\nstep and fails if one becomes slow. Measured in jsdom on a development\nmachine (2026-10-24):\n\n| Step | Time |\n| --- | --- |\n| Add 20,000 proposals | 88 ms |\n| Group them | 55 ms |\n| Build the tint rules | 8 ms |\n| Mark 1,000 cards | 24 ms |\n| Accept all 20,000 (one `setRows`) | 140 ms |\n| Undo, then redo | 71 ms, 96 ms |\n\nClustering, the stale checks and the writes are each a single pass over the\nproposals and the rows; nothing compares every proposal with every row.\n\n## With SvGrid Base\n\n`SvBase` hands any prop it does not use to its grid, so a review attaches the\nsame way. Add `onApply: baseReviewApplied(...)` so an accept does what an edit\ndoes in a base: \"Last modified time\" and \"Last modified by\" fields are stamped\nin the same write, and the record's activity credits the change to what\nproposed it and to the person who accepted it (\"CRM agent (accepted by Dana)\").\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, baseReviewApplied } from '@svgrid/enterprise/base'\n import { createReview, SvReviewPanel } from '@svgrid/enterprise/review'\n\n enableBase()\n let records = $state(initialRecords)\n let api = $state(null)\n const review = createReview({\n api: () => api,\n setRows: (next) => (records = next),\n onApply: baseReviewApplied(() => api),\n })\n</script>\n\n<SvBase\n data={records}\n columns={review.columns(columns)}\n conditionalFormats={review.formats}\n primaryField=\"name\"\n onApiReady={(a) => (api = a)}\n/>\n<SvReviewPanel {review} />\n```\n\nWhat a base shows:\n\n- **The proposed value in the cell** for field types that draw no cell of\n their own: single line text, long text, date, number, currency, percent,\n duration, formula, autonumber, lookup, rollup, count, created time and last\n modified time.\n- **The proposed value beside the cell** for types with a cell of their own:\n attachment, checkbox, single and multiple select, user, phone, email, URL,\n barcode, button, rating, link, created by and last modified by, and long\n text set to rich text or a percent drawn as a bar. The cell draws as it\n always does and \"→ Closed\" follows it, read through the field's own\n formatter, so a person shows by name.\n- **Cards and events too.** Kanban and gallery cards with pending proposals\n show \"2 proposed\", and calendar events a dot, with the fields and values on\n hover. A form adds new records, so it has nothing to mark.\n- **Sync.** With `createBaseSync`, an accepted value is a change like any\n other and is saved with the rest. Changes made elsewhere are still marked as\n before; a review is the step before that, where an agent proposes and a\n person decides.\n\nWith several tables (`tables`), keep one review per table: proposals are keyed\nby record id, and ids can repeat across tables. Give the active table's review\nto the grid and write into that table's rows:\n\n```ts\nconst review = createReview({\n api: () => api,\n setRows: (next) => (tables = tables.map((t) => (t.id === 'tasks' ? { ...t, data: next } : t))),\n onApply: baseReviewApplied(() => api),\n})\n```\n\n## Wording and languages\n\nEvery string the review shows comes from one message map with English\ndefaults: the panel, the group labels, the card and cell marks, and the notes\non proposals that were not written. Pass any subset to `createReview`, and\nunset keys stay English. `{name}` placeholders are filled in; `REVIEW_MESSAGES`\nlists every key with its English text.\n\n```ts\nconst review = createReview({\n api: () => api,\n setRows: (next) => (rows = next),\n messages: {\n acceptAll: 'Alle annehmen',\n changes: '{count} Änderungen',\n labelWhitespace: 'Leerzeichen in {field} kürzen',\n cardProposed: '{count} vorgeschlagen',\n },\n})\n```\n\n`<SvReviewPanel messages={...}>` overrides the review's wording for one panel.\n\n## Licensing\n\nChange review is part of SvGrid Enterprise. Without a license key it runs with\na watermark and a one-time notice. It adds nothing to `@svgrid/grid`: the tint\nis `conditionalFormats`, the proposed value is a wrapped `cell`, and the undo\nstep goes through the grid's public command context.\n\n## See also\n\n- [AI helpers](../ai.md)\n- [Undo and redo](../editing/undo-redo.md)\n- [Conditional formatting](../cells/conditional-formatting.md)\n- [Server-side row model](../server/server-row-model.md)\n"
5910
+ },
5880
5911
  {
5881
5912
  "slug": "help/rows/accessing-rows",
5882
5913
  "path": "docs/help/rows/accessing-rows.md",
@@ -5959,7 +5990,7 @@ export const docs = [
5959
5990
  "path": "docs/help/rows/row-sorting.md",
5960
5991
  "title": "Row sorting",
5961
5992
  "section": "Rows",
5962
- "markdown": "# Row sorting\n\nSorting is a feature you opt into. Try it live - click any column\nheader to cycle `none → asc → desc → none`; shift-click adds the\ncolumn to the sort key list (multi-sort):\n\n<div data-docs-demo=\"02-sort-filter-paginate\" data-height=\"440\"></div>\n\n\n\nThe examples on this page run against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n email: string\n department: string\n age: number\n salary: number\n city: string\n startDate: string\n active: boolean\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', email: 'ada@example.com', department: 'Engineering', age: 36, salary: 142000, city: 'London', startDate: '2021-03-01', active: true },\n { id: 2, name: 'Grace Hopper', email: 'grace@example.com', department: 'Engineering', age: 45, salary: 168000, city: 'New York', startDate: '2019-07-15', active: true },\n { id: 3, name: 'Linus Torvalds', email: 'linus@example.com', department: 'Platform', age: 54, salary: 155000, city: 'Portland', startDate: '2020-01-20', active: false },\n { id: 4, name: 'Radia Perlman', email: 'radia@example.com', department: 'Networking', age: 49, salary: 161000, city: 'Seattle', startDate: '2022-09-05', active: true },\n { id: 5, name: 'Barbara Liskov', email: 'barbara@example.com', department: 'Platform', age: 52, salary: 172000, city: 'Boston', startDate: '2018-11-11', active: true },\n ]\n\n const data = people\n</script>\n```\n\n```svelte\n<script lang=\"ts\">\n import {\n SvGrid, tableFeatures, rowSortingFeature, type ColumnDef,\n } from '@svgrid/grid'\n\n const features = tableFeatures({ rowSortingFeature })\n\n const columns: ColumnDef<typeof features, Person>[] = [\n { field: 'firstName', header: 'First name', editorType: 'text' },\n { field: 'age', header: 'Age', editorType: 'number' },\n { field: 'joinedAt', header: 'Joined', editorType: 'date' },\n ]\n</script>\n\n<SvGrid {data} {columns} features={features} />\n```\n\nClicking a sortable header toggles `none → asc → desc → none`. Shift-click\nadds the column to the sort key list (multi-sort).\n\n## Sort functions\n\n`sortFns` exposes the built-in comparators:\n\n```ts\nimport { sortFns } from '@svgrid/grid'\n// sortFns.auto - blanks, then numbers numerically, then text (default for unknown types)\n// sortFns.number - numeric; blanks and non-numeric values ('n/a') first\n// sortFns.date - Date-parsed; blanks and invalid dates first\n```\n\nAll three sort blanks (`null`, `undefined`, `''`) first ascending and last\ndescending, and never return `NaN`, so a column with placeholder text still\nsorts into a consistent order.\n\nThe grid picks the comparator based on the column's `editorType`:\n\n| editorType | comparator |\n| ---------- | ---------- |\n| `'number'` | `sortFns.number` |\n| `'date'` \\| `'datetime'` | `sortFns.date` |\n| anything else | `sortFns.auto` |\n\nIf your column has a non-trivial type, set `editorType` even if you do not\nwant inline editing - it is what tells sort and filter how to behave.\n\n### Sort by a rank\n\nA status column sorted as text puts \"Done\" before \"To do\". `sortValue` gives\nthe number to sort a value by instead, and grouped rows follow it too:\n\n```ts\nconst STATUS = ['To do', 'In progress', 'Done']\nconst columns = [\n { field: 'status', header: 'Status', sortValue: (v: unknown) => STATUS.indexOf(String(v)) },\n]\n```\n\nBlanks, and anything that is not a number, sort first ascending, as in a\nnumber column.\n\n## Programmatic sort\n\n```ts\napi.setSort('age', 'desc') // sort by age descending\napi.setSort('age', null) // clear sort on this column\napi.clearSort() // clear all sort\n```\n\n`setSort` replaces any existing sort with a single clause. For\nmulti-column sort, the user clicks the second column header with\n**Shift** held (the in-grid affordance). A multi-sort setter on the API\nis tracked in [Missing features](../missing-features.md).\n\nTo observe sort changes from outside the grid:\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onSortingChange={(next) => (sorting = next)}\n/>\n```\n\n## Disable sort per column\n\nNot yet first-class - there is no `enableSorting: false` field. To\nprevent a column from being sortable, omit `rowSortingFeature` from\n`tableFeatures(...)`, or render a custom header via `header: () =>\nrenderSnippet(...)` that doesn't bind to the sort button.\n\n## Sorting + server-side data\n\nWhen sort happens on the backend, pair `externalSort={true}` with\n`onSortingChange` and round-trip the sort clauses through your\nfetcher. See the [`09-server-side` demo](../../../examples/src/demos/09-server-side.svelte).\n\n## Multi-column sort\n\nShift-click a second header and the sort becomes ordered: department first,\nthen salary within it. The order you click is the order applied, which is why\nthe header shows a position number once more than one is active.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n salary: number\n bio: string\n }\n\n const seed: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', salary: 142000,\n bio: 'Wrote the first algorithm intended for a machine, and the first account of what a general-purpose computer could do beyond arithmetic.' },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', salary: 168000,\n bio: 'Built the first compiler and argued that programs should be written in something closer to English than to machine code.' },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', salary: 155000,\n bio: 'Wrote a kernel and, later, the version control system that most of the industry now runs on.' },\n ]\n\n const columns: GridColumns<Person> = [\n { field: 'department', header: 'Department', width: 170 },\n { field: 'name', header: 'Name', width: 180 },\n { field: 'salary', header: 'Salary', width: 140,\n format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n\n<SvGrid data={seed} {columns} sortable />\n```\n\n\n## Reading the sort model\n\n`onSortingChange` reports the model as an ordered array, which is exactly the\nshape you persist to a URL or hand to a server.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n salary: number\n bio: string\n }\n\n const seed: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', salary: 142000,\n bio: 'Wrote the first algorithm intended for a machine, and the first account of what a general-purpose computer could do beyond arithmetic.' },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', salary: 168000,\n bio: 'Built the first compiler and argued that programs should be written in something closer to English than to machine code.' },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', salary: 155000,\n bio: 'Wrote a kernel and, later, the version control system that most of the industry now runs on.' },\n ]\n\n let model = $state('[]')\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 190 },\n { field: 'city', header: 'City', width: 150 },\n { field: 'salary', header: 'Salary', width: 140,\n format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n\n<SvGrid\n data={seed}\n {columns}\n sortable\n onSortingChange={(s) => (model = JSON.stringify(s))}\n/>\n\n<p>Sort model: <code>{model}</code></p>\n```\n\n## See also\n\n- [Filter API](../filtering/filter-api.md)\n- [Server-side guide](../../getting-started.md#11-server-side-data)\n"
5993
+ "markdown": "# Row sorting\n\nSorting is a feature you opt into. Try it live - click any column\nheader to cycle `none → asc → desc → none`; shift-click adds the\ncolumn to the sort key list (multi-sort):\n\n<div data-docs-demo=\"02-sort-filter-paginate\" data-height=\"440\"></div>\n\n\n\nThe examples on this page run against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n email: string\n department: string\n age: number\n salary: number\n city: string\n startDate: string\n active: boolean\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', email: 'ada@example.com', department: 'Engineering', age: 36, salary: 142000, city: 'London', startDate: '2021-03-01', active: true },\n { id: 2, name: 'Grace Hopper', email: 'grace@example.com', department: 'Engineering', age: 45, salary: 168000, city: 'New York', startDate: '2019-07-15', active: true },\n { id: 3, name: 'Linus Torvalds', email: 'linus@example.com', department: 'Platform', age: 54, salary: 155000, city: 'Portland', startDate: '2020-01-20', active: false },\n { id: 4, name: 'Radia Perlman', email: 'radia@example.com', department: 'Networking', age: 49, salary: 161000, city: 'Seattle', startDate: '2022-09-05', active: true },\n { id: 5, name: 'Barbara Liskov', email: 'barbara@example.com', department: 'Platform', age: 52, salary: 172000, city: 'Boston', startDate: '2018-11-11', active: true },\n ]\n\n const data = people\n</script>\n```\n\n```svelte\n<script lang=\"ts\">\n import {\n SvGrid, tableFeatures, rowSortingFeature, type ColumnDef,\n } from '@svgrid/grid'\n\n const features = tableFeatures({ rowSortingFeature })\n\n const columns: ColumnDef<typeof features, Person>[] = [\n { field: 'firstName', header: 'First name', editorType: 'text' },\n { field: 'age', header: 'Age', editorType: 'number' },\n { field: 'joinedAt', header: 'Joined', editorType: 'date' },\n ]\n</script>\n\n<SvGrid {data} {columns} features={features} />\n```\n\nClicking a sortable header toggles `none → asc → desc → none`. Shift-click\nadds the column to the sort key list (multi-sort).\n\n## Sort functions\n\n`sortFns` exposes the built-in comparators:\n\n```ts\nimport { sortFns } from '@svgrid/grid'\n// sortFns.auto - blanks, then numbers numerically, then text (default for unknown types)\n// sortFns.number - numeric; blanks and non-numeric values ('n/a') first\n// sortFns.date - Date-parsed; blanks and invalid dates first\n```\n\nAll three sort blanks (`null`, `undefined`, `''`) first ascending and last\ndescending, and never return `NaN`, so a column with placeholder text still\nsorts into a consistent order.\n\nThe grid picks the comparator based on the column's `editorType`:\n\n| editorType | comparator |\n| ---------- | ---------- |\n| `'number'` | `sortFns.number` |\n| `'date'` \\| `'datetime'` | `sortFns.date` |\n| anything else | `sortFns.auto` |\n\nIf your column has a non-trivial type, set `editorType` even if you do not\nwant inline editing - it is what tells sort and filter how to behave.\n\n### Sort by a rank\n\nA status column sorted as text puts \"Done\" before \"To do\". `sortValue` gives\nthe number to sort a value by instead, and grouped rows follow it too:\n\n```ts\nconst STATUS = ['To do', 'In progress', 'Done']\nconst columns = [\n { field: 'status', header: 'Status', sortValue: (v: unknown) => STATUS.indexOf(String(v)) },\n]\n```\n\nBlanks, and anything that is not a number, sort first ascending, as in a\nnumber column.\n\n### Your own comparator\n\n`sortComparator` compares two of a column's values in place of the built-in\norder. It also gets the direction being sorted, `desc`. The grid reverses your\nresult for a descending sort, so return the ascending order; `desc` is there\nfor a value you want held at one end both ways. `sortValue` wins when a column\nsets both.\n\n```ts\nconst columns = [\n { field: 'code', header: 'Code', sortComparator: (a, b) => String(a).length - String(b).length },\n]\n```\n\n### Keep blanks at one end (Enterprise)\n\n`@svgrid/enterprise` ships comparators that hold blank cells at the bottom or\nthe top in both directions, so tasks with no due date stay below the dated\nones whichever way Due runs. The other values sort as the grid sorts them\n([setup](../../enterprise/README.md#grid-filter-and-sort-additions)):\n\n```ts\n// blanksLast is exported by @svgrid/enterprise\nconst columns = [\n { field: 'due', header: 'Due', cellDataType: 'dateString', sortComparator: blanksLast('date') },\n]\n```\n\n`blanksFirst` holds them at the top. Pass `'number'`, `'date'` or `'auto'`\n(the default) for how the other values compare.\n\n## Programmatic sort\n\n```ts\napi.setSort('age', 'desc') // sort by age descending\napi.setSort('age', null) // clear sort on this column\napi.clearSort() // clear all sort\n```\n\n`setSort` replaces any existing sort with a single clause. For\nmulti-column sort, the user clicks the second column header with\n**Shift** held (the in-grid affordance). A multi-sort setter on the API\nis tracked in [Missing features](../missing-features.md).\n\nTo observe sort changes from outside the grid:\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onSortingChange={(next) => (sorting = next)}\n/>\n```\n\n## Disable sort per column\n\nNot yet first-class - there is no `enableSorting: false` field. To\nprevent a column from being sortable, omit `rowSortingFeature` from\n`tableFeatures(...)`, or render a custom header via `header: () =>\nrenderSnippet(...)` that doesn't bind to the sort button.\n\n## Sorting + server-side data\n\nWhen sort happens on the backend, pair `externalSort={true}` with\n`onSortingChange` and round-trip the sort clauses through your\nfetcher. See the [`09-server-side` demo](../../../examples/src/demos/09-server-side.svelte).\n\n## Multi-column sort\n\nShift-click a second header and the sort becomes ordered: department first,\nthen salary within it. The order you click is the order applied, which is why\nthe header shows a position number once more than one is active.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n salary: number\n bio: string\n }\n\n const seed: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', salary: 142000,\n bio: 'Wrote the first algorithm intended for a machine, and the first account of what a general-purpose computer could do beyond arithmetic.' },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', salary: 168000,\n bio: 'Built the first compiler and argued that programs should be written in something closer to English than to machine code.' },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', salary: 155000,\n bio: 'Wrote a kernel and, later, the version control system that most of the industry now runs on.' },\n ]\n\n const columns: GridColumns<Person> = [\n { field: 'department', header: 'Department', width: 170 },\n { field: 'name', header: 'Name', width: 180 },\n { field: 'salary', header: 'Salary', width: 140,\n format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n\n<SvGrid data={seed} {columns} sortable />\n```\n\n\n## Reading the sort model\n\n`onSortingChange` reports the model as an ordered array, which is exactly the\nshape you persist to a URL or hand to a server.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n salary: number\n bio: string\n }\n\n const seed: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', salary: 142000,\n bio: 'Wrote the first algorithm intended for a machine, and the first account of what a general-purpose computer could do beyond arithmetic.' },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', salary: 168000,\n bio: 'Built the first compiler and argued that programs should be written in something closer to English than to machine code.' },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', salary: 155000,\n bio: 'Wrote a kernel and, later, the version control system that most of the industry now runs on.' },\n ]\n\n let model = $state('[]')\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 190 },\n { field: 'city', header: 'City', width: 150 },\n { field: 'salary', header: 'Salary', width: 140,\n format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n\n<SvGrid\n data={seed}\n {columns}\n sortable\n onSortingChange={(s) => (model = JSON.stringify(s))}\n/>\n\n<p>Sort model: <code>{model}</code></p>\n```\n\n## See also\n\n- [Filter API](../filtering/filter-api.md)\n- [Server-side guide](../../getting-started.md#11-server-side-data)\n"
5963
5994
  },
5964
5995
  {
5965
5996
  "slug": "help/rows/row-spanning",
@@ -6232,7 +6263,7 @@ export const docs = [
6232
6263
  "path": "docs/help/status-bar.md",
6233
6264
  "title": "Status bar",
6234
6265
  "section": "Help",
6235
- "markdown": "# Status bar\n\nThe status bar is the strip under the grid that shows live aggregates of the\n**selected cell range** - count, sum, average, min, max - the way Excel does at\nthe bottom-right when you select a block of numbers.\n\nThe examples on this page run against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n const data = people\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200 },\n { field: 'department', header: 'Department', width: 150 },\n { field: 'city', header: 'City', width: 140 },\n { field: 'age', header: 'Age', width: 90 },\n { field: 'salary', header: 'Salary', width: 130, format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```svelte\n<SvGrid {data} {columns} {features} enableCellSelection statusBar />\n```\n\nIt needs `enableCellSelection` (the bar aggregates the selected rectangle).\nDrag a range across numeric cells and the bar updates instantly.\n\n## Choosing aggregates\n\n`statusBar={true}` shows the default set (`count`, `sum`, `avg`, `min`, `max`).\nPass an object to pick which:\n\n```svelte\n<SvGrid enableCellSelection statusBar={{ aggregates: ['count', 'sum', 'avg'] }} />\n```\n\n| Aggregate | Meaning |\n| -------------- | ---------------------------------------------------- |\n| `count` | Cells in the selection (non-group). |\n| `numericCount` | How many of those hold a finite number. |\n| `sum` | Sum of the numeric cells. |\n| `avg` | Mean of the numeric cells. |\n| `min` / `max` | Smallest / largest numeric value. |\n\n## Behavior\n\n- The numeric aggregates (`sum`, `avg`, `min`, `max`) only appear when the\n selection actually contains numbers - selecting text cells shows just the\n count.\n- A single-cell selection shows nothing; the bar appears once a range of two\n or more cells is selected.\n- Edited values are respected: the aggregates read the displayed value, so an\n in-progress edit is reflected.\n- Group rows are skipped.\n\nSee the live [Status bar](https://svgrid.com/demos/144-status-bar/) demo.\n\n## Try it\n\nDrag a rectangle across the Age or Salary column and watch the bar total it.\n\n```svelte {runnable}\n<SvGrid {data} {columns} enableCellSelection statusBar />\n```\n"
6266
+ "markdown": "# Status bar\n\nThe status bar is the strip under the grid that shows live aggregates of the\n**selected cell range** - count, sum, average, min, max - the way Excel does at\nthe bottom-right when you select a block of numbers.\n\nThe examples on this page run against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n const data = people\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200 },\n { field: 'department', header: 'Department', width: 150 },\n { field: 'city', header: 'City', width: 140 },\n { field: 'age', header: 'Age', width: 90 },\n { field: 'salary', header: 'Salary', width: 130, format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```svelte\n<SvGrid {data} {columns} {features} enableCellSelection statusBar />\n```\n\nIt needs `enableCellSelection` (the bar aggregates the selected rectangle).\nDrag a range across numeric cells and the bar updates instantly.\n\n## Choosing aggregates\n\n`statusBar={true}` shows the default set (`count`, `sum`, `avg`, `min`, `max`).\nPass an object to pick which:\n\n```svelte\n<SvGrid enableCellSelection statusBar={{ aggregates: ['count', 'sum', 'avg'] }} />\n```\n\n| Aggregate | Meaning |\n| -------------- | ---------------------------------------------------- |\n| `count` | Cells in the selection (non-group). |\n| `numericCount` | How many of those hold a finite number. |\n| `sum` | Sum of the numeric cells. |\n| `avg` | Mean of the numeric cells. |\n| `min` / `max` | Smallest / largest numeric value. |\n\n## Row count (Enterprise)\n\nWith `@svgrid/enterprise`, `rows: true` adds a count on the left of the bar\nthat is always there, with or without a selection: \"250 rows\", or \"12 of 250\nrows\" while filters hide some. It needs no `enableCellSelection`. To show the\ncount alone, pass no aggregates. It is drawn once `enableRowCount()` has run\n([setup](../enterprise/README.md#grid-filter-and-sort-additions)):\n\n```svelte\n<SvGrid {data} {columns} statusBar={{ rows: true, aggregates: [] }} />\n```\n\nThe count leaves out group banners and ignores pagination. For a header or a\ncount of your own, `getRowCounts(api)` from `@svgrid/enterprise` returns\n`{ total, filtered }`; with grouping on, its `filtered` counts the group rows\ntoo. Under `externalFilter` or `externalPagination` the grid holds one page,\nso the bar shows the `rowCount` you pass.\n\nThe count is not announced to screen readers on each change; the grid already\nannounces filter results. Without the module, `rows: true` shows nothing.\n\n## Behavior\n\n- The numeric aggregates (`sum`, `avg`, `min`, `max`) only appear when the\n selection actually contains numbers - selecting text cells shows just the\n count.\n- A single-cell selection shows nothing; the bar appears once a range of two\n or more cells is selected.\n- Edited values are respected: the aggregates read the displayed value, so an\n in-progress edit is reflected.\n- Group rows are skipped.\n\nSee the live [Status bar](https://svgrid.com/demos/144-status-bar/) demo.\n\n## Try it\n\nDrag a rectangle across the Age or Salary column and watch the bar total it.\n\n```svelte {runnable}\n<SvGrid {data} {columns} enableCellSelection statusBar />\n```\n"
6236
6267
  },
6237
6268
  {
6238
6269
  "slug": "help/svelte-5-upgrade-data-tables",
@@ -7618,7 +7649,7 @@ export const docs = [
7618
7649
  "path": "docs/reference/SvGridApi.md",
7619
7650
  "title": "SvGridApi reference",
7620
7651
  "section": "API reference",
7621
- "markdown": "# `SvGridApi` reference\n\nThe imperative API exposed via `<SvGrid onApiReady={(api) => ...}>`.\nUse it for data, column, filter, sort, group, selection, and\nvisibility operations from outside the component.\n\n```ts\nimport type { SvGridApi } from '@svgrid/grid'\n\nlet api = $state<SvGridApi<typeof features, Order> | null>(null)\n```\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onApiReady={(next) => (api = next)}\n/>\n\n<button onclick={() => api?.addRow({ /* ... */ })}>Add row</button>\n```\n\n## Cells\n\n### `getCellValue(rowIndex, columnId)`\n\n```ts\ngetCellValue(rowIndex: number, columnId: string): unknown\n```\n\nRead a cell value from the underlying data. Returns `undefined` when\neither argument doesn't resolve.\n\n### `setCellValue(rowIndex, columnId, value)`\n\n```ts\nsetCellValue(rowIndex: number, columnId: string, value: unknown): void\n```\n\nWrite a cell value through the column's `field`. Triggers a re-render.\nDoes NOT fire `onCellValueChange` - that callback is for **user**\nedits.\n\n## Rows\n\n### `addRow(row, position?)`\n\n```ts\naddRow(row: TData, position?: 'top' | 'bottom' | number): void\n```\n\n`position` defaults to `'bottom'`. A numeric index inserts before that\nindex.\n\n### `addRows(rows, position?)`\n\n```ts\naddRows(rows: ReadonlyArray<TData>, position?: 'top' | 'bottom' | number): void\n```\n\nBatched insert. Cheaper than calling `addRow` in a loop for hundreds\nof rows.\n\n### `removeRow(rowIndex)` / `removeRows(rowIndices)`\n\n```ts\nremoveRow(rowIndex: number): void\nremoveRows(rowIndices: ReadonlyArray<number>): void\n```\n\nRemove by data-array index (the same index `onCellValueChange` reports).\n\n## Columns\n\n### `addColumn(column, position?)` / `addColumns(columns, position?)`\n\n```ts\naddColumn(column: ColumnDef<TFeatures, TData>, position?: 'left' | 'right' | number): void\naddColumns(columns: ReadonlyArray<ColumnDef<TFeatures, TData>>, position?: 'left' | 'right' | number): void\n```\n\n`position` defaults to `'right'`.\n\n### `removeColumn(columnId)`\n\n```ts\nremoveColumn(columnId: string): void\n```\n\nBy id (or `field` when no id was provided).\n\n## Visibility\n\n### `setColumnVisible(columnId, visible)` / `isColumnVisible(columnId)`\n\n```ts\nsetColumnVisible(columnId: string, visible: boolean): void\nisColumnVisible(columnId: string): boolean\n```\n\nHidden columns stay in the column array but don't render.\n\n## Sort\n\n### `setSort(columnId, direction)`\n\n```ts\nsetSort(columnId: string, direction: 'asc' | 'desc' | null): void\n```\n\nReplaces any existing sort. Pass `null` to clear sort on that column.\nMulti-sort through the API is on the\n[Missing features](../help/missing-features.md) list - the user can\nbuild it themselves with Shift-click on headers.\n\n### `clearSort()`\n\n```ts\nclearSort(): void\n```\n\nClear all sort clauses.\n\n## Group\n\n### `setGroupBy(columnIds)`\n\n```ts\nsetGroupBy(columnIds: ReadonlyArray<string>): void\n```\n\nGroup by zero or more columns. Replaces any existing group config.\n\n## Filter\n\n### `setFilter(columnId, filter)`\n\n```ts\nsetFilter(\n columnId: string,\n filter: { operator: SvGridFilterOperator; value?: string } | null,\n): void\n```\n\nWhere `SvGridFilterOperator` is:\n\n```ts\ntype SvGridFilterOperator =\n | 'contains' | 'equals' | 'startsWith'\n | 'greaterThan' | 'lessThan' | 'isBlank'\n```\n\nPass `null` to clear.\n\n### `clearFilter(columnId)`\n\n```ts\nclearFilter(columnId: string): void\n```\n\nClear a single column's filter. (A `clearAllFilters()` helper is on\nthe [Missing features](../help/missing-features.md) list.)\n\n## Data snapshot\n\n### `getData()`\n\n```ts\ngetData(): ReadonlyArray<TData>\n```\n\nSnapshot of the current internal data array - the grid's working\ncopy, which reflects every cell edit and `addRow` / `removeRow` since\nmount.\n\n### `getDisplayedRows()`\n\n```ts\ngetDisplayedRows(): ReadonlyArray<TData>\n```\n\nReturns the rows that are currently **visible** in the grid - after\nfilter, sort, and pagination. Use for `pro.exportData(...)` when you\nwant to export the current view.\n\n## Enterprise extensions\n\nAfter `installEnterprise(api)`, the same object also exposes:\n\n```ts\napi.exportData(opts) // see Enterprise export reference\napi.print(opts)\napi.importData(opts)\napi.ai.filter(...)\napi.ai.smartFill(...)\napi.ai.summarize(...)\napi.ai.classify(...)\napi.pivot.build(config)\napi.pivot.buildFrom(data, config)\n```\n\nSee [Enterprise reference](./enterprise.md).\n"
7652
+ "markdown": "# `SvGridApi` reference\n\nThe imperative API exposed via `<SvGrid onApiReady={(api) => ...}>`.\nUse it for data, column, filter, sort, group, selection, and\nvisibility operations from outside the component.\n\n```ts\nimport type { SvGridApi } from '@svgrid/grid'\n\nlet api = $state<SvGridApi<typeof features, Order> | null>(null)\n```\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onApiReady={(next) => (api = next)}\n/>\n\n<button onclick={() => api?.addRow({ /* ... */ })}>Add row</button>\n```\n\n## Cells\n\n### `getCellValue(rowIndex, columnId)`\n\n```ts\ngetCellValue(rowIndex: number, columnId: string): unknown\n```\n\nRead a cell value from the underlying data. Returns `undefined` when\neither argument doesn't resolve.\n\n### `setCellValue(rowIndex, columnId, value)`\n\n```ts\nsetCellValue(rowIndex: number, columnId: string, value: unknown): void\n```\n\nWrite a cell value through the column's `field`. Triggers a re-render.\nDoes NOT fire `onCellValueChange` - that callback is for **user**\nedits.\n\n## Rows\n\n### `addRow(row, position?)`\n\n```ts\naddRow(row: TData, position?: 'top' | 'bottom' | number): void\n```\n\n`position` defaults to `'bottom'`. A numeric index inserts before that\nindex.\n\n### `addRows(rows, position?)`\n\n```ts\naddRows(rows: ReadonlyArray<TData>, position?: 'top' | 'bottom' | number): void\n```\n\nBatched insert. Cheaper than calling `addRow` in a loop for hundreds\nof rows.\n\n### `removeRow(rowIndex)` / `removeRows(rowIndices)`\n\n```ts\nremoveRow(rowIndex: number): void\nremoveRows(rowIndices: ReadonlyArray<number>): void\n```\n\nRemove by data-array index (the same index `onCellValueChange` reports).\n\n## Columns\n\n### `addColumn(column, position?)` / `addColumns(columns, position?)`\n\n```ts\naddColumn(column: ColumnDef<TFeatures, TData>, position?: 'left' | 'right' | number): void\naddColumns(columns: ReadonlyArray<ColumnDef<TFeatures, TData>>, position?: 'left' | 'right' | number): void\n```\n\n`position` defaults to `'right'`.\n\n### `removeColumn(columnId)`\n\n```ts\nremoveColumn(columnId: string): void\n```\n\nBy id (or `field` when no id was provided).\n\n## Visibility\n\n### `setColumnVisible(columnId, visible)` / `isColumnVisible(columnId)`\n\n```ts\nsetColumnVisible(columnId: string, visible: boolean): void\nisColumnVisible(columnId: string): boolean\n```\n\nHidden columns stay in the column array but don't render.\n\n## Sort\n\n### `setSort(columnId, direction)`\n\n```ts\nsetSort(columnId: string, direction: 'asc' | 'desc' | null): void\n```\n\nReplaces any existing sort. Pass `null` to clear sort on that column.\nMulti-sort through the API is on the\n[Missing features](../help/missing-features.md) list - the user can\nbuild it themselves with Shift-click on headers.\n\n### `clearSort()`\n\n```ts\nclearSort(): void\n```\n\nClear all sort clauses.\n\n## Group\n\n### `setGroupBy(columnIds)`\n\n```ts\nsetGroupBy(columnIds: ReadonlyArray<string>): void\n```\n\nGroup by zero or more columns. Replaces any existing group config.\n\n## Filter\n\n### `setFilter(columnId, filter)`\n\n```ts\nsetFilter(\n columnId: string,\n filter: { operator: SvGridFilterOperator; value?: string } | null,\n): void\n```\n\nWhere `SvGridFilterOperator` is:\n\n```ts\ntype SvGridFilterOperator =\n | 'contains' | 'equals' | 'startsWith'\n | 'greaterThan' | 'lessThan' | 'isBlank'\n```\n\nPass `null` to clear.\n\n### `clearFilter(columnId)`\n\n```ts\nclearFilter(columnId: string): void\n```\n\nClear a single column's filter. (A `clearAllFilters()` helper is on\nthe [Missing features](../help/missing-features.md) list.)\n\n## Data snapshot\n\n### `getData()`\n\n```ts\ngetData(): ReadonlyArray<TData>\n```\n\nSnapshot of the current internal data array - the grid's working\ncopy, which reflects every cell edit and `addRow` / `removeRow` since\nmount.\n\n### `getDisplayedRows()`\n\n```ts\ngetDisplayedRows(): ReadonlyArray<TData>\n```\n\nReturns the rows that are currently **visible** in the grid - after\nfilter, sort, and pagination. Use for `pro.exportData(...)` when you\nwant to export the current view.\n\n### `getRowPosition(rowId)`\n\n```ts\ngetRowPosition(rowId: string): number | null\n```\n\nWhere a row sits in the filtered, sorted rows across every page (group\nbanners included, as paging counts them), or `null` when a filter hides\nit. With client paging, `Math.floor(position / pageSize)` is its page:\n\n```ts\nconst position = api.getRowPosition('ord-1042')\nif (position !== null) {\n const { pageSize } = api.getPageInfo()\n api.setPage(Math.floor(position / pageSize))\n api.scrollToRow(position % pageSize)\n}\n```\n\n## Enterprise extensions\n\nAfter `installEnterprise(api)`, the same object also exposes:\n\n```ts\napi.exportData(opts) // see Enterprise export reference\napi.print(opts)\napi.importData(opts)\napi.ai.filter(...)\napi.ai.smartFill(...)\napi.ai.summarize(...)\napi.ai.classify(...)\napi.pivot.build(config)\napi.pivot.buildFrom(data, config)\n```\n\nSee [Enterprise reference](./enterprise.md).\n"
7622
7653
  },
7623
7654
  {
7624
7655
  "slug": "reference/auto/index",
@@ -8346,8 +8377,8 @@ export const apiReference = {
8346
8377
  ]
8347
8378
  };
8348
8379
  export const apiSurface = {
8349
- "gridVersion": "3.0.20",
8350
- "enterpriseVersion": "3.1.21",
8380
+ "gridVersion": "3.0.22",
8381
+ "enterpriseVersion": "3.1.23",
8351
8382
  "grid": {
8352
8383
  "values": [
8353
8384
  "ALL_FILTER_OPERATORS",
@@ -9212,6 +9243,7 @@ export const apiSurface = {
9212
9243
  "FileRejection",
9213
9244
  "FileUpload",
9214
9245
  "FileUploadConfig",
9246
+ "FilterOperatorExtensions",
9215
9247
  "FilterValueType",
9216
9248
  "FlatRow",
9217
9249
  "FlattenTreeOptions",
@@ -9257,6 +9289,7 @@ export const apiSurface = {
9257
9289
  "GridExportScope",
9258
9290
  "GridExtension",
9259
9291
  "GridExtensionMenuItem",
9292
+ "GridFilterOperator",
9260
9293
  "GridFilterState",
9261
9294
  "GridIconName",
9262
9295
  "GridIcons",
@@ -9556,6 +9589,7 @@ export const apiSurface = {
9556
9589
  "PROTECTED_MESSAGE",
9557
9590
  "PROTECTION_PERMISSIONS",
9558
9591
  "REFERENCE_COLOURS",
9592
+ "RELATIVE_DATE_OPERATOR_IDS",
9559
9593
  "RIBBON_ICONS",
9560
9594
  "RIBBON_ICON_NAMES",
9561
9595
  "RIBBON_TABS",
@@ -9584,6 +9618,7 @@ export const apiSurface = {
9584
9618
  "SvGridGallery",
9585
9619
  "SvGridGantt",
9586
9620
  "SvGridMasterDetail",
9621
+ "SvGridRowCount",
9587
9622
  "SvGridScheduler",
9588
9623
  "SvGridSelectionBar",
9589
9624
  "SvGroupCell",
@@ -9652,6 +9687,8 @@ export const apiSurface = {
9652
9687
  "availableSlots",
9653
9688
  "axisForSelection",
9654
9689
  "blankField",
9690
+ "blanksFirst",
9691
+ "blanksLast",
9655
9692
  "blockPalette",
9656
9693
  "borderShadows",
9657
9694
  "buildAxis",
@@ -9698,6 +9735,7 @@ export const apiSurface = {
9698
9735
  "commonFree",
9699
9736
  "compileNumberFormat",
9700
9737
  "compilePredicate",
9738
+ "compileRelativeDateFilter",
9701
9739
  "compileScalar",
9702
9740
  "completeEntry",
9703
9741
  "controlKind",
@@ -9793,9 +9831,12 @@ export const apiSurface = {
9793
9831
  "enableAdvancedFilter",
9794
9832
  "enableAlerts",
9795
9833
  "enableBoardView",
9834
+ "enableFilterLabels",
9796
9835
  "enableGalleryView",
9797
9836
  "enableGanttView",
9798
9837
  "enablePivot",
9838
+ "enableRelativeDateFilters",
9839
+ "enableRowCount",
9799
9840
  "enableSchedulerView",
9800
9841
  "enableSelectionBar",
9801
9842
  "enableServerRowModel",
@@ -9857,6 +9898,7 @@ export const apiSurface = {
9857
9898
  "getLicenseKey",
9858
9899
  "getLiveDataSample",
9859
9900
  "getPredicateKind",
9901
+ "getRowCounts",
9860
9902
  "getSampleApp",
9861
9903
  "getStarterDataset",
9862
9904
  "getStructureTarget",
@@ -9906,6 +9948,7 @@ export const apiSurface = {
9906
9948
  "isProjectValid",
9907
9949
  "isR1C1",
9908
9950
  "isRangeOperator",
9951
+ "isRelativeDateOperator",
9909
9952
  "isSafeLinkTarget",
9910
9953
  "isScheduleDue",
9911
9954
  "isSchemaValid",
@@ -9919,6 +9962,7 @@ export const apiSurface = {
9919
9962
  "isXlsFile",
9920
9963
  "jsonServerAdapter",
9921
9964
  "kpiSeries",
9965
+ "labelFacetOptions",
9922
9966
  "lettersToCol",
9923
9967
  "licenseCovers",
9924
9968
  "lineShift",
@@ -10030,6 +10074,7 @@ export const apiSurface = {
10030
10074
  "referenceSpans",
10031
10075
  "registerPdfFonts",
10032
10076
  "registerPredicateKind",
10077
+ "relativeDateOperators",
10033
10078
  "remapNotes",
10034
10079
  "removeBlock",
10035
10080
  "removeCf",
@@ -10054,6 +10099,7 @@ export const apiSurface = {
10054
10099
  "resolvePasteCell",
10055
10100
  "resolvePdfCharts",
10056
10101
  "resolvePdfVfs",
10102
+ "resolveRelativeDateFilter",
10057
10103
  "resolveServerGroupMessages",
10058
10104
  "resolveSheetMessages",
10059
10105
  "resolveTableRange",
@@ -10255,6 +10301,7 @@ export const apiSurface = {
10255
10301
  "AxisSegment",
10256
10302
  "AxisSegmentKind",
10257
10303
  "BarRect",
10304
+ "BlanksSortType",
10258
10305
  "Block",
10259
10306
  "BlockConfig",
10260
10307
  "BlockKind",
@@ -10495,6 +10542,7 @@ export const apiSurface = {
10495
10542
  "RelationLookup",
10496
10543
  "RelationLookupConfig",
10497
10544
  "RelationOption",
10545
+ "RelativeDateOperator",
10498
10546
  "RequestParam",
10499
10547
  "ResolvedTask",
10500
10548
  "ResourceAssignment",
@@ -10679,6 +10727,7 @@ export const apiSurface = {
10679
10727
  "@svgrid/enterprise/license",
10680
10728
  "@svgrid/enterprise/pivot",
10681
10729
  "@svgrid/enterprise/print",
10730
+ "@svgrid/enterprise/review",
10682
10731
  "@svgrid/enterprise/server",
10683
10732
  "@svgrid/enterprise/sheet",
10684
10733
  "@svgrid/enterprise/studio",
@@ -11656,6 +11705,11 @@ export const apiSurface = {
11656
11705
  "optional": true,
11657
11706
  "type": "(value: unknown) => number | null | undefined"
11658
11707
  },
11708
+ {
11709
+ "name": "sortComparator",
11710
+ "optional": true,
11711
+ "type": "(a: unknown, b: unknown, desc: boolean) => number"
11712
+ },
11659
11713
  {
11660
11714
  "name": "aggregate",
11661
11715
  "optional": true,
@@ -11901,6 +11955,7 @@ export const apiSurface = {
11901
11955
  "getPageInfo",
11902
11956
  "getRowHeight",
11903
11957
  "getRowId",
11958
+ "getRowPosition",
11904
11959
  "getSavedCharts",
11905
11960
  "getSelected",
11906
11961
  "getSelectedLast",
package/dist/preview.d.ts CHANGED
@@ -8,7 +8,7 @@ export declare const UI_MIME_TYPE = "text/html;profile=mcp-app";
8
8
  * start failing in a way nobody is watching for. `tools/mcp-tools.test.ts` checks these
9
9
  * against the workspace so they cannot quietly rot either.
10
10
  */
11
- export declare const PREVIEW_GRID_WC_VERSION = "3.0.28";
11
+ export declare const PREVIEW_GRID_WC_VERSION = "3.0.30";
12
12
  export declare function previewResource(): {
13
13
  uri: string;
14
14
  name: string;
package/dist/preview.js CHANGED
@@ -27,7 +27,7 @@ export const UI_MIME_TYPE = 'text/html;profile=mcp-app';
27
27
  * start failing in a way nobody is watching for. `tools/mcp-tools.test.ts` checks these
28
28
  * against the workspace so they cannot quietly rot either.
29
29
  */
30
- export const PREVIEW_GRID_WC_VERSION = '3.0.28';
30
+ export const PREVIEW_GRID_WC_VERSION = '3.0.30';
31
31
  const EXT_APPS_VERSION = '1.7.5';
32
32
  const CDN = 'https://cdn.jsdelivr.net/npm';
33
33
  /**
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "type": "commercial",
6
6
  "url": "https://svgrid.com/pricing"
7
7
  },
8
- "version": "3.0.27",
8
+ "version": "3.0.29",
9
9
  "description": "Model Context Protocol server for SvGrid, the Svelte 5 data grid: checks the code your AI writes against the real API surface, plus version-pinned docs, API reference and 373 demo sources.",
10
10
  "license": "MIT",
11
11
  "author": "jQWidgets <sales@jqwidgets.com>",
@@ -35,7 +35,7 @@
35
35
  "zod": "^3.23.8"
36
36
  },
37
37
  "peerDependencies": {
38
- "@svgrid/enterprise": "^3.1.21"
38
+ "@svgrid/enterprise": "^3.1.23"
39
39
  },
40
40
  "peerDependenciesMeta": {
41
41
  "@svgrid/enterprise": {
@@ -45,7 +45,7 @@
45
45
  "devDependencies": {
46
46
  "@types/node": "^22.10.7",
47
47
  "typescript": "6.0.3",
48
- "@svgrid/enterprise": "^3.1.21"
48
+ "@svgrid/enterprise": "^3.1.23"
49
49
  },
50
50
  "engines": {
51
51
  "node": ">=18"
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "com.svgrid/svgrid",
4
4
  "title": "SvGrid",
5
5
  "description": "Checks AI-written SvGrid code against the real API, plus version-pinned Svelte 5 grid docs.",
6
- "version": "3.0.27",
6
+ "version": "3.0.29",
7
7
  "websiteUrl": "https://svgrid.com/docs/help/mcp-server/",
8
8
  "repository": {
9
9
  "url": "https://github.com/sv-grid/sv-grid",
@@ -15,7 +15,7 @@
15
15
  "registryType": "npm",
16
16
  "registryBaseUrl": "https://registry.npmjs.org",
17
17
  "identifier": "@svgrid/mcp",
18
- "version": "3.0.27",
18
+ "version": "3.0.29",
19
19
  "runtimeHint": "npx",
20
20
  "transport": {
21
21
  "type": "stdio"