@svgrid/mcp 3.0.29 → 3.0.31

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
@@ -4063,6 +4063,14 @@ export const examples = [
4063
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
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
4065
  },
4066
+ {
4067
+ "id": "703-test-run-tree",
4068
+ "path": "examples/src/demos/703-test-run-tree.svelte",
4069
+ "title": "Test Run Tree",
4070
+ "category": "Tree & Hierarchy",
4071
+ "blurb": "703. Test results tree - reload one subtree A release-qualification board for a kernel candidate. Each test environment (architecture + machine) holds its reported issues and its",
4072
+ "source": "<script lang=\"ts\">\n /**\n * 703. Test results tree - reload one subtree\n * -------------------------------------------\n * A release-qualification board for a kernel candidate. Each test\n * environment (architecture + machine) holds its reported issues and its\n * test plans; a plan holds its runs, and a run its results split into\n * Failed, Passed and Skipped.\n *\n * The grid's own `treeData` builds the hierarchy from flat rows whose ids\n * are paths (`env:amd64-precision-3680/plans/automated/runs/2`). The reload\n * icon on an environment, plan or run row asks the server for that subtree\n * only and splices the answer back into the flat array in place. `getRowId`\n * keeps the ids stable, so the controlled `expanded` map leaves every open\n * node open across the reload.\n *\n * The server here is in memory and does not wait for you: a running run\n * reports a result every couple of seconds, and the grid sees it only when\n * that run, or a node above it, is reloaded. Rerun queues a new run, Add\n * result posts a manual result, Add records an environment issue, and the\n * environment checkboxes approve or reject in bulk. Every request is in the\n * log under the grid.\n */\n import {\n SvGrid,\n SvModal,\n SvButton,\n SvTextInput,\n SvTextArea,\n SvDropDownList,\n SvSegmented,\n tableFeatures,\n renderSnippet,\n type GridColumns,\n } from '@svgrid/grid'\n\n type Outcome = 'failed' | 'passed' | 'skipped'\n type Review = 'undecided' | 'approved' | 'rejected'\n type RunStatus = 'queued' | 'running' | 'complete'\n type Kind = 'env' | 'issues' | 'issue' | 'plans' | 'plan' | 'run' | 'bucket' | 'result'\n\n // ---- Server records --------------------------------------------------------\n type TestResult = { test: string; outcome: Outcome; seconds: number; comment: string }\n type RunRec = {\n n: number\n status: RunStatus\n startedAt: number\n startAt: number\n results: TestResult[]\n pending: TestResult[]\n }\n type PlanRec = { key: string; name: string; manual: boolean; tests: string[]; runs: RunRec[] }\n type IssueRec = { n: number; title: string; bug: string }\n type EnvRec = {\n key: string\n arch: string\n machine: string\n hardware: string\n review: Review\n issues: IssueRec[]\n plans: PlanRec[]\n }\n\n // ---- What the API returns: one flat row per node ---------------------------\n type TestRow = {\n id: string\n parentId: string | null\n kind: Kind\n name: string\n detail: string\n fetchedAt: number\n arch?: string\n review?: Review\n manual?: boolean\n tests?: string[]\n runStatus?: RunStatus\n done?: number\n total?: number\n outcome?: Outcome\n count?: number\n seconds?: number\n }\n\n const OUTCOMES: Outcome[] = ['failed', 'passed', 'skipped']\n const OUTCOME_LABEL: Record<Outcome, string> = { failed: 'Failed', passed: 'Passed', skipped: 'Skipped' }\n const REVIEW_LABEL: Record<Review, string> = { undecided: 'Undecided', approved: 'Approved', rejected: 'Rejected' }\n const RELOADABLE = new Set<Kind>(['env', 'plan', 'run'])\n\n const ARTEFACT = 'linux-generic 6.11.0-19.19'\n\n const AUTOMATED = [\n 'boot/kernel-version',\n 'cpu/topology',\n 'cpu/frequency-governor',\n 'memory/stress-ng-60s',\n 'disk/read-performance',\n 'disk/smart-self-test',\n 'ethernet/ping-gateway',\n 'wireless/connect-wpa2-5ghz',\n 'bluetooth/detect',\n 'suspend/resume-cycle',\n 'suspend/wireless-after-resume',\n 'usb/storage-insert',\n 'graphics/modeset',\n ]\n const MANUAL = [\n 'audio/headphone-jack-playback',\n 'camera/preview',\n 'display/external-hdmi-hotplug',\n 'keys/brightness',\n 'touchpad/two-finger-scroll',\n ]\n\n // Failures and skips each machine produces, with the comment the harness\n // attaches. Everything else passes.\n const FAILS: Record<string, Record<string, string>> = {\n 'amd64-thinkpad-x13-g4': { 'suspend/wireless-after-resume': 'wlp0s20f3 has no carrier 30 s after resume' },\n 'amd64-precision-3680': {\n 'graphics/modeset': 'DP-2: atomic commit failed, -EINVAL',\n 'disk/read-performance': '1.1 GB/s, threshold 1.5 GB/s',\n },\n 'riscv64-visionfive-2': {\n 'disk/smart-self-test': 'no NVMe controller on PCIe bus 0000:01',\n 'disk/read-performance': 'no block device to test',\n 'cpu/frequency-governor': 'schedutil not available',\n },\n }\n const SKIPS: Record<string, string[]> = {\n 'amd64-thinkpad-x13-g4': ['bluetooth/detect'],\n 'arm64-rpi5-8gb': ['wireless/connect-wpa2-5ghz', 'suspend/resume-cycle', 'suspend/wireless-after-resume'],\n 'riscv64-visionfive-2': ['graphics/modeset', 'bluetooth/detect'],\n 'arm64-manual': ['camera/preview'],\n }\n\n // Seeded so a reload of the page draws the same durations.\n let seed = 703\n function rand(): number {\n seed = (seed * 1103515245 + 12345) & 0x7fffffff\n return seed / 0x7fffffff\n }\n\n function resultsFor(envKey: string, tests: string[]): TestResult[] {\n return tests.map((test) => {\n const comment = FAILS[envKey]?.[test]\n const skipped = SKIPS[envKey]?.includes(test)\n return {\n test,\n outcome: comment ? 'failed' : skipped ? 'skipped' : 'passed',\n seconds: skipped ? 0 : Math.round(2 + rand() * 70),\n comment: comment ?? (skipped ? 'requirement not met on this machine' : ''),\n }\n })\n }\n\n const T0 = Date.now()\n function completeRun(n: number, envKey: string, tests: string[], minutesAgo: number): RunRec {\n return { n, status: 'complete', startedAt: T0 - minutesAgo * 60_000, startAt: 0, results: resultsFor(envKey, tests), pending: [] }\n }\n function liveRun(n: number, envKey: string, tests: string[], reported: number, minutesAgo: number): RunRec {\n const all = resultsFor(envKey, tests)\n return { n, status: 'running', startedAt: T0 - minutesAgo * 60_000, startAt: 0, results: all.slice(0, reported), pending: all.slice(reported) }\n }\n\n const db: EnvRec[] = [\n {\n key: 'amd64-precision-3680', arch: 'amd64', machine: 'dell-precision-3680', hardware: 'Core i9-14900K, RTX A2000',\n review: 'undecided',\n issues: [{ n: 1, title: 'DisplayPort 2 stays dark after modeset', bug: 'BUG-4127' }],\n plans: [{\n key: 'automated', name: 'Automated testing', manual: false, tests: AUTOMATED,\n runs: [completeRun(1, 'amd64-precision-3680', AUTOMATED, 190), liveRun(2, 'amd64-precision-3680', AUTOMATED, 6, 4)],\n }],\n },\n {\n key: 'arm64-manual', arch: 'arm64', machine: 'user manual tests', hardware: 'Lab bench, any arm64 laptop',\n review: 'approved',\n issues: [],\n plans: [{\n key: 'manual', name: 'Manual testing', manual: true, tests: MANUAL,\n runs: [{ ...completeRun(1, 'arm64-manual', MANUAL, 300), results: resultsFor('arm64-manual', MANUAL).slice(0, 4), status: 'running' }],\n }],\n },\n {\n key: 'amd64-thinkpad-x13-g4', arch: 'amd64', machine: 'lenovo-thinkpad-x13-g4', hardware: 'Core i7-1365U, AX211 Wi-Fi',\n review: 'undecided',\n issues: [{ n: 1, title: 'Wi-Fi does not come back after suspend (iwlwifi)', bug: 'BUG-4119' }],\n plans: [\n { key: 'automated', name: 'Automated testing', manual: false, tests: AUTOMATED, runs: [completeRun(1, 'amd64-thinkpad-x13-g4', AUTOMATED, 75)] },\n { key: 'manual', name: 'Manual testing', manual: true, tests: MANUAL, runs: [] },\n ],\n },\n {\n key: 'arm64-rpi5-8gb', arch: 'arm64', machine: 'raspberry-pi-5-8gb', hardware: 'Cortex-A76, 8 GB',\n review: 'undecided',\n issues: [],\n plans: [{ key: 'automated', name: 'Automated testing', manual: false, tests: AUTOMATED, runs: [liveRun(1, 'arm64-rpi5-8gb', AUTOMATED, 3, 2)] }],\n },\n {\n key: 'riscv64-visionfive-2', arch: 'riscv64', machine: 'starfive-visionfive-2', hardware: 'JH7110, 8 GB',\n review: 'rejected',\n issues: [{ n: 1, title: 'PCIe NVMe not detected on boot', bug: 'BUG-4102' }],\n plans: [{ key: 'automated', name: 'Automated testing', manual: false, tests: AUTOMATED, runs: [completeRun(1, 'riscv64-visionfive-2', AUTOMATED, 420)] }],\n },\n ]\n\n // ---- Rows for one environment, in tree order ------------------------------\n function envRows(env: EnvRec, at: number): TestRow[] {\n const id = `env:${env.key}`\n const out: TestRow[] = [{ id, parentId: null, kind: 'env', name: env.machine, arch: env.arch, detail: env.hardware, review: env.review, fetchedAt: at }]\n\n const issuesId = `${id}/issues`\n out.push({ id: issuesId, parentId: id, kind: 'issues', name: 'Reported environment issues', count: env.issues.length, detail: '', fetchedAt: at })\n for (const issue of env.issues) {\n out.push({ id: `${issuesId}/${issue.n}`, parentId: issuesId, kind: 'issue', name: issue.title, detail: issue.bug, fetchedAt: at })\n }\n\n const plansId = `${id}/plans`\n out.push({ id: plansId, parentId: id, kind: 'plans', name: 'Test plans', count: env.plans.length, detail: '', fetchedAt: at })\n for (const plan of env.plans) {\n const planId = `${plansId}/${plan.key}`\n out.push({\n id: planId, parentId: plansId, kind: 'plan', name: plan.name, manual: plan.manual, tests: plan.tests,\n detail: `${plan.tests.length} tests, ${plan.runs.length} run${plan.runs.length === 1 ? '' : 's'}`, fetchedAt: at,\n })\n // Newest run first, the one a reviewer cares about.\n for (const run of [...plan.runs].reverse()) {\n const runId = `${planId}/runs/${run.n}`\n out.push({\n id: runId, parentId: planId, kind: 'run', name: `Run ${run.n}`, runStatus: run.status,\n done: run.results.length, total: plan.tests.length,\n detail: run.status === 'queued' ? 'waiting for a machine' : `started ${clock(run.startedAt)}`, fetchedAt: at,\n })\n for (const outcome of OUTCOMES) {\n const bucketId = `${runId}/${outcome}`\n const hits = run.results.filter((r) => r.outcome === outcome)\n out.push({ id: bucketId, parentId: runId, kind: 'bucket', name: OUTCOME_LABEL[outcome], outcome, count: hits.length, detail: '', fetchedAt: at })\n for (const r of hits) {\n out.push({ id: `${bucketId}/${r.test}`, parentId: bucketId, kind: 'result', name: r.test, outcome, seconds: r.seconds, detail: r.comment, fetchedAt: at })\n }\n }\n }\n }\n return out\n }\n\n // ---- The server -------------------------------------------------------------\n const wait = () => new Promise<void>((resolve) => setTimeout(resolve, 260 + Math.random() * 420))\n const envKeyOf = (id: string) => id.slice(4).split('/')[0]\n const findEnv = (id: string) => db.find((e) => e.key === envKeyOf(id))\n function findPlan(id: string): PlanRec | undefined {\n const m = /\\/plans\\/([^/]+)/.exec(id)\n return m ? findEnv(id)?.plans.find((p) => p.key === m[1]) : undefined\n }\n function findRun(id: string): RunRec | undefined {\n const m = /\\/runs\\/(\\d+)/.exec(id)\n return m ? findPlan(id)?.runs.find((r) => r.n === Number(m[1])) : undefined\n }\n const inSubtree = (rootId: string, id: string) => id === rootId || id.startsWith(rootId + '/')\n\n const server = {\n snapshot(): TestRow[] {\n const at = Date.now()\n return db.flatMap((env) => envRows(env, at))\n },\n async getSubtree(id: string): Promise<TestRow[]> {\n await wait()\n const env = findEnv(id)\n return env ? envRows(env, Date.now()).filter((r) => inSubtree(id, r.id)) : []\n },\n async setReview(envIds: string[], review: Review): Promise<void> {\n await wait()\n for (const id of envIds) {\n const env = findEnv(id)\n if (env) env.review = review\n }\n },\n async addIssue(envId: string, title: string, bug: string): Promise<void> {\n await wait()\n const env = findEnv(envId)\n if (env) env.issues.push({ n: env.issues.length + 1, title, bug })\n },\n async rerun(planId: string): Promise<number> {\n await wait()\n const env = findEnv(planId)\n const plan = findPlan(planId)\n if (!env || !plan) return 0\n const n = plan.runs.length + 1\n plan.runs.push(\n plan.manual\n // A manual run is open until a tester has reported every test.\n ? { n, status: 'running', startedAt: Date.now(), startAt: 0, results: [], pending: [] }\n : { n, status: 'queued', startedAt: 0, startAt: Date.now() + 3000, results: [], pending: resultsFor(env.key, plan.tests) },\n )\n return n\n },\n async addResult(runId: string, result: TestResult): Promise<void> {\n await wait()\n const plan = findPlan(runId)\n const run = findRun(runId)\n if (!plan || !run) return\n run.results = [...run.results.filter((r) => r.test !== result.test), result]\n run.pending = run.pending.filter((r) => r.test !== result.test)\n if (run.results.length >= plan.tests.length) run.status = 'complete'\n },\n // The lab keeps working whether or not anyone is looking.\n tick() {\n const now = Date.now()\n for (const env of db) {\n for (const plan of env.plans) {\n for (const run of plan.runs) {\n if (run.status === 'queued' && run.startAt <= now) {\n run.status = 'running'\n run.startedAt = now\n } else if (run.status === 'running' && run.pending.length) {\n run.results.push(run.pending.shift()!)\n if (!run.pending.length) run.status = 'complete'\n }\n }\n }\n }\n },\n }\n\n // ---- Client state -----------------------------------------------------------\n const firstLoad = server.snapshot()\n let rows = $state<TestRow[]>(firstLoad)\n let expanded = $state<Record<string, boolean>>({\n 'env:amd64-precision-3680': true,\n 'env:amd64-precision-3680/plans': true,\n 'env:amd64-precision-3680/plans/automated': true,\n 'env:amd64-precision-3680/plans/automated/runs/2': true,\n 'env:arm64-manual': true,\n 'env:arm64-manual/plans': true,\n 'env:arm64-manual/plans/manual': true,\n 'env:arm64-manual/plans/manual/runs/1': true,\n })\n let reloading = $state<Record<string, boolean>>({})\n let arrived = $state<Record<string, number>>({})\n let selected = $state<Record<string, boolean>>({})\n let now = $state(Date.now())\n\n type LogEntry = { n: number; at: number; method: 'GET' | 'POST' | 'PATCH'; path: string; note: string }\n let log = $state<LogEntry[]>([{ n: 1, at: Date.now(), method: 'GET', path: `/api/v1/artefacts/${slug(ARTEFACT)}/environments`, note: `${firstLoad.length} rows, page load` }])\n function record(method: LogEntry['method'], path: string, note: string) {\n log = [{ n: (log[0]?.n ?? 0) + 1, at: Date.now(), method, path, note }, ...log].slice(0, 5)\n }\n\n $effect(() => {\n const lab = setInterval(() => server.tick(), 1800)\n const clockTimer = setInterval(() => (now = Date.now()), 1000)\n return () => {\n clearInterval(lab)\n clearInterval(clockTimer)\n }\n })\n\n function apiPath(id: string): string {\n return `/api/v1/environments/${id.slice(4)}`\n }\n\n /** Re-read one node and everything under it, and splice it back in place. */\n async function reload(id: string): Promise<void> {\n if (reloading[id]) return\n reloading = { ...reloading, [id]: true }\n const t0 = performance.now()\n try {\n const next = await server.getSubtree(id)\n const before = new Map(rows.filter((r) => inSubtree(id, r.id)).map((r) => [r.id, r]))\n const at = rows.findIndex((r) => r.id === id)\n const rest = rows.filter((r) => !inSubtree(id, r.id))\n // The subtree is one contiguous block starting at the node, so the rows\n // before it are exactly rest's first `at` entries.\n rows = at < 0 ? [...rest, ...next] : [...rest.slice(0, at), ...next, ...rest.slice(at)]\n\n const stamp = Date.now()\n const fresh = next.filter((r) => !before.has(r.id) && (r.kind === 'result' || r.kind === 'issue' || r.kind === 'run'))\n if (fresh.length) arrived = { ...arrived, ...Object.fromEntries(fresh.map((r) => [r.id, stamp])) }\n\n const results = fresh.filter((r) => r.kind === 'result').length\n const ms = Math.round(performance.now() - t0)\n const note = results\n ? `${results} new result${results === 1 ? '' : 's'}`\n : fresh.length ? `${fresh.length} new` : 'no changes'\n record('GET', apiPath(id), `${next.length} rows, ${ms} ms, ${note}`)\n } finally {\n reloading = Object.fromEntries(Object.entries(reloading).filter(([key]) => key !== id))\n }\n }\n\n function reloadAll() {\n for (const r of rows) if (r.kind === 'env') void reload(r.id)\n }\n\n async function setReview(envIds: string[], review: Review) {\n await server.setReview(envIds, review)\n record('PATCH', '/api/v1/environments/review', `${envIds.length} set to ${REVIEW_LABEL[review]}`)\n const ids = new Set(envIds)\n rows = rows.map((r) => (ids.has(r.id) ? { ...r, review } : r))\n selected = {}\n }\n\n async function rerun(planId: string) {\n const n = await server.rerun(planId)\n record('POST', `${apiPath(planId)}/runs`, `Run ${n} created`)\n expanded = { ...expanded, [planId]: true }\n await reload(planId)\n }\n\n // ---- Dialogs ----------------------------------------------------------------\n type Dialog = { kind: 'issue'; envId: string; title: string } | { kind: 'result'; runId: string; title: string } | null\n let dialog = $state<Dialog>(null)\n let form = $state({ title: '', bug: '', test: '', outcome: 'passed' as Outcome, comment: '' })\n let saving = $state(false)\n\n function envLabel(envId: string): string {\n const env = rows.find((r) => r.id === envId)\n return env ? `${env.arch} ${env.name}` : ''\n }\n\n function openIssue(issuesId: string) {\n const envId = issuesId.replace(/\\/issues$/, '')\n form = { title: '', bug: '', test: '', outcome: 'passed', comment: '' }\n dialog = { kind: 'issue', envId, title: `Report an issue on ${envLabel(envId)}` }\n }\n\n /** Tests in the run's plan that have no result yet. */\n function untested(runId: string): string[] {\n const planId = runId.replace(/\\/runs\\/\\d+$/, '')\n const plan = rows.find((r) => r.id === planId)\n const reported = new Set(rows.filter((r) => r.kind === 'result' && inSubtree(runId, r.id)).map((r) => r.name))\n return (plan?.tests ?? []).filter((t) => !reported.has(t))\n }\n\n function openResult(runId: string) {\n const first = untested(runId)[0] ?? ''\n const run = rows.find((r) => r.id === runId)\n form = { title: '', bug: '', test: first, outcome: 'passed', comment: '' }\n dialog = { kind: 'result', runId, title: `Add a result to ${run?.name ?? 'run'}, ${envLabel(runId.split('/')[0])}` }\n }\n\n const testOptions = $derived(dialog?.kind === 'result' ? untested(dialog.runId).map((t) => ({ value: t, label: t })) : [])\n const outcomeOptions = OUTCOMES.map((o) => ({ value: o, label: OUTCOME_LABEL[o] }))\n const canSave = $derived(\n !saving && (dialog?.kind === 'issue' ? form.title.trim() !== '' : dialog?.kind === 'result' ? form.test !== '' : false),\n )\n\n async function save() {\n const d = dialog\n if (!d || !canSave) return\n saving = true\n try {\n if (d.kind === 'issue') {\n await server.addIssue(d.envId, form.title.trim(), form.bug.trim() || 'not filed')\n record('POST', `${apiPath(d.envId)}/issues`, form.title.trim())\n const issuesId = `${d.envId}/issues`\n expanded = { ...expanded, [d.envId]: true, [issuesId]: true }\n dialog = null\n await reload(issuesId)\n } else {\n const outcome = form.outcome\n await server.addResult(d.runId, { test: form.test, outcome, seconds: 0, comment: form.comment.trim() })\n record('POST', `${apiPath(d.runId)}/results`, `${form.test}: ${OUTCOME_LABEL[outcome]}`)\n expanded = { ...expanded, [d.runId]: true, [`${d.runId}/${outcome}`]: true }\n dialog = null\n await reload(d.runId)\n }\n } finally {\n saving = false\n }\n }\n\n // ---- Toolbar ----------------------------------------------------------------\n const selectedIds = $derived(Object.keys(selected).filter((id) => selected[id]))\n const envs = $derived(rows.filter((r) => r.kind === 'env'))\n const summary = $derived.by(() => {\n let failed = 0\n let running = 0\n for (const r of rows) {\n if (r.kind === 'bucket' && r.outcome === 'failed') failed += r.count ?? 0\n if (r.kind === 'run' && r.runStatus !== 'complete') running += 1\n }\n const approved = envs.filter((e) => e.review === 'approved').length\n return { failed, running, approved }\n })\n\n function expandAll() {\n const parents = new Set(rows.map((r) => r.parentId).filter((p): p is string => p != null))\n expanded = Object.fromEntries([...parents].map((id) => [id, true]))\n }\n\n function toggleSelected(id: string) {\n selected = { ...selected, [id]: !selected[id] }\n }\n\n // ---- Formatting -------------------------------------------------------------\n function clock(t: number): string {\n return new Date(t).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })\n }\n function ago(t: number): string {\n const s = Math.max(0, Math.round((now - t) / 1000))\n if (s < 5) return 'just now'\n if (s < 60) return `${s} s ago`\n return `${Math.floor(s / 60)} min ago`\n }\n function slug(s: string): string {\n return s.replace(/[^a-z0-9.]+/gi, '-')\n }\n function labelOf(r: TestRow): string {\n if (r.kind === 'issues') return `${r.name} (${r.count ?? 0})`\n if (r.kind === 'bucket') return `${r.name} ${r.count ?? 0}`\n return r.name\n }\n const isNew = (id: string) => arrived[id] != null && now - arrived[id] < 6000\n // A running run's counts go stale while the lab keeps reporting.\n const isBehind = (r: TestRow) => r.kind === 'run' && r.runStatus !== 'complete' && now - r.fetchedAt > 15_000\n\n const features = tableFeatures({})\n const columns: GridColumns<TestRow> = [\n { id: 'name', header: 'Environment / test', width: 380, fieldFn: (r) => labelOf(r), cell: (ctx) => renderSnippet(NameCell, { row: ctx.row.original }) },\n { id: 'status', header: 'Status', width: 150, fieldFn: (r) => r.review ?? r.runStatus ?? r.outcome ?? '', cell: (ctx) => renderSnippet(StatusCell, { row: ctx.row.original }) },\n { id: 'detail', header: 'Detail', width: 260, fieldFn: (r) => r.detail, cell: (ctx) => renderSnippet(DetailCell, { row: ctx.row.original }) },\n { id: 'updated', header: 'Fetched', width: 110, fieldFn: (r) => (RELOADABLE.has(r.kind) ? ago(r.fetchedAt) : ''), cell: (ctx) => renderSnippet(UpdatedCell, { row: ctx.row.original }) },\n { id: 'actions', header: '', width: 190, fieldFn: () => '', cell: (ctx) => renderSnippet(ActionsCell, { row: ctx.row.original }) },\n ]\n</script>\n\n{#snippet NameCell(props: { row: TestRow })}\n {@const r = props.row}\n <span class=\"tr703-name\" data-kind={r.kind}>\n {#if r.kind === 'env'}\n <input\n type=\"checkbox\"\n class=\"tr703-check\"\n checked={!!selected[r.id]}\n onclick={(e) => e.stopPropagation()}\n onchange={() => toggleSelected(r.id)}\n aria-label={`Select ${r.arch} ${r.name}`}\n />\n {/if}\n {#if RELOADABLE.has(r.kind)}\n <button\n type=\"button\"\n class=\"tr703-reload\"\n class:tr703-spin={!!reloading[r.id]}\n disabled={!!reloading[r.id]}\n title=\"Reload this subtree from the server\"\n aria-label={`Reload ${r.kind === 'env' ? `${r.arch} ${r.name}` : r.name}`}\n onclick={(e) => { e.stopPropagation(); void reload(r.id) }}\n >\n <svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">\n <path d=\"M13.5 8a5.5 5.5 0 1 1-1.6-3.9\" />\n <polyline points=\"13.5 2.5 13.5 5.5 10.5 5.5\" />\n </svg>\n </button>\n {/if}\n {#if r.kind === 'env'}\n <span class=\"tr703-arch\">{r.arch}</span>\n {:else if r.kind === 'bucket' || r.kind === 'result'}\n <span class=\"tr703-glyph\" data-outcome={r.outcome} aria-hidden=\"true\">\n {#if r.outcome === 'passed'}\n <svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\"><circle cx=\"8\" cy=\"8\" r=\"6.5\" /><polyline points=\"5 8.2 7.1 10.2 11 6\" /></svg>\n {:else if r.outcome === 'failed'}\n <svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\"><circle cx=\"8\" cy=\"8\" r=\"6.5\" /><path d=\"M5.8 5.8l4.4 4.4M10.2 5.8l-4.4 4.4\" /></svg>\n {:else}\n <svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\"><circle cx=\"8\" cy=\"8\" r=\"6.5\" /><path d=\"M5 8h6\" /></svg>\n {/if}\n </span>\n {/if}\n <span class=\"tr703-label\" class:tr703-mono={r.kind === 'result'}>{labelOf(r)}</span>\n {#if isNew(r.id)}<span class=\"tr703-new\">new</span>{/if}\n </span>\n{/snippet}\n\n{#snippet StatusCell(props: { row: TestRow })}\n {@const r = props.row}\n {#if r.kind === 'env' && r.review}\n <span class=\"tr703-pill\" data-tone={r.review}>{REVIEW_LABEL[r.review]}</span>\n {:else if r.kind === 'run'}\n {#if r.runStatus === 'queued'}\n <span class=\"tr703-pill\" data-tone=\"undecided\">Queued</span>\n {:else if r.runStatus === 'running'}\n <span class=\"tr703-progress\" title={`${r.done} of ${r.total} tests reported`}>\n <span class=\"tr703-bar\"><span style={`width:${((r.done ?? 0) / (r.total || 1)) * 100}%`}></span></span>\n <span class=\"tr703-num\">{r.done}/{r.total}</span>\n </span>\n {:else}\n <span class=\"tr703-pill\" data-tone=\"done\">Complete</span>\n {/if}\n {:else if r.kind === 'plan'}\n <span class=\"tr703-tag\">{r.manual ? 'manual' : 'automated'}</span>\n {:else if r.kind === 'result' && r.outcome}\n <span class=\"tr703-pill\" data-tone={r.outcome}>{OUTCOME_LABEL[r.outcome]}</span>\n {/if}\n{/snippet}\n\n{#snippet DetailCell(props: { row: TestRow })}\n {@const r = props.row}\n {#if r.kind === 'result'}\n <span class=\"tr703-detail\">\n {#if r.seconds}<span class=\"tr703-num\">{r.seconds} s</span>{/if}\n {#if r.detail}<span class=\"tr703-muted\" title={r.detail}>{r.detail}</span>{/if}\n </span>\n {:else if r.kind === 'issue'}\n <span class=\"tr703-bug\">{r.detail}</span>\n {:else}\n <span class=\"tr703-muted\">{r.detail}</span>\n {/if}\n{/snippet}\n\n{#snippet UpdatedCell(props: { row: TestRow })}\n {@const r = props.row}\n {#if RELOADABLE.has(r.kind)}\n <span class=\"tr703-ago\" class:tr703-behind={isBehind(r)} title={isBehind(r) ? 'The lab may have reported more results since. Reload this run.' : undefined}>\n {ago(r.fetchedAt)}\n </span>\n {/if}\n{/snippet}\n\n{#snippet ActionsCell(props: { row: TestRow })}\n {@const r = props.row}\n <span class=\"tr703-actions\">\n {#if r.kind === 'env'}\n {#if r.review === 'undecided'}\n <button type=\"button\" class=\"tr703-link\" onclick={() => setReview([r.id], 'approved')}>Approve</button>\n <button type=\"button\" class=\"tr703-link\" onclick={() => setReview([r.id], 'rejected')}>Reject</button>\n {:else}\n <button type=\"button\" class=\"tr703-link\" onclick={() => setReview([r.id], 'undecided')}>Reopen</button>\n {/if}\n {:else if r.kind === 'issues'}\n <button type=\"button\" class=\"tr703-link\" onclick={() => openIssue(r.id)}>Add</button>\n {:else if r.kind === 'plan'}\n <button type=\"button\" class=\"tr703-link\" onclick={() => rerun(r.id)}>Rerun</button>\n {:else if r.kind === 'run' && r.runStatus !== 'queued' && untested(r.id).length}\n <button type=\"button\" class=\"tr703-link\" onclick={() => openResult(r.id)}>Add result</button>\n {/if}\n </span>\n{/snippet}\n\n<section class=\"tr703 flex flex-col flex-1 min-h-0 gap-3\">\n <header class=\"tr703-head\">\n <div class=\"tr703-artefact\">\n <span class=\"tr703-mono\">{ARTEFACT}</span>\n <span class=\"tr703-tag\">proposed</span>\n </div>\n <div class=\"tr703-facts\">\n <span><strong>{summary.approved}</strong> of {envs.length} environments approved</span>\n <span><strong>{summary.failed}</strong> failed results</span>\n <span><strong>{summary.running}</strong> {summary.running === 1 ? 'run' : 'runs'} open</span>\n </div>\n </header>\n\n <div class=\"tr703-toolbar\">\n {#if selectedIds.length}\n <span class=\"tr703-muted\">{selectedIds.length} selected</span>\n <SvButton size=\"sm\" onclick={() => setReview(selectedIds, 'approved')}>Approve</SvButton>\n <SvButton size=\"sm\" variant=\"outline\" onclick={() => setReview(selectedIds, 'rejected')}>Reject</SvButton>\n <SvButton size=\"sm\" variant=\"ghost\" onclick={() => (selected = {})}>Clear</SvButton>\n {:else}\n <span class=\"tr703-muted\">Tick environments to review them together. The reload icon re-reads that node and everything under it.</span>\n {/if}\n <span class=\"tr703-spacer\"></span>\n <SvButton size=\"sm\" variant=\"outline\" onclick={expandAll}>Expand all</SvButton>\n <SvButton size=\"sm\" variant=\"outline\" onclick={() => (expanded = {})}>Collapse all</SvButton>\n <SvButton size=\"sm\" variant=\"outline\" onclick={reloadAll}>Reload all</SvButton>\n </div>\n\n <div class=\"tr703-grid flex-1 min-h-0\">\n <SvGrid\n data={rows}\n {columns}\n {features}\n treeData={{ parentField: 'parentId', column: 'name', indentPx: 18 }}\n getRowId={(r) => r.id}\n {expanded}\n onExpandedChange={(next) => (expanded = next)}\n selectionMode=\"none\"\n filterMode=\"none\"\n enableInlineEditing={false}\n rowHeight={36}\n containerHeight=\"100%\"\n fitColumns\n columnResize\n responsive\n />\n </div>\n\n <ol class=\"tr703-log\" aria-label=\"Requests\" aria-live=\"polite\">\n {#each log as entry (entry.n)}\n <li>\n <span class=\"tr703-method\" data-method={entry.method}>{entry.method}</span>\n <span class=\"tr703-path\">{entry.path}</span>\n <span class=\"tr703-muted\">{entry.note}</span>\n </li>\n {/each}\n </ol>\n</section>\n\n<SvModal open={dialog != null} onClose={() => (dialog = null)} title={dialog?.title ?? ''} width={480}>\n {#if dialog?.kind === 'issue'}\n <div class=\"tr703-form\">\n <label class=\"tr703-field\">\n <span>What is wrong with this environment</span>\n <SvTextInput value={form.title} onChange={(v) => (form.title = v)} placeholder=\"Fan runs at full speed after resume\" ariaLabel=\"Issue\" block autofocus />\n </label>\n <label class=\"tr703-field\">\n <span>Bug reference</span>\n <SvTextInput value={form.bug} onChange={(v) => (form.bug = v)} placeholder=\"BUG-4130\" ariaLabel=\"Bug reference\" block />\n </label>\n </div>\n {:else if dialog?.kind === 'result'}\n <div class=\"tr703-form\">\n {#if testOptions.length}\n <div class=\"tr703-field\">\n <span>Test</span>\n <SvDropDownList options={testOptions} value={form.test} onChange={(v) => (form.test = String(v))} ariaLabel=\"Test\" block />\n </div>\n <div class=\"tr703-field\">\n <span>Outcome</span>\n <SvSegmented options={outcomeOptions} value={form.outcome} onChange={(v) => (form.outcome = OUTCOMES.find((o) => o === v) ?? 'passed')} />\n </div>\n <label class=\"tr703-field\">\n <span>Comment</span>\n <SvTextArea value={form.comment} onChange={(v) => (form.comment = v)} rows={3} placeholder=\"What the tester saw\" ariaLabel=\"Comment\" block />\n </label>\n {:else}\n <p class=\"tr703-muted\">Every test in this plan already has a result in this run.</p>\n {/if}\n </div>\n {/if}\n {#snippet footer()}\n <SvButton variant=\"ghost\" onclick={() => (dialog = null)}>Cancel</SvButton>\n <SvButton variant=\"primary\" disabled={!canSave} loading={saving} onclick={save}>Save</SvButton>\n {/snippet}\n</SvModal>\n\n<style>\n .tr703 { min-height: 0; }\n\n .tr703-head {\n display: flex;\n flex-wrap: wrap;\n align-items: baseline;\n justify-content: space-between;\n gap: 8px 16px;\n flex-shrink: 0;\n }\n .tr703-artefact { display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 600; color: var(--sg-fg); }\n .tr703-facts { display: flex; flex-wrap: wrap; gap: 4px 16px; font-size: 12.5px; color: var(--sg-muted); }\n .tr703-facts strong { color: var(--sg-fg); font-variant-numeric: tabular-nums; }\n\n .tr703-toolbar {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 8px;\n min-height: 32px;\n flex-shrink: 0;\n font-size: 12.5px;\n }\n .tr703-spacer { flex: 1; }\n\n .tr703-grid {\n border: 1px solid var(--sg-border);\n border-radius: 8px;\n overflow: hidden;\n }\n\n .tr703-log {\n list-style: none;\n margin: 0;\n padding: 8px 10px;\n border: 1px solid var(--sg-border);\n border-radius: 8px;\n background: var(--sg-header-bg);\n font-size: 11.5px;\n flex-shrink: 0;\n display: grid;\n gap: 2px;\n }\n .tr703-log li { display: flex; gap: 8px; min-width: 0; white-space: nowrap; }\n .tr703-path {\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n color: var(--sg-fg);\n overflow: hidden;\n text-overflow: ellipsis;\n min-width: 0;\n }\n .tr703-method {\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n font-weight: 600;\n width: 44px;\n flex-shrink: 0;\n color: var(--sg-muted);\n }\n .tr703-method[data-method='POST'], .tr703-method[data-method='PATCH'] { color: var(--sg-accent); }\n\n .tr703-form { display: grid; gap: 14px; }\n .tr703-field { display: grid; gap: 6px; font-size: 12.5px; color: var(--sg-muted); }\n\n /* Cells render inside the grid, so their rules are global. */\n :global(.tr703-name) {\n display: inline-flex;\n align-items: center;\n gap: 7px;\n min-width: 0;\n }\n :global(.tr703-name[data-kind='env'] .tr703-label) { font-weight: 600; }\n :global(.tr703-label) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n :global(.tr703-mono) { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; }\n :global(.tr703-check) { width: 14px; height: 14px; margin: 0; accent-color: var(--sg-accent); flex-shrink: 0; }\n :global(.tr703-reload) {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 20px;\n height: 20px;\n padding: 0;\n border: 0;\n border-radius: 4px;\n background: transparent;\n color: var(--sg-muted);\n cursor: pointer;\n flex-shrink: 0;\n }\n :global(.tr703-reload:hover) { background: var(--sg-header-bg); color: var(--sg-fg); }\n :global(.tr703-reload:focus-visible) { outline: 2px solid var(--sg-focus-ring, var(--sg-accent)); outline-offset: 1px; }\n :global(.tr703-reload:disabled) { cursor: default; }\n :global(.tr703-spin svg) { animation: tr703-spin 0.8s linear infinite; }\n @keyframes -global-tr703-spin { to { transform: rotate(360deg); } }\n :global(.tr703-arch) {\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n font-size: 11.5px;\n font-weight: 600;\n color: var(--sg-fg);\n }\n :global(.tr703-glyph) { display: inline-flex; flex-shrink: 0; }\n :global(.tr703-glyph[data-outcome='failed']) { color: var(--sg-danger, #dc2626); }\n :global(.tr703-glyph[data-outcome='passed']) { color: var(--sg-success, #16a34a); }\n :global(.tr703-glyph[data-outcome='skipped']) { color: var(--sg-muted); }\n :global(.tr703-new) {\n font-size: 10px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n padding: 0 6px;\n border-radius: 999px;\n color: var(--sg-accent);\n border: 1px solid currentColor;\n flex-shrink: 0;\n }\n\n :global(.tr703-pill) {\n display: inline-block;\n padding: 1px 10px;\n border-radius: 999px;\n font-size: 11.5px;\n border: 1px solid var(--sg-border);\n color: var(--sg-muted);\n white-space: nowrap;\n }\n :global(.tr703-pill[data-tone='approved']),\n :global(.tr703-pill[data-tone='passed']) {\n color: var(--sg-success, #16a34a);\n border-color: color-mix(in srgb, var(--sg-success, #16a34a) 45%, transparent);\n }\n :global(.tr703-pill[data-tone='rejected']),\n :global(.tr703-pill[data-tone='failed']) {\n color: var(--sg-danger, #dc2626);\n border-color: color-mix(in srgb, var(--sg-danger, #dc2626) 45%, transparent);\n }\n :global(.tr703-pill[data-tone='done']) { color: var(--sg-fg); }\n :global(.tr703-tag) {\n font-size: 11px;\n padding: 0 7px;\n border-radius: 4px;\n background: var(--sg-header-bg);\n color: var(--sg-muted);\n font-weight: 500;\n }\n :global(.tr703-progress) { display: inline-flex; align-items: center; gap: 8px; width: 100%; }\n :global(.tr703-bar) {\n flex: 1;\n max-width: 80px;\n height: 5px;\n border-radius: 999px;\n background: var(--sg-border);\n overflow: hidden;\n }\n :global(.tr703-bar > span) { display: block; height: 100%; background: var(--sg-accent); transition: width 300ms ease; }\n :global(.tr703-num) { font-variant-numeric: tabular-nums; font-size: 12px; color: var(--sg-fg); }\n\n :global(.tr703-detail) { display: inline-flex; gap: 10px; min-width: 0; }\n :global(.tr703-muted) { color: var(--sg-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n :global(.tr703-bug) { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; color: var(--sg-fg); }\n :global(.tr703-ago) { font-size: 12px; color: var(--sg-muted); font-variant-numeric: tabular-nums; }\n :global(.tr703-behind) { color: var(--sg-warning, #b45309); }\n\n :global(.tr703-actions) { display: flex; justify-content: flex-end; gap: 12px; width: 100%; padding-right: 10px; }\n :global(.tr703-link) {\n border: 0;\n padding: 0;\n background: transparent;\n color: var(--sg-accent);\n font-size: 12.5px;\n cursor: pointer;\n }\n :global(.tr703-link:hover) { text-decoration: underline; }\n :global(.tr703-link:focus-visible) { outline: 2px solid var(--sg-focus-ring, var(--sg-accent)); outline-offset: 2px; border-radius: 2px; }\n</style>\n"
4073
+ },
4066
4074
  {
4067
4075
  "id": "704-agent-review-desk",
4068
4076
  "path": "examples/src/demos/704-agent-review-desk.svelte",
@@ -4373,7 +4381,7 @@ export const docs = [
4373
4381
  "path": "docs/brand/social/README.md",
4374
4382
  "title": "GitHub social preview images",
4375
4383
  "section": "Brand",
4376
- "markdown": "# GitHub social preview images\n\nOn-brand 1280x640 cards for GitHub's repo **Social preview** (Settings ->\nGeneral -> Social preview). All are PNG, 1280x640 (GitHub's recommended size),\nand well under the 1 MB upload limit.\n\n| File | Use |\n| --- | --- |\n| `svgrid-github-social.png` | Primary. Headline lockup: \"The Svelte 5 data grid. / Headless-first. Render-ready.\" |\n| `svgrid-github-social-product.png` | Product card: headline + a mini-grid showing an accent-highlighted cell. |\n| `svgrid-github-social-centered.png` | Centered, minimal: mark + wordmark + tagline. |\n\n## Apply on GitHub\n\n1. Repo -> **Settings** -> **General**.\n2. Scroll to **Social preview** -> **Edit** -> upload one of the PNGs above.\n\n(The image lives in GitHub's settings, not in code - it is not auto-read from\nthe repo. These files are kept here as the source of truth + for reuse on other\nsocial cards.)\n\n## Regenerate\n\n```bash\nnode tools/render-social-preview.mjs\n```\n\nRenders all three via Chromium (Playwright) at 1280x640. Brand tokens (dark\nnavy gradient, the 4-tile mark, the Svelte orange->red accent) are lifted from\n`website/public/og-image.svg`; edit the variant markup in the script to tweak\ncopy or layout. Inter is pulled from Google Fonts when online and falls back to\nthe system sans otherwise.\n"
4384
+ "markdown": "# GitHub social preview images\n\nOn-brand 1280x640 cards for GitHub's repo **Social preview** (Settings ->\nGeneral -> Social preview). All are PNG, 1280x640 (GitHub's recommended size),\nand well under the 1 MB upload limit.\n\n| File | Use |\n| --- | --- |\n| `svgrid-github-social.png` | Primary. Headline lockup: \"The Svelte 5 data grid. / Headless-first. Render-ready.\" |\n| `svgrid-github-social-product.png` | Product card: headline + a mini-grid showing an accent-highlighted cell. |\n| `svgrid-github-social-centered.png` | Centered, minimal: mark + wordmark + tagline. |\n\n## Apply on GitHub\n\n1. Repo -> **Settings** -> **General**.\n2. Scroll to **Social preview** -> **Edit** -> upload one of the PNGs above.\n\n(The image lives in GitHub's settings, not in code - it is not auto-read from\nthe repo. The PNGs are gitignored; render them with the script below.)\n\n## Regenerate\n\n```bash\nnode tools/render-social-preview.mjs\n```\n\nRenders all three via Chromium (Playwright) at 1280x640. Brand tokens (dark\nnavy gradient, the 4-tile mark, the Svelte orange->red accent) are lifted from\n`website/public/og-image.svg`; edit the variant markup in the script to tweak\ncopy or layout. Inter is pulled from Google Fonts when online and falls back to\nthe system sans otherwise.\n"
4377
4385
  },
4378
4386
  {
4379
4387
  "slug": "changelog",
@@ -5024,7 +5032,7 @@ export const docs = [
5024
5032
  "path": "docs/help/base/templates.md",
5025
5033
  "title": "Ready-to-use bases",
5026
5034
  "section": "SvGrid Base",
5027
- "markdown": "# Ready-to-use bases\n\nEach base below is one `<SvBase>` with sample data: the fields, the saved\nviews and the forms a team would set up on day one. Open the source of any of\nthem, replace the sample rows with your own, and it is your app's tool.\n\nAll of them share the same parts, so what works in one works in all: the table\ntabs (where a base has more than one table), the view bar (Hide fields, Filter, Group, Sort, Color, Row height, search), the\nexpanded record with its changes and comments, Space on a row to open it,\n\"+ Add row\", the field editor, the selection bar for editing or deleting many\nrows at once, and dragging the pinned columns' edge.\n\n## Project tracker\n\nTwo tables, Tasks and Milestones. Tasks have a status, tags, an assignee,\ndates, an estimate, progress, a budget, files and a milestone; each milestone\nlists its tasks with their average progress and their budget. The\n[tutorial](./start.md) builds the task table step by step.\n\n## Content calendar\n\n<div data-docs-demo=\"511-base-content-calendar\" data-height=\"640\"></div>\n\nTwo tables, Posts and Campaigns. A post has a stage, channels, an author, a\npublish date, a cover image, a word count, a brief and its campaign; a\ncampaign lists its posts and adds up their words.\n\n- **Content plan:** the posts in publishing order, colored by stage, word\n counts summed in the footer.\n- **Pipeline:** a Kanban by stage; dragging a card moves the post along.\n- **Publishing calendar:** posts on their publish date; drag one to another\n day, or pick an empty day to schedule a new one.\n- **Covers:** a gallery of the cover images.\n- **Pitch an idea:** a form with the title, channels, author and brief.\n\n## Sales CRM\n\n<div data-docs-demo=\"512-base-sales-crm\" data-height=\"640\"></div>\n\nThree tables: Deals, Accounts and Contacts. A deal links to an account and a\ncontact and has a stage, an owner, a value, a probability, a close date, the\nnext step, a source and a priority. An account lists its deals and contacts\nand rolls up its pipeline value; a contact lists its deals.\n\n- **All deals:** biggest first, colored by stage; the footer sums the value\n and averages the probability.\n- **Pipeline:** a Kanban by stage.\n- **Closing calendar:** deals on their close date.\n- **Open deals by owner:** grouped by owner, Won and Lost filtered out; each\n group shows its own totals.\n- **New lead:** a form that starts a deal in the Lead stage.\n\nLinking a deal to an account lists it on the account, and the other way\nround. Hover a chip to preview the account, click it to open it (\"Open in\nAccounts\" goes there), and create a new account from the link picker.\n\n## Product roadmap\n\n<div data-docs-demo=\"513-base-product-roadmap\" data-height=\"640\"></div>\n\nTwo tables, Features and Feedback. A feature has a quarter, a status, teams,\na lead, impact, effort in days, start and target dates, customer votes and a\nspec link; each customer request links to the feature it is about, and the\nfeature counts them.\n\n- **Roadmap by quarter:** grouped by quarter, highest impact first, each\n group with its effort and votes; \"+\" in a group adds a feature to that\n quarter.\n- **Status board:** a Kanban by status.\n- **Timeline:** each feature from its start to its target date.\n- **Now:** in progress, in beta or blocked, by target date.\n- **Request a feature:** a form for anyone in the company.\n\n## Hiring tracker\n\n<div data-docs-demo=\"514-base-hiring-tracker\" data-height=\"640\"></div>\n\nTwo tables, Candidates and Roles. A candidate has a photo, a role, a stage, a\nrecruiter, a rating, the interview date, the salary ask, an email, a resume,\nthe source and notes; a role has its team, hiring manager and headcount, and\nlists its candidates.\n\n- **Hiring pipeline:** a Kanban by stage.\n- **All candidates:** best rated first, colored by stage.\n- **Faces:** a gallery of the photos.\n- **Interviews:** a calendar of interview dates.\n- **Apply:** the form a candidate fills in, with their resume.\n\n## Inventory\n\n<div data-docs-demo=\"515-base-inventory\" data-height=\"640\"></div>\n\nTwo tables, Items and Suppliers. An item has photos, a category, a location,\na supplier, the quantity, the unit cost, the stock value (a formula,\n`{Qty} * {Unit cost}`), the condition, who has it checked out, when it was\nlast counted and a barcode; a supplier lists its items and the units in\nstock.\n\n- **Stock by category:** grouped by category, the footer and each group\n summing quantity and value.\n- **Photos:** a gallery.\n- **By location:** a Kanban by location; dragging an item moves it.\n- **Reorder:** three or fewer in stock, red at zero and amber below four.\n- **Add an item:** a form.\n\n## Bug tracker\n\n<div data-docs-demo=\"520-base-bug-tracker\" data-height=\"640\"></div>\n\nTwo tables, Bugs and Releases. A bug has a severity, a status, the areas it\ntouches, who reported it and who is on it, the release it ships in, the\nsteps to reproduce, and when it was reported and fixed. A release lists its\nbugs and counts them.\n\n![Bug tracker: Bugs with Release, a link to one; Releases with Bugs, the field that links back.](/docs-media/base-template-bug-tracker.svg)\n\n- **Triage:** grouped by status, colored by severity.\n- **Board:** a Kanban by status.\n- **Critical now:** critical bugs that are not fixed.\n- **Bugs by area:** a bar chart.\n- **Report a bug:** the form anyone can fill in.\n\nAutomations: a critical bug that is not fixed turns red and raises a notice;\nsetting Status to Fixed stamps \"Fixed on\"; a bug from the form starts as\nNew; **Start** in the Fix column moves a bug to In progress.\n\n## Event planning\n\n<div data-docs-demo=\"521-base-event-planning\" data-height=\"640\"></div>\n\nThree tables: Events, Attendees and Checklist. An event has a date, a venue,\na status, an owner, a budget and a capacity; it counts who registered and\nworks out the seats left (`{Capacity} - {Registered}`). Attendees have a\nticket type and check in on the day; checklist items have a team and a due\ndate.\n\n![Event planning: Attendees link to one event; Events list attendees and checklist items; Checklist items link to one event.](/docs-media/base-template-event-planning.svg)\n\n- **Calendar:** events on their date, colored by status.\n- **Planning board:** a Kanban by status.\n- **Guest list:** attendees grouped by event.\n- **Tickets by type:** a donut.\n- **RSVP:** the form a guest fills in.\n\nAutomations: an event that turns Confirmed gets its checklist (three items\ncreated in Checklist and linked back to it); an event with no seats left\nturns red and raises a notice, also when the last seat goes from the\nAttendees table; a guest who RSVPs is told they are in.\n\n## OKRs\n\n<div data-docs-demo=\"522-base-okrs\" data-height=\"640\"></div>\n\nTwo tables, Key results and Objectives. A key result measures something from\na start value to a target; its progress is a formula,\n`MAX(0, MIN(1, ({Current} - {Start}) / ({Target} - {Start})))`, and its\nconfidence says whether it will get there. An objective has a quarter and an\nowner, and averages the progress of its key results with a rollup.\n\n![OKRs: Key results link to one objective; Objectives list their key results and average their progress.](/docs-media/base-template-okrs.svg)\n\n- **By objective:** key results grouped by objective, colored by confidence.\n- **Confidence:** a Kanban.\n- **Weekly check-in:** the numbers to update, least recently checked first.\n- **Progress by objective:** a bar chart of the rollup.\n\nAutomations: a key result that falls Off track turns red and raises a\nnotice; one that reaches its target is marked Achieved.\n\n## Expense approvals\n\n<div data-docs-demo=\"523-base-expenses\" data-height=\"640\"></div>\n\nTwo tables, Expenses and Budgets. An expense has an amount, a category, a\ndate, who spent it, a receipt, a status from Draft to Paid, and who approved\nit and when. A budget category lists its expenses, adds up what was spent\n(a rollup) and shows what is left (a formula over the rollup).\n\n![Expense approvals: Expenses link to one category; Budgets list their expenses, sum them, and work out what is left.](/docs-media/base-template-expenses.svg)\n\n- **This month:** newest first, colored by status, totals in the footer.\n- **Approvals:** a Kanban by status.\n- **Spend by category:** a pie of the amounts.\n- **Receipts:** a gallery.\n- **Submit an expense:** the form.\n\nAutomations: an expense over $1,000 goes to Needs approval; **Approve** in\nthe Review column approves it and records who and when; a rejected expense\nturns red; one sent with the form starts as Submitted; a category over its\nbudget raises a notice.\n\n## Employee onboarding\n\n<div data-docs-demo=\"524-base-onboarding\" data-height=\"640\"></div>\n\nThree tables: People, Checklist and Departments. A person has a photo, a\nrole, a department, a manager, a start date and a status; checklist items\nhave an owner (IT, HR or the manager) and a due date; departments list their\npeople and count them.\n\n![Employee onboarding: Checklist items link to one person; People link to one department and list their checklist; Departments list their people.](/docs-media/base-template-onboarding.svg)\n\n- **Pipeline:** a Kanban by status.\n- **Photo directory:** a gallery.\n- **Start dates:** a calendar.\n- **By department:** grouped by department.\n- **Add a new hire:** the form.\n\nAutomations: a new hire, from \"+ Add row\" or the form, gets a checklist:\nthree items for IT, HR and their manager, created in Checklist and linked\nback. Someone starting within a week has their start date colored, and\n**Activate** in the Ready column marks them Active.\n\n## Start from your own database\n\nEvery template here is also a database. `npm create @svgrid@latest my-base\n-- -t base` offers each one by name and writes it as SQL to `db/schema.sql`,\nwith its records, views and automations, on Postgres in the browser, your\nown Postgres or Supabase ([From a database to an app](./quick-start.md)):\n\n```bash\nnpm create @svgrid@latest my-base -- -t base --data supabase --sample bug-tracker\n```\n\nThe names: `project-tracker`, `sales-crm`, `content-calendar`,\n`product-roadmap`, `hiring-tracker`, `inventory`, `bug-tracker`,\n`event-planning`, `okrs`, `expenses`, `onboarding`. A base you changed\nhere goes the same way: \"All tables\", then **Download as SQL**.\n"
5035
+ "markdown": "# Ready-to-use bases\n\nEach base below is one `<SvBase>` with sample data: the fields, the saved\nviews and the forms a team would set up on day one. Open the source of any of\nthem, replace the sample rows with your own, and it is your app's tool.\n\nTo try one with nothing installed, open it full screen at\n[svgrid.com/base](https://svgrid.com/base); the bar at the top switches between\nthem.\n\nAll of them share the same parts, so what works in one works in all: the table\ntabs (where a base has more than one table), the view bar (Hide fields, Filter, Group, Sort, Color, Row height, search), the\nexpanded record with its changes and comments, Space on a row to open it,\n\"+ Add row\", the field editor, the selection bar for editing or deleting many\nrows at once, and dragging the pinned columns' edge.\n\n## Project tracker\n\nTwo tables, Tasks and Milestones. Tasks have a status, tags, an assignee,\ndates, an estimate, progress, a budget, files and a milestone; each milestone\nlists its tasks with their average progress and their budget. The\n[tutorial](./start.md) builds the task table step by step.\n\n## Content calendar\n\n<div data-docs-demo=\"511-base-content-calendar\" data-height=\"640\"></div>\n\nTwo tables, Posts and Campaigns. A post has a stage, channels, an author, a\npublish date, a cover image, a word count, a brief and its campaign; a\ncampaign lists its posts and adds up their words.\n\n- **Content plan:** the posts in publishing order, colored by stage, word\n counts summed in the footer.\n- **Pipeline:** a Kanban by stage; dragging a card moves the post along.\n- **Publishing calendar:** posts on their publish date; drag one to another\n day, or pick an empty day to schedule a new one.\n- **Covers:** a gallery of the cover images.\n- **Pitch an idea:** a form with the title, channels, author and brief.\n\n## Sales CRM\n\n<div data-docs-demo=\"512-base-sales-crm\" data-height=\"640\"></div>\n\nThree tables: Deals, Accounts and Contacts. A deal links to an account and a\ncontact and has a stage, an owner, a value, a probability, a close date, the\nnext step, a source and a priority. An account lists its deals and contacts\nand rolls up its pipeline value; a contact lists its deals.\n\n- **All deals:** biggest first, colored by stage; the footer sums the value\n and averages the probability.\n- **Pipeline:** a Kanban by stage.\n- **Closing calendar:** deals on their close date.\n- **Open deals by owner:** grouped by owner, Won and Lost filtered out; each\n group shows its own totals.\n- **New lead:** a form that starts a deal in the Lead stage.\n\nLinking a deal to an account lists it on the account, and the other way\nround. Hover a chip to preview the account, click it to open it (\"Open in\nAccounts\" goes there), and create a new account from the link picker.\n\n## Product roadmap\n\n<div data-docs-demo=\"513-base-product-roadmap\" data-height=\"640\"></div>\n\nTwo tables, Features and Feedback. A feature has a quarter, a status, teams,\na lead, impact, effort in days, start and target dates, customer votes and a\nspec link; each customer request links to the feature it is about, and the\nfeature counts them.\n\n- **Roadmap by quarter:** grouped by quarter, highest impact first, each\n group with its effort and votes; \"+\" in a group adds a feature to that\n quarter.\n- **Status board:** a Kanban by status.\n- **Timeline:** each feature from its start to its target date.\n- **Now:** in progress, in beta or blocked, by target date.\n- **Request a feature:** a form for anyone in the company.\n\n## Hiring tracker\n\n<div data-docs-demo=\"514-base-hiring-tracker\" data-height=\"640\"></div>\n\nTwo tables, Candidates and Roles. A candidate has a photo, a role, a stage, a\nrecruiter, a rating, the interview date, the salary ask, an email, a resume,\nthe source and notes; a role has its team, hiring manager and headcount, and\nlists its candidates.\n\n- **Hiring pipeline:** a Kanban by stage.\n- **All candidates:** best rated first, colored by stage.\n- **Faces:** a gallery of the photos.\n- **Interviews:** a calendar of interview dates.\n- **Apply:** the form a candidate fills in, with their resume.\n\n## Inventory\n\n<div data-docs-demo=\"515-base-inventory\" data-height=\"640\"></div>\n\nTwo tables, Items and Suppliers. An item has photos, a category, a location,\na supplier, the quantity, the unit cost, the stock value (a formula,\n`{Qty} * {Unit cost}`), the condition, who has it checked out, when it was\nlast counted and a barcode; a supplier lists its items and the units in\nstock.\n\n- **Stock by category:** grouped by category, the footer and each group\n summing quantity and value.\n- **Photos:** a gallery.\n- **By location:** a Kanban by location; dragging an item moves it.\n- **Reorder:** three or fewer in stock, red at zero and amber below four.\n- **Add an item:** a form.\n\n## Bug tracker\n\n<div data-docs-demo=\"520-base-bug-tracker\" data-height=\"640\"></div>\n\nTwo tables, Bugs and Releases. A bug has a severity, a status, the areas it\ntouches, who reported it and who is on it, the release it ships in, the\nsteps to reproduce, and when it was reported and fixed. A release lists its\nbugs and counts them.\n\n![Bug tracker: Bugs with Release, a link to one; Releases with Bugs, the field that links back.](/docs-media/base-template-bug-tracker.svg)\n\n- **Triage:** grouped by status, colored by severity.\n- **Board:** a Kanban by status.\n- **Critical now:** critical bugs that are not fixed.\n- **Bugs by area:** a bar chart.\n- **Report a bug:** the form anyone can fill in.\n\nAutomations: a critical bug that is not fixed turns red and raises a notice;\nsetting Status to Fixed stamps \"Fixed on\"; a bug from the form starts as\nNew; **Start** in the Fix column moves a bug to In progress.\n\n## Event planning\n\n<div data-docs-demo=\"521-base-event-planning\" data-height=\"640\"></div>\n\nThree tables: Events, Attendees and Checklist. An event has a date, a venue,\na status, an owner, a budget and a capacity; it counts who registered and\nworks out the seats left (`{Capacity} - {Registered}`). Attendees have a\nticket type and check in on the day; checklist items have a team and a due\ndate.\n\n![Event planning: Attendees link to one event; Events list attendees and checklist items; Checklist items link to one event.](/docs-media/base-template-event-planning.svg)\n\n- **Calendar:** events on their date, colored by status.\n- **Planning board:** a Kanban by status.\n- **Guest list:** attendees grouped by event.\n- **Tickets by type:** a donut.\n- **RSVP:** the form a guest fills in.\n\nAutomations: an event that turns Confirmed gets its checklist (three items\ncreated in Checklist and linked back to it); an event with no seats left\nturns red and raises a notice, also when the last seat goes from the\nAttendees table; a guest who RSVPs is told they are in.\n\n## OKRs\n\n<div data-docs-demo=\"522-base-okrs\" data-height=\"640\"></div>\n\nTwo tables, Key results and Objectives. A key result measures something from\na start value to a target; its progress is a formula,\n`MAX(0, MIN(1, ({Current} - {Start}) / ({Target} - {Start})))`, and its\nconfidence says whether it will get there. An objective has a quarter and an\nowner, and averages the progress of its key results with a rollup.\n\n![OKRs: Key results link to one objective; Objectives list their key results and average their progress.](/docs-media/base-template-okrs.svg)\n\n- **By objective:** key results grouped by objective, colored by confidence.\n- **Confidence:** a Kanban.\n- **Weekly check-in:** the numbers to update, least recently checked first.\n- **Progress by objective:** a bar chart of the rollup.\n\nAutomations: a key result that falls Off track turns red and raises a\nnotice; one that reaches its target is marked Achieved.\n\n## Expense approvals\n\n<div data-docs-demo=\"523-base-expenses\" data-height=\"640\"></div>\n\nTwo tables, Expenses and Budgets. An expense has an amount, a category, a\ndate, who spent it, a receipt, a status from Draft to Paid, and who approved\nit and when. A budget category lists its expenses, adds up what was spent\n(a rollup) and shows what is left (a formula over the rollup).\n\n![Expense approvals: Expenses link to one category; Budgets list their expenses, sum them, and work out what is left.](/docs-media/base-template-expenses.svg)\n\n- **This month:** newest first, colored by status, totals in the footer.\n- **Approvals:** a Kanban by status.\n- **Spend by category:** a pie of the amounts.\n- **Receipts:** a gallery.\n- **Submit an expense:** the form.\n\nAutomations: an expense over $1,000 goes to Needs approval; **Approve** in\nthe Review column approves it and records who and when; a rejected expense\nturns red; one sent with the form starts as Submitted; a category over its\nbudget raises a notice.\n\n## Employee onboarding\n\n<div data-docs-demo=\"524-base-onboarding\" data-height=\"640\"></div>\n\nThree tables: People, Checklist and Departments. A person has a photo, a\nrole, a department, a manager, a start date and a status; checklist items\nhave an owner (IT, HR or the manager) and a due date; departments list their\npeople and count them.\n\n![Employee onboarding: Checklist items link to one person; People link to one department and list their checklist; Departments list their people.](/docs-media/base-template-onboarding.svg)\n\n- **Pipeline:** a Kanban by status.\n- **Photo directory:** a gallery.\n- **Start dates:** a calendar.\n- **By department:** grouped by department.\n- **Add a new hire:** the form.\n\nAutomations: a new hire, from \"+ Add row\" or the form, gets a checklist:\nthree items for IT, HR and their manager, created in Checklist and linked\nback. Someone starting within a week has their start date colored, and\n**Activate** in the Ready column marks them Active.\n\n## Start from your own database\n\nEvery template here is also a database. `npm create @svgrid@latest my-base\n-- -t base` offers each one by name and writes it as SQL to `db/schema.sql`,\nwith its records, views and automations, on Postgres in the browser, your\nown Postgres or Supabase ([From a database to an app](./quick-start.md)):\n\n```bash\nnpm create @svgrid@latest my-base -- -t base --data supabase --sample bug-tracker\n```\n\nThe names: `project-tracker`, `sales-crm`, `content-calendar`,\n`product-roadmap`, `hiring-tracker`, `inventory`, `bug-tracker`,\n`event-planning`, `okrs`, `expenses`, `onboarding`. A base you changed\nhere goes the same way: \"All tables\", then **Download as SQL**.\n"
5028
5036
  },
5029
5037
  {
5030
5038
  "slug": "help/base/views",
@@ -5689,7 +5697,7 @@ export const docs = [
5689
5697
  "path": "docs/help/mcp-server.md",
5690
5698
  "title": "MCP server",
5691
5699
  "section": "Help",
5692
- "markdown": "# MCP server\n\nThe SvGrid MCP server does two things for an AI client (Claude Code,\nClaude Desktop, Cursor, Zed, Codex, custom agents): it answers questions\nabout SvGrid from the files this repository ships, and it **checks the\ncode the model writes** against the real exported surface of the version\nyou have installed. No API key either way.\n\n![An AI coding agent calls the @svgrid/mcp server over the Model Context Protocol, which runs grid tools and returns structured JSON results back to the agent.](/docs-media/grid-mcp.svg)\n\n> **What is MCP?** Model Context Protocol is the open standard\n> ([modelcontextprotocol.io](https://modelcontextprotocol.io)) for\n> exposing tools to LLM clients. SvGrid ships an MCP server so the\n> model your team already uses can \"see\" the grid without you having\n> to copy-paste docs into prompts.\n\nIt runs either way you like: as a local process\n([`@svgrid/mcp`](https://www.npmjs.com/package/@svgrid/mcp) on npm), or as\na hosted endpoint at `https://mcp.svgrid.com/mcp` that needs no install at\nall. Both are listed in the official MCP registry as `com.svgrid/svgrid`.\n\n## Two ways to connect\n\n**Hosted (nothing to install).** Point any MCP client at the URL:\n\n```\nhttps://mcp.svgrid.com/mcp\n```\n\n```bash\nclaude mcp add --transport http svgrid https://mcp.svgrid.com/mcp\n```\n\nOne click:\n[Add to Cursor](https://cursor.com/en/install-mcp?name=svgrid&config=eyJ1cmwiOiJodHRwczovL21jcC5zdmdyaWQuY29tL21jcCJ9)\n· [Add to VS Code](https://insiders.vscode.dev/redirect/mcp/install?name=svgrid&config=%7B%22name%22%3A%22svgrid%22%2C%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fmcp.svgrid.com%2Fmcp%22%7D)\n\nIt carries seven tools - `search`, `fetch`, `list_examples`,\n`get_example_source`, `get_api_reference`, `check_svgrid_code` and\n`svgrid_preview` - and needs no Node, no config file, and no key.\n\n**Local (`npx @svgrid/mcp`).** Everything the hosted server has, plus\nthe Studio tools, the docs and demos as MCP resources, ready-made\nprompts, and a `svgrid_check_code` that additionally *compiles* the file\nwith the Svelte compiler rather than checking it statically. Use it when\nyou want the compile pass, the Studio tools, or no third-party endpoint\nin the loop.\n\n| | Hosted | Local |\n| --- | --- | --- |\n| Setup | a URL | `npx @svgrid/mcp` |\n| Needs Node | no | yes |\n| Code check compiles | no, static checks only | yes |\n| Resources and prompts | yes | yes |\n| Visual preview | yes | yes |\n| `studio_*` tools | no | yes, opt-in |\n| Works offline | no | yes |\n\n## Install\n\nNo install step is required - `npx` fetches it on demand:\n\n```bash\n# One-shot, from any project\nnpx -y @svgrid/mcp\n```\n\nTo pin it as a dev dependency instead:\n\n```bash\npnpm add -D @svgrid/mcp\n```\n\nThe local server is a Node binary (`svgrid-mcp`) that speaks MCP over\nstdio. There is no daemon to maintain. The hosted server needs no install\nstep at all - skip to [Wire it into your AI client](#wire-it-into-your-ai-client)\nand use the URL.\n\n## Wire it into your AI client\n\nEvery snippet below shows the local (stdio) form and the hosted (HTTP)\nform. Pick one - running both connects the same tools twice.\n\n### Claude Code\n\nThe plugin is the shortest path: it installs the\n[Agent Skill](./skill.md) and the hosted server together, so the model\ngets the house style *and* the checker in one step.\n\n```\n/plugin marketplace add sv-grid/sv-grid\n/plugin install svgrid@svgrid\n```\n\nOr add the server on its own:\n\n```bash\n# hosted, nothing to install\nclaude mcp add --transport http svgrid https://mcp.svgrid.com/mcp\n\n# or local\nclaude mcp add svgrid -- npx -y @svgrid/mcp\n```\n\nThen run `/mcp` in a session and you will see `svgrid` listed.\n\nTo share the server with your team, add `--scope project`. That writes\na `.mcp.json` at the repository root which you can commit, so everyone\nwho clones the repo gets the same tooling with no per-machine setup:\n\n```bash\nclaude mcp add svgrid --scope project -- npx -y @svgrid/mcp\n```\n\n### Claude Desktop\n\nEdit `~/Library/Application Support/Claude/claude_desktop_config.json`\n(macOS) or `%APPDATA%\\Claude\\claude_desktop_config.json` (Windows):\n\n```json\n{\n \"mcpServers\": {\n \"svgrid\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@svgrid/mcp\"]\n }\n }\n}\n```\n\nOr the hosted server, with nothing to install:\n\n```json\n{\n \"mcpServers\": {\n \"svgrid\": {\n \"type\": \"http\",\n \"url\": \"https://mcp.svgrid.com/mcp\"\n }\n }\n}\n```\n\nRestart Claude Desktop, then ask *\"using svgrid, build me a grid that\ngroups by department\"* to confirm the tools are exposed.\n\n### Cursor\n\nOne click:\n[Add to Cursor](https://cursor.com/en/install-mcp?name=svgrid&config=eyJ1cmwiOiJodHRwczovL21jcC5zdmdyaWQuY29tL21jcCJ9)\n\nOr by hand, in `Settings -> MCP -> Add new MCP server`:\n\n```json\n{ \"url\": \"https://mcp.svgrid.com/mcp\" }\n```\n\n```json\n{ \"command\": \"npx\", \"args\": [\"-y\", \"@svgrid/mcp\"] }\n```\n\n### Zed\n\n`~/.config/zed/settings.json`:\n\n```json\n{\n \"context_servers\": {\n \"svgrid\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@svgrid/mcp\"],\n \"env\": {}\n }\n }\n}\n```\n\n### VS Code\n\nOne click:\n[Add to VS Code](https://insiders.vscode.dev/redirect/mcp/install?name=svgrid&config=%7B%22name%22%3A%22svgrid%22%2C%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fmcp.svgrid.com%2Fmcp%22%7D)\n\nOr create `.vscode/mcp.json` in the workspace. Note that VS Code uses\n`servers` rather than the `mcpServers` wrapper:\n\n```json\n{\n \"servers\": {\n \"svgrid\": {\n \"type\": \"http\",\n \"url\": \"https://mcp.svgrid.com/mcp\"\n }\n }\n}\n```\n\n```json\n{\n \"servers\": {\n \"svgrid\": {\n \"type\": \"stdio\",\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@svgrid/mcp\"]\n }\n }\n}\n```\n\n### Custom agents (OpenAI Agents SDK, Anthropic SDK, LangChain)\n\nPoint your client's MCP stdio transport at `npx -y @svgrid/mcp`, or its\nstreamable-HTTP transport at `https://mcp.svgrid.com/mcp`. Any client that\nspeaks either transport works.\n\nThe hosted server names its two retrieval tools `search` and `fetch`\nexactly, which is what a connector needs to index it.\n\n## Tools exposed\n\nFive, by default. `tools/list` is sent on **every** request, so the tool\nsurface is pure overhead on every turn - and this server used to spend\n~4,710 tokens of it on 36 tools, 79% of them Studio tools that most\nsessions never call once.\n\n| Tool | What it does |\n| ---- | ------------ |\n| `svgrid_search` | Search the docs, every demo and the API surface **in one call**. No arguments returns an index. |\n| `svgrid_get` | Read one thing in full: a doc slug, a demo id, or `api`. |\n| `svgrid_check_code` | Verify code against the real exported surface before the user sees it. |\n| `svgrid_preview` | Render a **live, interactive grid** in the conversation from columns + rows. |\n| `svgrid_scaffold` | Turn a Drizzle schema, sample rows or an EntitySchema into runnable SvelteKit files. |\n\nStudio adds four more, and only when you ask for them - set\n`SVGRID_MCP_STUDIO=1` or a licence key in the server's env. They need a\nlicence to be useful, so they are not charged to everyone else's context\nwindow.\n\n`svgrid_scaffold` and the Studio tools run on `@svgrid/enterprise`, which the\nserver loads only when it is installed beside it. `npx -y @svgrid/mcp` leaves\nit out so the server starts fast. To scaffold, install both in the project and\nrun the local server:\n\n```bash\nnpm i -D @svgrid/mcp @svgrid/enterprise\nclaude mcp add svgrid -- npx svgrid-mcp\n```\n\nWithout `-y`, `npx` runs the installed copy instead of downloading one, so\nthere is no install on the first connect.\n\nThe **hosted** server carries `search`, `fetch`, `list_examples`,\n`get_example_source`, `get_api_reference`, `check_svgrid_code` and\n`svgrid_preview`, plus the same resources and prompts. The first two are named\nthat way deliberately: those exact names are what a one-click connector needs to\nindex a remote server. It also answers to `svgrid_search`, `svgrid_get` and\n`svgrid_check_code`, so a model that learned the npm package's names is never\ntold \"unknown tool\".\n\nWhat it does **not** have is the compile pass (the Svelte compiler cannot run in\na Worker), the Studio tools (they need a filesystem), and the offline guarantee\n- it is a remote server, so by definition your query reaches it. Use the local\none when any of those matter.\n\n### Verification\n\n#### `svgrid_check_code`\n\nChecks a file **against the version you have installed** and returns\nline-numbered diagnostics with the exact replacement for each: unknown\n`<SvGrid>` props, wrong `ColumnDef` keys, api methods that do not\nexist, imports that will not resolve, and Svelte 5 runes mistakes. It\nalso compiles the component, so a syntax error surfaces here rather\nthan in the user's terminal.\n\nThis is the tool that makes the rest worth having. Retrieval alone\nstill lets a model write a confident, wrong grid; nothing else in the\nserver stops it. Run it on every file you write, fix what it reports,\nand run it again.\n\n### Finding and reading\n\n#### `svgrid_search`\n\nOne call across all three corpora, because \"how do I pin a column\" does\nnot announce whether it is answered by a doc page, a demo, or an API\nname:\n\n```json\n{ \"query\": \"pin a column\" }\n```\n\nReturns ranked doc hits with excerpts, matching demos, and matching API\nnames - each with the reference you pass to `svgrid_get`. Narrow with\n`kind` (`docs` | `examples` | `api`), trade tokens for completeness\nwith `detail` (`concise` | `full`), and cap with `limit` (max 50).\n\nCall it with **no arguments** for an index of doc sections, demo\ncategories and API groups - the cheapest way to orient before searching.\n\n#### `svgrid_get`\n\n```json\n{ \"ref\": \"help/columns/column-definitions\" }\n{ \"ref\": \"11-stock-market\" }\n{ \"ref\": \"api\" }\n```\n\nThe kind is inferred from the reference; pass `kind` to force it. A\nreference that does not resolve comes back with near matches rather\nthan a bare \"not found\".\n\n### It fixes what it finds\n\n`svgrid_check_code` does not stop at telling you what is wrong. Where the\ncorrection is exact it returns the corrected file too:\n\n```json\n{\n \"diagnostics\": [ ... ],\n \"applied\": [\"rowData -> data (line 7)\", \"accessorKey -> field (line 3)\"],\n \"fixed\": \"<the corrected source>\"\n}\n```\n\nBoth fields are omitted when there is nothing mechanically fixable, so a clean\ncheck stays small.\n\nThe rules are deliberately narrow, because this tool's whole worth is that it\nnever cries wolf - and rewriting raises the stakes from wasting a turn to\ncorrupting working code. Only exact renames are applied (a known rename, or a\nclose-enough spelling), only on word boundaries, and only on the line the\ndiagnostic reported. Advice that is ambiguous - \"this has no equivalent, remove\nit\" - stays advice. A test asserts that running auto-fix across every demo\nin this repository changes nothing at all.\n\n### It knows which version you have\n\nThe result carries the version it checked against:\n\n```json\n{ \"version\": { \"corpus\": \"3.0.0\", \"installed\": \"2.6.8\", \"warning\": \"...\" } }\n```\n\nThe server reads the `@svgrid/grid` in your project and says plainly when it\ndisagrees with the corpus it ships, so a model is told to hedge instead of\nconfidently citing an API you do not have. A server that answers from a remote\nbackend cannot do this - it has no idea what is in your `node_modules`.\n\n### Nothing leaves your machine\n\nThis server makes **no network calls**. Not for docs, not for the API surface,\nnot for verification - the whole corpus (every demo, every doc page, the full\nexported API) ships inside the package, which is why it is megabytes rather\nthan kilobytes. There is no API key, no licence check on the wire, and no telemetry.\n\nIt works on a plane, behind a corporate proxy, and inside an air-gapped\nnetwork. `tools/mcp-offline.test.ts` enforces it: the server is driven through\na full session with every network primitive booby-trapped, and the test fails if\nanything is even attempted.\n\nThe one honest exception: the **preview** loads the grid from a CDN to draw it.\nThat happens in your client's sandboxed iframe, never in this server, and only\nwhen you actually render a preview.\n\n### Seeing the grid, not just reading about it\n\n`svgrid_preview` renders a **real, interactive SvGrid inside the\nconversation** - sortable, filterable, scrollable. Not a screenshot and not a\nmock table: the same `<sv-grid>` custom element a page would use, loaded from\nthe CDN, with the columns and rows you passed.\n\n```json\n{\n \"title\": \"Team roster\",\n \"columns\": [{ \"field\": \"name\", \"header\": \"Name\" }, { \"field\": \"amount\", \"header\": \"Amount\" }],\n \"data\": [{ \"name\": \"Ada\", \"amount\": 20000 }],\n \"sortable\": true\n}\n```\n\nIt uses [MCP Apps](https://blog.modelcontextprotocol.io/posts/2026-01-26-mcp-apps/),\nthe official UI extension: the tool points at a `ui://` resource through\n`_meta`, the client loads that HTML in a sandboxed iframe, and the tool's\n`structuredContent` arrives over a postMessage bridge. Supported in Claude\n(web and desktop), VS Code and ChatGPT.\n\nClients without UI support are not left out - they ignore the `_meta` and get\na text summary of the same grid, so it is always safe to call. That is the\nextension's own rule, and it is why the text half describes the grid rather\nthan pointing at a picture the reader cannot see.\n\nPass `demo` instead of `columns` / `data` and you get the demo's source: a\ndemo is a Svelte component, not data, so there is nothing to hand the element\nand rendering an empty grid would just look broken.\n\n### Resources and prompts\n\nThe docs and demos are also exposed as **MCP resources**, so a user can\nattach a page or a demo directly instead of hoping the model thinks to\nsearch for it:\n\n```\nsvgrid://doc/help/columns/column-definitions\nsvgrid://example/11-stock-market\n```\n\nAnd three **prompts** ship ready to run: `build_grid`, `explain_api`\nand `review_grid_code`. Each is written to make the model use this\nserver rather than recall SvGrid from training data, and each ends at\n`svgrid_check_code`.\n\n### SvGrid Studio (commercial)\n\nOff unless enabled. Set `SVGRID_MCP_STUDIO=1`, or a valid\n`SVGRID_LICENSE_KEY`, in the server's env, and run the server from a project\nthat has `@svgrid/enterprise` installed beside it\n(`npm i -D @svgrid/mcp @svgrid/enterprise`, then `npx svgrid-mcp`). Without it\nthese tools answer with those steps instead of running.\n\n#### `svgrid_scaffold`\n\nPoint it at a Drizzle schema, sample JSON rows, or an `EntitySchema`\nyou already have, and it infers the schema and generates the `$lib`\nschema module, a `+server.ts` API route and a `+page.svelte` with\n`SvGrid` + `SvGridEditPanel` - in one call. Pass `schemaOnly: true` to\nstop after inference. Generated bodies carry `svgrid:managed` markers,\nso regenerating preserves your edits outside them.\n\n#### The `studio_*` tools\n\nFour tools drive the same validated project model the visual designer\nuses:\n\n| Tool | What it does |\n| ---- | ------------ |\n| `studio_project` | `new`, `load`, `describe`, `config`, `capabilities` |\n| `studio_apply` | A **batch** of model changes - entities, screens, blocks, components - applied in order |\n| `studio_configure` | Theme, auth, access, tenancy, data layer, jobs, deploy target, layouts, in one call |\n| `studio_build` | `validate`, then `generate` the full runnable SvelteKit app |\n\nCall `studio_project` with `action: \"capabilities\"` first: it reports\nexactly what the installed version supports, so the agent does not have\nto guess block kinds or component keys.\n\n`studio_apply` takes a batch on purpose. Building a five-screen app was\ntwenty-odd round trips when every block was its own tool; now a whole\nscreen is one call, and a failure reports which op failed and what\nalready applied.\n\n### The pre-3.0 names\n\nEvery tool name from before 3.0 still answers - `search_docs`,\n`get_doc`, `list_examples`, `get_example_source`, `list_docs`,\n`get_api_reference`, `check_svgrid_code`, `introspect_source`,\n`scaffold_entity` and all 27 individual `studio_*` tools. They are not\n**listed**, because listing is what costs context and answering a name\nyou did not advertise costs nothing. Saved prompts and scripts keep\nworking; nobody pays for the compatibility.\n\nTheir JSON response shape follows 3.0, not 2.x. A model reads either\nwithout trouble; a script that parsed the old shape by hand needs a look.\n\n## Licensing\n\nThe documentation and example tools are free. The Studio code\ngenerators are part of the commercial offering. You can evaluate them\nwithout a key: they run, but prepend a notice comment\nto generated files. To license them, set\nthe key in your MCP client's server config:\n\n```json\n{\n \"mcpServers\": {\n \"svgrid\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@svgrid/mcp\"],\n \"env\": { \"SVGRID_LICENSE_KEY\": \"YOUR-LICENSE-KEY\" }\n }\n }\n}\n```\n\n## Enterprise features and the trial\n\nMost of SvGrid is the MIT `@svgrid/grid` package. Export to Excel and PDF,\npivot tables, the Kanban board, the scheduler, the spreadsheet and the\nserver-side row model are in `@svgrid/enterprise`, which is commercial.\n\nThe server tells your assistant which is which. In `svgrid_search` results a\npaid doc or demo carries `\"enterprise\": true`, and when a question is about a\npaid feature the answer says so once, with the trial link.\n`svgrid_get` puts the same line at the top of a paid doc or demo, and\n`svgrid_check_code` adds it when the fix is to install the package. Nothing\nis sent anywhere to do this; it is part of the answer text.\n\n`@svgrid/enterprise` runs without a license key and shows a watermark until\none is set, so you can try a feature before deciding. The\n[30-day trial](https://svgrid.com/pricing/?trial=mcp-docs) adds a download of\nevery demo and 30 days of email support.\n\n## Verifying it works\n\nAsk your model: *\"What MCP tools do you have from svgrid?\"* The local\nserver lists five, including `svgrid_check_code` (four Studio tools more when\nenabled); the hosted server lists seven.\n\nThen give it something to catch:\n\n> Check this with svgrid: `<SvGrid rowData={rows} {columns} />`\n\nIt should come back with `rowData` is not a SvGrid prop, use `data`. If\nit explains the code instead of calling a tool, the server is not\nconnected.\n\nIf nothing is listed at all, check your client's MCP log. For the local\nserver the usual cause is `npx` not being on PATH - use the absolute path\nto the binary. For the hosted one, confirm the endpoint answers:\n\n```bash\ncurl https://mcp.svgrid.com/health\n```\n\n## Security model\n\nThe two ways of running it differ here, so pick deliberately.\n\n**Local (`npx @svgrid/mcp`)**\n\n- Runs on your machine over stdio. No telemetry, no outbound network\n calls, no API key.\n- Serves a documentation and example corpus bundled into the package at\n build time, so answers are pinned to the version you installed.\n- `svgrid_check_code` reads the source you pass it in-process and never\n sends it anywhere.\n\n**Hosted (`https://mcp.svgrid.com/mcp`)**\n\n- Your client sends tool arguments to a Cloudflare Worker we operate.\n Anything you pass to a tool leaves your machine, and for\n `check_svgrid_code` that means **the source you ask it to check**.\n- Each call is recorded: tool name, duration, whether it succeeded, the\n query or id it was given, how many pages matched, and whether the answer\n mentioned the Enterprise trial. For `check_svgrid_code` only the **byte\n length** of the submitted source and the names of the rules that fired\n are recorded, never the source itself. The records stay in Cloudflare\n (Workers logs, and an Analytics Engine dataset kept three months) and are\n read in aggregate to see what people ask for.\n- No account, no key, no cookies. Requests are not tied to a user.\n- If your code cannot leave the building, use the local server. That is\n what it is for.\n\n**Both**\n\n- The Studio tools return generated files as data. Writing them to disk\n is your client's decision, not the server's.\n- See [security](./security.md) for the general supply-chain posture.\n\n## Building your own MCP integrations\n\nThe same docs manifest, JSON Schemas (column definitions, the grid's\noptions, export options, and the chart spec at `schemas/chart-spec.json`,\nwhich `svgrid_get` also serves for \"chart spec schema\"), and `llms.txt`\nfiles are also served directly from the docs site:\n\n```ts\nconst docs = await fetch('https://svgrid.com/docs.json').then((r) => r.json())\nconst schemas = await fetch('https://svgrid.com/schemas/index.json').then((r) => r.json())\nconst llms = await fetch('https://svgrid.com/llms-full.txt').then((r) => r.text())\n```\n\nIf you do not want to run the MCP server, building these into your\nagent's system prompt gives most of the same grounding.\n\n## Frequently asked questions\n\n### What is the SvGrid MCP server?\n\nA Model Context Protocol server that lets AI clients (Claude Code, Claude\nDesktop, Cursor, Zed, custom agents) query SvGrid's documentation, read real\ndemo source, scaffold SvelteKit CRUD apps, and check the code they write\nagainst the real API - grounded in the files the package ships, so the model\nanswers from current facts instead of guessing.\n\n### Do I need an API key to run it?\n\nNo, on either transport. A `SVGRID_LICENSE_KEY` is optional and only affects\nthe commercial Studio code generators.\n\n### Local or hosted - which should I use?\n\nHosted (`https://mcp.svgrid.com/mcp`) if you want it working in one paste,\nwith no Node and no config file. Local (`npx @svgrid/mcp`) if you want the\nSvelte compiler pass in `svgrid_check_code`, the Studio tools, offline\nuse, or your source never leaving the machine. See\n[Security model](#security-model) for what each one sends.\n\n### How does it help AI assistants write better SvGrid code?\n\nTwo ways. It exposes the docs, example sources, and API reference as tools,\nso the assistant retrieves version-pinned answers instead of hallucinating an\nAPI from training data. And `svgrid_check_code` closes the loop: the model\nruns what it wrote past the real exported surface and gets told exactly what\nis wrong before you see it. That matters most for Svelte 5, where models\nroutinely mix in outdated Svelte 4 syntax.\n\n### Does it work with a version of SvGrid I have not upgraded to?\n\nThe local server answers for the version bundled in the `@svgrid/mcp` release\nyou install, so pin it alongside `@svgrid/grid` if you are behind. The hosted\nserver always tracks the current release. Either way, every\n`svgrid_check_code` result names the version it checked against in its\n`checkedAgainst` field.\n\n## See also\n\n- [Agent Skill](./skill.md) - the always-on house-style layer; the Claude Code plugin installs it together with this server\n- [LLM grounding](./llm-grounding.md) - the same files used by the MCP server, but documented for direct LLM consumption\n- [Agents](./agents.md) - how to build an AI agent that drives the live grid\n- [AI assistant](./ai.md) - the in-grid AI features (filter / smart-fill / classify / summarise), free in @svgrid/grid\n"
5700
+ "markdown": "# MCP server\n\nThe SvGrid MCP server does two things for an AI client (Claude Code,\nClaude Desktop, Cursor, Zed, Codex, custom agents): it answers questions\nabout SvGrid from the files this repository ships, and it **checks the\ncode the model writes** against the real exported surface of the version\nyou have installed. No API key either way.\n\n![An AI coding agent calls the @svgrid/mcp server over the Model Context Protocol, which runs grid tools and returns structured JSON results back to the agent.](/docs-media/grid-mcp.svg)\n\n> **What is MCP?** Model Context Protocol is the open standard\n> ([modelcontextprotocol.io](https://modelcontextprotocol.io)) for\n> exposing tools to LLM clients. SvGrid ships an MCP server so the\n> model your team already uses can \"see\" the grid without you having\n> to copy-paste docs into prompts.\n\nIt runs either way you like: as a local process\n([`@svgrid/mcp`](https://www.npmjs.com/package/@svgrid/mcp) on npm), or as\na hosted endpoint at `https://mcp.svgrid.com/mcp` that needs no install at\nall. Both are listed in the official MCP registry as `com.svgrid/svgrid`.\n\n## Two ways to connect\n\n**Hosted (nothing to install).** Point any MCP client at the URL:\n\n```\nhttps://mcp.svgrid.com/mcp\n```\n\n```bash\nclaude mcp add --transport http svgrid https://mcp.svgrid.com/mcp\n```\n\nOne click:\n[Add to Cursor](https://cursor.com/en/install-mcp?name=svgrid&config=eyJ1cmwiOiJodHRwczovL21jcC5zdmdyaWQuY29tL21jcCJ9)\n· [Add to VS Code](https://insiders.vscode.dev/redirect/mcp/install?name=svgrid&config=%7B%22name%22%3A%22svgrid%22%2C%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fmcp.svgrid.com%2Fmcp%22%7D)\n\nIt carries seven tools - `search`, `fetch`, `list_examples`,\n`get_example_source`, `get_api_reference`, `check_svgrid_code` and\n`svgrid_preview` - and needs no Node, no config file, and no key.\n\n**Local (`npx @svgrid/mcp`).** Everything the hosted server has, plus\nthe Studio tools, the docs and demos as MCP resources, ready-made\nprompts, and a `svgrid_check_code` that additionally *compiles* the file\nwith the Svelte compiler rather than checking it statically. Use it when\nyou want the compile pass, the Studio tools, or no third-party endpoint\nin the loop.\n\n| | Hosted | Local |\n| --- | --- | --- |\n| Setup | a URL | `npx @svgrid/mcp` |\n| Needs Node | no | yes |\n| Code check compiles | no, static checks only | yes |\n| Resources and prompts | yes | yes |\n| Visual preview | yes | yes |\n| `studio_*` tools | no | yes, opt-in |\n| Works offline | no | yes |\n\n## Install\n\nNo install step is required - `npx` fetches it on demand:\n\n```bash\n# One-shot, from any project\nnpx -y @svgrid/mcp\n```\n\nTo pin it as a dev dependency instead:\n\n```bash\npnpm add -D @svgrid/mcp\n```\n\nThe local server is a Node binary (`svgrid-mcp`) that speaks MCP over\nstdio. There is no daemon to maintain. The hosted server needs no install\nstep at all - skip to [Wire it into your AI client](#wire-it-into-your-ai-client)\nand use the URL.\n\n## Wire it into your AI client\n\nEvery snippet below shows the local (stdio) form and the hosted (HTTP)\nform. Pick one - running both connects the same tools twice.\n\n### Claude Code\n\nThe plugin is the shortest path: it installs the\n[Agent Skill](./skill.md) and the hosted server together, so the model\ngets the house style *and* the checker in one step.\n\n```\n/plugin marketplace add sv-grid/sv-grid\n/plugin install svgrid@svgrid\n```\n\nOr add the server on its own:\n\n```bash\n# hosted, nothing to install\nclaude mcp add --transport http svgrid https://mcp.svgrid.com/mcp\n\n# or local\nclaude mcp add svgrid -- npx -y @svgrid/mcp\n```\n\nThen run `/mcp` in a session and you will see `svgrid` listed.\n\nTo share the server with your team, add `--scope project`. That writes\na `.mcp.json` at the repository root which you can commit, so everyone\nwho clones the repo gets the same tooling with no per-machine setup:\n\n```bash\nclaude mcp add svgrid --scope project -- npx -y @svgrid/mcp\n```\n\n### Claude Desktop\n\nEdit `~/Library/Application Support/Claude/claude_desktop_config.json`\n(macOS) or `%APPDATA%\\Claude\\claude_desktop_config.json` (Windows):\n\n```json\n{\n \"mcpServers\": {\n \"svgrid\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@svgrid/mcp\"]\n }\n }\n}\n```\n\nOr the hosted server, with nothing to install:\n\n```json\n{\n \"mcpServers\": {\n \"svgrid\": {\n \"type\": \"http\",\n \"url\": \"https://mcp.svgrid.com/mcp\"\n }\n }\n}\n```\n\nRestart Claude Desktop, then ask *\"using svgrid, build me a grid that\ngroups by department\"* to confirm the tools are exposed.\n\n### Cursor\n\nOne click:\n[Add to Cursor](https://cursor.com/en/install-mcp?name=svgrid&config=eyJ1cmwiOiJodHRwczovL21jcC5zdmdyaWQuY29tL21jcCJ9)\n\nOr by hand, in `Settings -> MCP -> Add new MCP server`:\n\n```json\n{ \"url\": \"https://mcp.svgrid.com/mcp\" }\n```\n\n```json\n{ \"command\": \"npx\", \"args\": [\"-y\", \"@svgrid/mcp\"] }\n```\n\n### Zed\n\n`~/.config/zed/settings.json`:\n\n```json\n{\n \"context_servers\": {\n \"svgrid\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@svgrid/mcp\"],\n \"env\": {}\n }\n }\n}\n```\n\n### VS Code\n\nOne click:\n[Add to VS Code](https://insiders.vscode.dev/redirect/mcp/install?name=svgrid&config=%7B%22name%22%3A%22svgrid%22%2C%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fmcp.svgrid.com%2Fmcp%22%7D)\n\nOr create `.vscode/mcp.json` in the workspace. Note that VS Code uses\n`servers` rather than the `mcpServers` wrapper:\n\n```json\n{\n \"servers\": {\n \"svgrid\": {\n \"type\": \"http\",\n \"url\": \"https://mcp.svgrid.com/mcp\"\n }\n }\n}\n```\n\n```json\n{\n \"servers\": {\n \"svgrid\": {\n \"type\": \"stdio\",\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@svgrid/mcp\"]\n }\n }\n}\n```\n\n### Custom agents (OpenAI Agents SDK, Anthropic SDK, LangChain)\n\nPoint your client's MCP stdio transport at `npx -y @svgrid/mcp`, or its\nstreamable-HTTP transport at `https://mcp.svgrid.com/mcp`. Any client that\nspeaks either transport works.\n\nThe hosted server names its two retrieval tools `search` and `fetch`\nexactly, which is what a connector needs to index it.\n\n## Tools exposed\n\nFive, by default. `tools/list` is sent on **every** request, so the tool\nsurface is pure overhead on every turn - and this server used to spend\n~4,710 tokens of it on 36 tools, 79% of them Studio tools that most\nsessions never call once.\n\n| Tool | What it does |\n| ---- | ------------ |\n| `svgrid_search` | Search the docs, every demo and the API surface **in one call**. No arguments returns an index. |\n| `svgrid_get` | Read one thing in full: a doc slug, a demo id, or `api`. |\n| `svgrid_check_code` | Verify code against the real exported surface before the user sees it. |\n| `svgrid_preview` | Render a **live, interactive grid** in the conversation from columns + rows. |\n| `svgrid_scaffold` | Turn a Drizzle schema, sample rows or an EntitySchema into runnable SvelteKit files. |\n\nStudio adds four more, and only when you ask for them - set\n`SVGRID_MCP_STUDIO=1` or a licence key in the server's env. They need a\nlicence to be useful, so they are not charged to everyone else's context\nwindow.\n\n`svgrid_scaffold` and the Studio tools run on `@svgrid/enterprise`, which the\nserver loads only when it is installed beside it. `npx -y @svgrid/mcp` leaves\nit out so the server starts fast. To scaffold, install both in the project and\nrun the local server:\n\n```bash\nnpm i -D @svgrid/mcp @svgrid/enterprise\nclaude mcp add svgrid -- npx svgrid-mcp\n```\n\nWithout `-y`, `npx` runs the installed copy instead of downloading one, so\nthere is no install on the first connect.\n\nThe **hosted** server carries `search`, `fetch`, `list_examples`,\n`get_example_source`, `get_api_reference`, `check_svgrid_code` and\n`svgrid_preview`, plus the same resources and prompts. The first two are named\nthat way deliberately: those exact names are what a one-click connector needs to\nindex a remote server. It also answers to `svgrid_search`, `svgrid_get` and\n`svgrid_check_code`, so a model that learned the npm package's names is never\ntold \"unknown tool\".\n\nWhat it does **not** have is the compile pass (the Svelte compiler cannot run in\na Worker), the Studio tools (they need a filesystem), and the offline guarantee\n- it is a remote server, so by definition your query reaches it. Use the local\none when any of those matter.\n\n### Verification\n\n#### `svgrid_check_code`\n\nChecks a file **against the version you have installed** and returns\nline-numbered diagnostics with the exact replacement for each: unknown\n`<SvGrid>` props, wrong `ColumnDef` keys, api methods that do not\nexist, imports that will not resolve, and Svelte 5 runes mistakes. It\nalso compiles the component, so a syntax error surfaces here rather\nthan in the user's terminal.\n\nThis is the tool that makes the rest worth having. Retrieval alone\nstill lets a model write a confident, wrong grid; nothing else in the\nserver stops it. Run it on every file you write, fix what it reports,\nand run it again.\n\n### Finding and reading\n\n#### `svgrid_search`\n\nOne call across all three corpora, because \"how do I pin a column\" does\nnot announce whether it is answered by a doc page, a demo, or an API\nname:\n\n```json\n{ \"query\": \"pin a column\" }\n```\n\nReturns ranked doc hits with excerpts, matching demos, and matching API\nnames - each with the reference you pass to `svgrid_get`. Narrow with\n`kind` (`docs` | `examples` | `api`), trade tokens for completeness\nwith `detail` (`concise` | `full`), and cap with `limit` (max 50).\n\nCall it with **no arguments** for an index of doc sections, demo\ncategories and API groups - the cheapest way to orient before searching.\n\n#### `svgrid_get`\n\n```json\n{ \"ref\": \"help/columns/column-definitions\" }\n{ \"ref\": \"11-stock-market\" }\n{ \"ref\": \"api\" }\n```\n\nThe kind is inferred from the reference; pass `kind` to force it. A\nreference that does not resolve comes back with near matches rather\nthan a bare \"not found\".\n\n### It fixes what it finds\n\n`svgrid_check_code` does not stop at telling you what is wrong. Where the\ncorrection is exact it returns the corrected file too:\n\n```json\n{\n \"diagnostics\": [ ... ],\n \"applied\": [\"rowData -> data (line 7)\", \"accessorKey -> field (line 3)\"],\n \"fixed\": \"<the corrected source>\"\n}\n```\n\nBoth fields are omitted when there is nothing mechanically fixable, so a clean\ncheck stays small.\n\nThe rules are deliberately narrow, because this tool's whole worth is that it\nnever cries wolf - and rewriting raises the stakes from wasting a turn to\ncorrupting working code. Only exact renames are applied (a known rename, or a\nclose-enough spelling), only on word boundaries, and only on the line the\ndiagnostic reported. Advice that is ambiguous - \"this has no equivalent, remove\nit\" - stays advice. A test asserts that running auto-fix across every demo\nin this repository changes nothing at all.\n\n### It knows which version you have\n\nThe result carries the version it checked against:\n\n```json\n{ \"version\": { \"corpus\": \"3.0.0\", \"installed\": \"2.6.8\", \"warning\": \"...\" } }\n```\n\nThe server reads the `@svgrid/grid` in your project and says plainly when it\ndisagrees with the corpus it ships, so a model is told to hedge instead of\nconfidently citing an API you do not have. A server that answers from a remote\nbackend cannot do this - it has no idea what is in your `node_modules`.\n\n### Nothing leaves your machine\n\nThis server makes **no network calls**. Not for docs, not for the API surface,\nnot for verification - the whole corpus (every demo, every doc page, the full\nexported API) ships inside the package, which is why it is megabytes rather\nthan kilobytes. There is no API key, no licence check on the wire, and no telemetry.\n\nIt works on a plane, behind a corporate proxy, and inside an air-gapped\nnetwork. `tools/mcp-offline.test.ts` enforces it: the server is driven through\na full session with every network primitive booby-trapped, and the test fails if\nanything is even attempted.\n\nThe one honest exception: the **preview** loads the grid from a CDN to draw it.\nThat happens in your client's sandboxed iframe, never in this server, and only\nwhen you actually render a preview.\n\n### Seeing the grid, not just reading about it\n\n`svgrid_preview` renders a **real, interactive SvGrid inside the\nconversation** - sortable, filterable, scrollable. Not a screenshot and not a\nmock table: the same `<sv-grid>` custom element a page would use, loaded from\nthe CDN, with the columns and rows you passed.\n\n```json\n{\n \"title\": \"Team roster\",\n \"columns\": [{ \"field\": \"name\", \"header\": \"Name\" }, { \"field\": \"amount\", \"header\": \"Amount\" }],\n \"data\": [{ \"name\": \"Ada\", \"amount\": 20000 }],\n \"sortable\": true\n}\n```\n\nIt uses [MCP Apps](https://blog.modelcontextprotocol.io/posts/2026-01-26-mcp-apps/),\nthe official UI extension: the tool points at a `ui://` resource through\n`_meta`, the client loads that HTML in a sandboxed iframe, and the tool's\n`structuredContent` arrives over a postMessage bridge. Supported in Claude\n(web and desktop), VS Code and ChatGPT.\n\nClients without UI support are not left out - they ignore the `_meta` and get\na text summary of the same grid, so it is always safe to call. That is the\nextension's own rule, and it is why the text half describes the grid rather\nthan pointing at a picture the reader cannot see.\n\nPass `demo` instead of `columns` / `data` and you get the demo's source: a\ndemo is a Svelte component, not data, so there is nothing to hand the element\nand rendering an empty grid would just look broken.\n\n### Resources and prompts\n\nThe docs and demos are also exposed as **MCP resources**, so a user can\nattach a page or a demo directly instead of hoping the model thinks to\nsearch for it:\n\n```\nsvgrid://doc/help/columns/column-definitions\nsvgrid://example/11-stock-market\n```\n\nAnd three **prompts** ship ready to run: `build_grid`, `explain_api`\nand `review_grid_code`. Each is written to make the model use this\nserver rather than recall SvGrid from training data, and each ends at\n`svgrid_check_code`.\n\n### SvGrid Studio (commercial)\n\nOff unless enabled. Set `SVGRID_MCP_STUDIO=1`, or a valid\n`SVGRID_LICENSE_KEY`, in the server's env, and run the server from a project\nthat has `@svgrid/enterprise` installed beside it\n(`npm i -D @svgrid/mcp @svgrid/enterprise`, then `npx svgrid-mcp`). Without it\nthese tools answer with those steps instead of running.\n\n#### `svgrid_scaffold`\n\nPoint it at a Drizzle schema, sample JSON rows, or an `EntitySchema`\nyou already have, and it infers the schema and generates the `$lib`\nschema module, a `+server.ts` API route and a `+page.svelte` with\n`SvGrid` + `SvGridEditPanel` - in one call. Pass `schemaOnly: true` to\nstop after inference. Generated bodies carry `svgrid:managed` markers,\nso regenerating preserves your edits outside them.\n\n#### The `studio_*` tools\n\nFour tools drive the same validated project model the visual designer\nuses:\n\n| Tool | What it does |\n| ---- | ------------ |\n| `studio_project` | `new`, `load`, `describe`, `config`, `capabilities` |\n| `studio_apply` | A **batch** of model changes - entities, screens, blocks, components - applied in order |\n| `studio_configure` | Theme, auth, access, tenancy, data layer, jobs, deploy target, layouts, in one call |\n| `studio_build` | `validate`, then `generate` the full runnable SvelteKit app |\n\nCall `studio_project` with `action: \"capabilities\"` first: it reports\nexactly what the installed version supports, so the agent does not have\nto guess block kinds or component keys.\n\n`studio_apply` takes a batch on purpose. Building a five-screen app was\ntwenty-odd round trips when every block was its own tool; now a whole\nscreen is one call, and a failure reports which op failed and what\nalready applied.\n\n### The pre-3.0 names\n\nEvery tool name from before 3.0 still answers - `search_docs`,\n`get_doc`, `list_examples`, `get_example_source`, `list_docs`,\n`get_api_reference`, `check_svgrid_code`, `introspect_source`,\n`scaffold_entity` and all 27 individual `studio_*` tools. They are not\n**listed**, because listing is what costs context and answering a name\nyou did not advertise costs nothing. Saved prompts and scripts keep\nworking; nobody pays for the compatibility.\n\nTheir JSON response shape follows 3.0, not 2.x. A model reads either\nwithout trouble; a script that parsed the old shape by hand needs a look.\n\n## Licensing\n\nThe documentation and example tools are free. The Studio code\ngenerators are part of the commercial offering. You can evaluate them\nwithout a key: they run, but prepend a notice comment\nto generated files. To license them, set\nthe key in your MCP client's server config:\n\n```json\n{\n \"mcpServers\": {\n \"svgrid\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@svgrid/mcp\"],\n \"env\": { \"SVGRID_LICENSE_KEY\": \"YOUR-LICENSE-KEY\" }\n }\n }\n}\n```\n\n## Enterprise features and the trial\n\nMost of SvGrid is the MIT `@svgrid/grid` package. Export to Excel and PDF,\npivot tables, the Kanban board, the scheduler, the spreadsheet and the\nserver-side row model are in `@svgrid/enterprise`, which is commercial.\n\nThe server tells your assistant which is which. In `svgrid_search` results a\npaid doc or demo carries `\"enterprise\": true`, and when a question is about a\npaid feature the answer says so once, with the trial link.\n`svgrid_get` puts the same line at the top of a paid doc or demo, and\n`svgrid_check_code` adds it when the fix is to install the package. Nothing\nis sent anywhere to do this; it is part of the answer text.\n\n`@svgrid/enterprise` runs without a license key and shows a watermark until\none is set, so you can try a feature before deciding. The\n[30-day trial](https://svgrid.com/pricing/?trial=mcp-docs) adds a download of\nevery demo and 30 days of email support.\n\n## Verifying it works\n\nAsk your model: *\"What MCP tools do you have from svgrid?\"* The local\nserver lists five, including `svgrid_check_code` (four Studio tools more when\nenabled); the hosted server lists seven.\n\nThen give it something to catch:\n\n> Check this with svgrid: `<SvGrid rowData={rows} {columns} />`\n\nIt should come back with `rowData` is not a SvGrid prop, use `data`. If\nit explains the code instead of calling a tool, the server is not\nconnected.\n\nIf nothing is listed at all, check your client's MCP log. For the local\nserver the usual cause is `npx` not being on PATH - use the absolute path\nto the binary. For the hosted one, confirm the endpoint answers:\n\n```bash\ncurl https://mcp.svgrid.com/health\n```\n\n## Security model\n\nThe two ways of running it differ here, so pick deliberately.\n\n**Local (`npx @svgrid/mcp`)**\n\n- Runs on your machine over stdio. No telemetry, no outbound network\n calls, no API key.\n- Serves a documentation and example corpus bundled into the package at\n build time, so answers are pinned to the version you installed.\n- `svgrid_check_code` reads the source you pass it in-process and never\n sends it anywhere.\n\n**Hosted (`https://mcp.svgrid.com/mcp`)**\n\n- Your client sends tool arguments to a Cloudflare Worker we operate.\n Anything you pass to a tool leaves your machine, and for\n `check_svgrid_code` that means **the source you ask it to check**.\n- Each call is recorded: tool name, duration, whether it succeeded, the\n query or id it was given, how many pages matched, and whether the answer\n mentioned the Enterprise trial. For `check_svgrid_code` only the **byte\n length** of the submitted source and the names of the rules that fired\n are recorded, never the source itself. The records stay in Cloudflare\n (Workers logs, and an Analytics Engine dataset kept three months) and are\n read in aggregate to see what people ask for.\n- No account, no key, no cookies. Requests are not tied to a user.\n- If your code cannot leave the building, use the local server. That is\n what it is for.\n\n**Both**\n\n- The Studio tools return generated files as data. Writing them to disk\n is your client's decision, not the server's.\n- See [security](./security.md) for the general supply-chain posture.\n\n## Building your own MCP integrations\n\nThe same docs manifest, JSON Schemas (column definitions, the grid's\noptions, export options, and the chart spec at `schemas/chart-spec.json`,\nwhich `svgrid_get` also serves for \"chart spec schema\"), and `llms.txt`\nfiles are also served directly from the docs site:\n\n```ts\nconst docs = await fetch('https://svgrid.com/docs.json').then((r) => r.json())\nconst schemas = await fetch('https://svgrid.com/schemas/index.json').then((r) => r.json())\nconst llms = await fetch('https://svgrid.com/llms-full.txt').then((r) => r.text())\n```\n\nIf you do not want to run the MCP server, building these into your\nagent's system prompt gives most of the same grounding.\n\n## Without the MCP server\n\nAn agent that can only fetch pages gets the same material over plain HTTP,\nin pieces small enough for one fetch (fetch tools cut a response near\n100 KB):\n\n| URL | What it holds |\n|---|---|\n| `/llms.txt` | The docs index, with links to everything below. `/llms/<product>.txt` (grid, ui, enterprise, sheet, base, studio, compare) is one product's part of it |\n| `/docs/<slug>.md` | One docs page as markdown |\n| `/demos.md`, `/demos/<id>.md` | Every live demo, and one demo with what it shows and its full source |\n| `/api.json` | Every export of `@svgrid/grid` and `@svgrid/enterprise` by module, with the member names of each type |\n| `/api/<name>.json` | One symbol's doc comment and signature, by its lowercased name: `/api/svgridapi.json`, `/api/createreview.json` |\n| `/.well-known/mcp.json` | Where this server is: the remote endpoint, the npm package, the setup commands |\n\n```ts\nconst index = await fetch('https://svgrid.com/api.json').then((r) => r.json())\nconst api = await fetch('https://svgrid.com/api/svgridapi.json').then((r) => r.json())\nconst demo = await fetch('https://svgrid.com/demos/702-change-review.md').then((r) => r.text())\n```\n\nIn a browser with WebMCP (`document.modelContext`), svgrid.com registers\nfour tools for an agent driving the page: `svgrid_search`, `svgrid_get_doc`,\n`svgrid_get_demo` and `svgrid_lookup_api`. They answer from the files\nabove.\n\n## Frequently asked questions\n\n### What is the SvGrid MCP server?\n\nA Model Context Protocol server that lets AI clients (Claude Code, Claude\nDesktop, Cursor, Zed, custom agents) query SvGrid's documentation, read real\ndemo source, scaffold SvelteKit CRUD apps, and check the code they write\nagainst the real API - grounded in the files the package ships, so the model\nanswers from current facts instead of guessing.\n\n### Do I need an API key to run it?\n\nNo, on either transport. A `SVGRID_LICENSE_KEY` is optional and only affects\nthe commercial Studio code generators.\n\n### Local or hosted - which should I use?\n\nHosted (`https://mcp.svgrid.com/mcp`) if you want it working in one paste,\nwith no Node and no config file. Local (`npx @svgrid/mcp`) if you want the\nSvelte compiler pass in `svgrid_check_code`, the Studio tools, offline\nuse, or your source never leaving the machine. See\n[Security model](#security-model) for what each one sends.\n\n### How does it help AI assistants write better SvGrid code?\n\nTwo ways. It exposes the docs, example sources, and API reference as tools,\nso the assistant retrieves version-pinned answers instead of hallucinating an\nAPI from training data. And `svgrid_check_code` closes the loop: the model\nruns what it wrote past the real exported surface and gets told exactly what\nis wrong before you see it. That matters most for Svelte 5, where models\nroutinely mix in outdated Svelte 4 syntax.\n\n### Does it work with a version of SvGrid I have not upgraded to?\n\nThe local server answers for the version bundled in the `@svgrid/mcp` release\nyou install, so pin it alongside `@svgrid/grid` if you are behind. The hosted\nserver always tracks the current release. Either way, every\n`svgrid_check_code` result names the version it checked against in its\n`checkedAgainst` field.\n\n## See also\n\n- [Agent Skill](./skill.md) - the always-on house-style layer; the Claude Code plugin installs it together with this server\n- [LLM grounding](./llm-grounding.md) - the same files used by the MCP server, but documented for direct LLM consumption\n- [Agents](./agents.md) - how to build an AI agent that drives the live grid\n- [AI assistant](./ai.md) - the in-grid AI features (filter / smart-fill / classify / summarise), free in @svgrid/grid\n"
5693
5701
  },
5694
5702
  {
5695
5703
  "slug": "help/migrating-from-ag-grid",
@@ -5976,7 +5984,7 @@ export const docs = [
5976
5984
  "path": "docs/help/rows/row-pagination.md",
5977
5985
  "title": "Row pagination",
5978
5986
  "section": "Rows",
5979
- "markdown": "# Row pagination\n\nPagination is opt-in. Register the feature, register the row model, then\neither turn it on with `showPagination` or drive its state from outside.\n<div data-docs-demo=\"02-sort-filter-paginate\" data-height=\"540\"></div>\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 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\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 {runnable}\n<script lang=\"ts\">\n import {\n SvGrid, tableFeatures,\n rowPaginationFeature, createPaginatedRowModel,\n } from '@svgrid/grid'\n\n const features = tableFeatures({ rowPaginationFeature })\n</script>\n\n<SvGrid {data} {columns} features={features} showPagination={true} />\n```\n\nThe wrapper renders a footer with page nav and a page-size selector.\n\n## Set the initial page size\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n showPagination={true}\n pageSize={25}\n/>\n```\n\nThe wrapper's footer renders 10 / 25 / 50 / 100 in the size selector\nand lets the user change it at runtime. Jumping to a page from outside\nis best done by hiding the built-in footer (`showPagination={false}`)\nand rendering your own controls - see the\n[`09-server-side` demo](../../../examples/src/demos/09-server-side.svelte)\nfor the canonical pattern. A server-side fetcher keeps the footer: hand\n`createServerDataSource` to the grid as `rowModel` and the pager reads the\nserver's count and drives the controller's `setPage` - see\n[Server paging](../server/server-paging.md).\n\n## Page size\n\nThe default is 10 unless you pass `pageSize`. The footer's size\nselector picks 10 / 25 / 50 / 100; pass a different `pageSize` to seed\na different initial value.\n\n## Pagination + virtualization\n\nThese two **work together** but they solve different problems. Use\nvirtualization when the page itself is large (>200 rows); use pagination\nwhen you want explicit pages, when the user prints/exports, or when\nserver-side fetch returns pages.\n\nFor 100k-row + virtualized examples, pagination is off and the whole\nfiltered set is scrollable - see\n[demos/06-large-dataset.svelte](../../../examples/src/demos/06-large-dataset.svelte).\n\n## Try it\n\n`pageable` turns the footer on and `pageSize` sets the slice. Sorting and\nfiltering run before pagination, so page 1 is always the first rows of the\nresult rather than the first rows of your array.\n\n```svelte {runnable}\n<SvGrid data={people} {columns} pageable pageSize={2} sortable filterable />\n```\n\n## See also\n\n- [Server-side guide](../../getting-started.md#11-server-side-data)\n- [Accessing rows](./accessing-rows.md)\n"
5987
+ "markdown": "# Row pagination\n\nPagination is opt-in: `pageable` turns it on (the longer `showPagination`\ndoes the same) and `pageSize` sets the slice. `<SvGrid>` pages its rows\nitself, so there is nothing else to register. `rowPaginationFeature` and\n`createPaginatedRowModel` are for the headless engine, where the row model\ngoes in `_rowModels.paginatedRowModel` of `createSvGridCore` (see\n[Row models](../headless/row-models.md)); `<SvGrid>` has no `options` prop\nto pass them through.\n<div data-docs-demo=\"02-sort-filter-paginate\" data-height=\"540\"></div>\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 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\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 {runnable}\n<SvGrid {data} {columns} pageable />\n```\n\nThe wrapper renders a footer with page nav and a page-size selector.\n\n## Set the initial page size\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n showPagination={true}\n pageSize={25}\n/>\n```\n\nThe wrapper's footer renders 10 / 25 / 50 / 100 in the size selector\nand lets the user change it at runtime. Jumping to a page from outside\nis best done by hiding the built-in footer (`showPagination={false}`)\nand rendering your own controls - see the\n[`09-server-side` demo](../../../examples/src/demos/09-server-side.svelte)\nfor the canonical pattern. A server-side fetcher keeps the footer: hand\n`createServerDataSource` to the grid as `rowModel` and the pager reads the\nserver's count and drives the controller's `setPage` - see\n[Server paging](../server/server-paging.md).\n\n## Page size\n\nThe default is 10 unless you pass `pageSize`. The footer's size\nselector picks 10 / 25 / 50 / 100; pass a different `pageSize` to seed\na different initial value.\n\n## Pagination + virtualization\n\nThese two **work together** but they solve different problems. Use\nvirtualization when the page itself is large (>200 rows); use pagination\nwhen you want explicit pages, when the user prints/exports, or when\nserver-side fetch returns pages.\n\nFor 100k-row + virtualized examples, pagination is off and the whole\nfiltered set is scrollable - see\n[demos/06-large-dataset.svelte](../../../examples/src/demos/06-large-dataset.svelte).\n\n## Try it\n\n`pageable` turns the footer on and `pageSize` sets the slice. Sorting and\nfiltering run before pagination, so page 1 is always the first rows of the\nresult rather than the first rows of your array.\n\n```svelte {runnable}\n<SvGrid data={people} {columns} pageable pageSize={2} sortable filterable />\n```\n\n## See also\n\n- [Server-side guide](../../getting-started.md#11-server-side-data)\n- [Accessing rows](./accessing-rows.md)\n"
5980
5988
  },
5981
5989
  {
5982
5990
  "slug": "help/rows/row-pinning",
@@ -6032,7 +6040,7 @@ export const docs = [
6032
6040
  "path": "docs/help/rows/tree-data.md",
6033
6041
  "title": "Tree data",
6034
6042
  "section": "Rows",
6035
- "markdown": "# Tree data\n\nNest rows into an expandable hierarchy with the `treeData` prop.\n\n<div data-docs-demo=\"426-tree-data\" data-height=\"520\"></div>\n\n<!-- tutorial:tree-data -->\n<figure class=\"docs-tutorial\" id=\"tutorial-tree-data\" data-docs-tutorial=\"tree-data\">\n<video class=\"docs-tutorial-video\" src=\"/tutorials/tree-data.mp4\" poster=\"/tutorials/tree-data.poster.webp\" width=\"960\" height=\"540\" muted loop playsinline preload=\"none\" aria-label=\"Tree data in SvGrid, 31 second tutorial\"><track kind=\"captions\" srclang=\"en\" label=\"English\" src=\"/tutorials/tree-data.vtt\" default>Your browser does not play embedded video. <a href=\"/tutorials/tree-data.mp4\">Download the MP4</a>.</video>\n<figcaption><strong>Tree data in SvGrid</strong> (31 s, silent).</figcaption>\n<details class=\"docs-tutorial-transcript\"><summary>Transcript</summary>\n<p>Tree data is one prop. Point treeData at the parent field and name the tree column, and flat rows become a hierarchy.</p>\n<p>Click an expander to open a branch. Children indent under their parent and keep every column.</p>\n<p>Expand all and Collapse all walk the whole tree through the grid API.</p>\n<p>Nested objects work too: flatten them once with flattenTreeData, and the same prop takes it from there.</p>\n</details>\n</figure>\n<!-- /tutorial:tree-data -->\n\nTree rows are **real data rows**. They keep their own cells, formatting,\nediting and selection, and only gain an expander plus indentation in the tree\ncolumn. That is the difference from row grouping, where the parent is a\nsynthetic full-width banner standing in for its children.\n\n## Flat data (parent id)\n\nThe model nests by parent id, so data that already carries one needs no\npreparation:\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 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 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<script lang=\"ts\">\n import { SvGrid } from '@svgrid/grid'\n\n const people = [\n { id: 1, managerId: null, name: 'Ada', title: 'CEO' },\n { id: 2, managerId: 1, name: 'Grace', title: 'VP Engineering' },\n { id: 3, managerId: 2, name: 'Alan', title: 'Principal Engineer' },\n ]\n</script>\n\n<SvGrid\n data={people}\n {columns}\n treeData={{ parentField: 'managerId', column: 'name' }}\n/>\n```\n\n| Option | Meaning |\n| --- | --- |\n| `parentField` | Field holding each row's parent id. Required. |\n| `idField` | Field holding the row's own id. Defaults to `'id'`. |\n| `column` | Column that carries the expander + indent. Defaults to the first visible column. |\n| `indentPx` | Indent per depth level, in px. Default `12`. |\n\n## Nested data (children arrays)\n\nThe grid only builds rows for the objects in `data`, so children nested inside\na parent are never rows. Flatten them first:\n\n```svelte\n<script lang=\"ts\">\n import { SvGrid, flattenTreeData } from '@svgrid/grid'\n\n const tree = [\n { id: 1, name: 'src', children: [\n { id: 2, name: 'components', children: [{ id: 3, name: 'Grid.svelte' }] },\n ] },\n ]\n\n // Stamps `__parentId` on every child and returns one flat list, children\n // directly after their parent.\n const rows = flattenTreeData(tree, { childrenField: 'children' })\n</script>\n\n<SvGrid data={rows} {columns} treeData={{ parentField: '__parentId', column: 'name' }} />\n```\n\n`flattenTreeData` takes `childrenField`, plus optional `idField` (default\n`'id'`) and `parentField` (default `'__parentId'`) if you want a different link\nfield.\n\n## Accessibility\n\nTurning on `treeData` puts the grid in the `treegrid` role. Every row gets\n`aria-level`, and expandable rows get `aria-expanded`. Keyboard:\n\n| Key | Action |\n| --- | --- |\n| <kbd>→</kbd> | Expand the focused row |\n| <kbd>←</kbd> | Collapse the focused row |\n| <kbd>Enter</kbd> / click | Toggle via the expander button |\n\nRows without children render a spacer where the chevron would be, so values\nstay aligned with their expandable siblings.\n\n## Edge cases\n\n- **Missing parent.** A row whose `parentField` points at an id that is not in\n the data becomes a root rather than disappearing. Losing rows silently is\n worse than a shallower tree - this matters when a filter removes a parent but\n keeps a child.\n- **Self-parenting.** A row that names itself as its parent is treated as a root.\n- **Cycles.** A loop in the parent chain is detected and stops the walk instead\n of recursing forever.\n- **Grouping.** `treeData` replaces row grouping - a row cannot be both a\n hierarchy node and bucketed under a group banner.\n\n## Server-side trees\n\nFor hierarchies too large to send at once, load children on demand with the\nEnterprise `createServerRowModel` (`treeData: true`) over a `ServerDataSource`\ninstead - see [Server tree data](../server/server-tree-data.md). The two share\nthe same treegrid keyboard and ARIA contract.\n\n## More examples\n\n### Project WBS tree\n\nPhase → task → subtask with % complete that rolls up via effort-weighted average when you edit any leaf.\n\n<div data-docs-demo=\"29-wbs-project-tree\" data-height=\"460\"></div>\n\n### Bill of Materials\n\nBicycle BOM, 4 levels deep. Edit any leaf part's qty or unit cost; subtotals roll up through the assembly chain to the grand total.\n\n<div data-docs-demo=\"30-bom-tree\" data-height=\"460\"></div>\n\n## See also\n\n- [Demo #426 Tree data](https://svgrid.com/demos/426-tree-data/)\n- [Grouping & aggregation](../grouping-aggregation.md) - the row-bucketing shape\n- [Master / detail](./master-detail.md) - a rich panel under a row, rather than child rows\n"
6043
+ "markdown": "# Tree data\n\nNest rows into an expandable hierarchy with the `treeData` prop.\n\n<div data-docs-demo=\"426-tree-data\" data-height=\"520\"></div>\n\n<!-- tutorial:tree-data -->\n<figure class=\"docs-tutorial\" id=\"tutorial-tree-data\" data-docs-tutorial=\"tree-data\">\n<video class=\"docs-tutorial-video\" src=\"/tutorials/tree-data.mp4\" poster=\"/tutorials/tree-data.poster.webp\" width=\"960\" height=\"540\" muted loop playsinline preload=\"none\" aria-label=\"Tree data in SvGrid, 31 second tutorial\"><track kind=\"captions\" srclang=\"en\" label=\"English\" src=\"/tutorials/tree-data.vtt\" default>Your browser does not play embedded video. <a href=\"/tutorials/tree-data.mp4\">Download the MP4</a>.</video>\n<figcaption><strong>Tree data in SvGrid</strong> (31 s, silent).</figcaption>\n<details class=\"docs-tutorial-transcript\"><summary>Transcript</summary>\n<p>Tree data is one prop. Point treeData at the parent field and name the tree column, and flat rows become a hierarchy.</p>\n<p>Click an expander to open a branch. Children indent under their parent and keep every column.</p>\n<p>Expand all and Collapse all walk the whole tree through the grid API.</p>\n<p>Nested objects work too: flatten them once with flattenTreeData, and the same prop takes it from there.</p>\n</details>\n</figure>\n<!-- /tutorial:tree-data -->\n\nTree rows are **real data rows**. They keep their own cells, formatting,\nediting and selection, and only gain an expander plus indentation in the tree\ncolumn. That is the difference from row grouping, where the parent is a\nsynthetic full-width banner standing in for its children.\n\n## Flat data (parent id)\n\nThe model nests by parent id, so data that already carries one needs no\npreparation:\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 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 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<script lang=\"ts\">\n import { SvGrid } from '@svgrid/grid'\n\n const people = [\n { id: 1, managerId: null, name: 'Ada', title: 'CEO' },\n { id: 2, managerId: 1, name: 'Grace', title: 'VP Engineering' },\n { id: 3, managerId: 2, name: 'Alan', title: 'Principal Engineer' },\n ]\n</script>\n\n<SvGrid\n data={people}\n {columns}\n treeData={{ parentField: 'managerId', column: 'name' }}\n/>\n```\n\n| Option | Meaning |\n| --- | --- |\n| `parentField` | Field holding each row's parent id. Required. |\n| `idField` | Field holding the row's own id. Defaults to `'id'`. |\n| `column` | Column that carries the expander + indent. Defaults to the first visible column. |\n| `indentPx` | Indent per depth level, in px. Default `12`. |\n\n## Nested data (children arrays)\n\nThe grid only builds rows for the objects in `data`, so children nested inside\na parent are never rows. Flatten them first:\n\n```svelte\n<script lang=\"ts\">\n import { SvGrid, flattenTreeData } from '@svgrid/grid'\n\n const tree = [\n { id: 1, name: 'src', children: [\n { id: 2, name: 'components', children: [{ id: 3, name: 'Grid.svelte' }] },\n ] },\n ]\n\n // Stamps `__parentId` on every child and returns one flat list, children\n // directly after their parent.\n const rows = flattenTreeData(tree, { childrenField: 'children' })\n</script>\n\n<SvGrid data={rows} {columns} treeData={{ parentField: '__parentId', column: 'name' }} />\n```\n\n`flattenTreeData` takes `childrenField`, plus optional `idField` (default\n`'id'`) and `parentField` (default `'__parentId'`) if you want a different link\nfield.\n\n## Accessibility\n\nTurning on `treeData` puts the grid in the `treegrid` role. Every row gets\n`aria-level`, and expandable rows get `aria-expanded`. Keyboard:\n\n| Key | Action |\n| --- | --- |\n| <kbd>→</kbd> | Expand the focused row |\n| <kbd>←</kbd> | Collapse the focused row |\n| <kbd>Enter</kbd> / click | Toggle via the expander button |\n\nRows without children render a spacer where the chevron would be, so values\nstay aligned with their expandable siblings.\n\n## Edge cases\n\n- **Missing parent.** A row whose `parentField` points at an id that is not in\n the data becomes a root rather than disappearing. Losing rows silently is\n worse than a shallower tree - this matters when a filter removes a parent but\n keeps a child.\n- **Self-parenting.** A row that names itself as its parent is treated as a root.\n- **Cycles.** A loop in the parent chain is detected and stops the walk instead\n of recursing forever.\n- **Grouping.** `treeData` replaces row grouping - a row cannot be both a\n hierarchy node and bucketed under a group banner.\n\n## Server-side trees\n\nFor hierarchies too large to send at once, load children on demand with the\nEnterprise `createServerRowModel` (`treeData: true`) over a `ServerDataSource`\ninstead - see [Server tree data](../server/server-tree-data.md). The two share\nthe same treegrid keyboard and ARIA contract.\n\n## More examples\n\n### Test results tree with subtree reload\n\nA release-qualification board as a tree: test environments hold reported issues and test plans, plans hold runs, runs hold their Failed, Passed and Skipped results. The reload icon on an environment, plan or run re-reads that subtree only and splices it back in place, so open nodes stay open; the lab keeps reporting results in the background and a running run shows them after a reload. Rerun, Add result, Add issue and bulk Approve or Reject go through the same server, logged under the grid.\n\n<div data-docs-demo=\"703-test-run-tree\" data-height=\"580\"></div>\n\n\n### Project WBS tree\n\nPhase → task → subtask with % complete that rolls up via effort-weighted average when you edit any leaf.\n\n<div data-docs-demo=\"29-wbs-project-tree\" data-height=\"460\"></div>\n\n### Bill of Materials\n\nBicycle BOM, 4 levels deep. Edit any leaf part's qty or unit cost; subtotals roll up through the assembly chain to the grand total.\n\n<div data-docs-demo=\"30-bom-tree\" data-height=\"460\"></div>\n\n## See also\n\n- [Demo #426 Tree data](https://svgrid.com/demos/426-tree-data/)\n- [Grouping & aggregation](../grouping-aggregation.md) - the row-bucketing shape\n- [Master / detail](./master-detail.md) - a rich panel under a row, rather than child rows\n"
6036
6044
  },
6037
6045
  {
6038
6046
  "slug": "help/rows/tree-rows",
@@ -7656,70 +7664,133 @@ export const docs = [
7656
7664
  "path": "docs/reference/auto/index.md",
7657
7665
  "title": "Auto-generated reference",
7658
7666
  "section": "API reference",
7659
- "markdown": "# Auto-generated reference\n\n_Generated from the published TypeScript sources. Do not edit by hand - rerun `node tools/build-reference.mjs`._\n\nFor the hand-curated reference (with defaults + behaviour tables),\nsee [the main reference index](../index.md).\n\n## @svgrid/grid\n\n- [`@svgrid/grid/core.ts`](./svgrid-grid-core.md) - 68 exports\n- [`@svgrid/grid/svgrid-wrapper.types.ts`](./svgrid-grid-svgrid-wrapper.types.md) - 10 exports\n- [`@svgrid/grid/ai.ts`](./svgrid-grid-ai.md) - 34 exports\n- [`@svgrid/grid/scheduler-model.ts`](./svgrid-grid-scheduler-model.md) - 30 exports\n- [`@svgrid/grid/dock-model.ts`](./svgrid-grid-dock-model.md) - 25 exports\n- [`@svgrid/grid/dock-manager-model.ts`](./svgrid-grid-dock-manager-model.md) - 32 exports\n- [`@svgrid/grid/chart.ts`](./svgrid-grid-chart.md) - 19 exports\n- [`@svgrid/grid/chart-types.ts`](./svgrid-grid-chart-types.md) - 61 exports\n- [`@svgrid/grid/chart-scale.ts`](./svgrid-grid-chart-scale.md) - 7 exports\n- [`@svgrid/grid/chart-format.ts`](./svgrid-grid-chart-format.md) - 1 exports\n- [`@svgrid/grid/chart-stats.ts`](./svgrid-grid-chart-stats.md) - 17 exports\n- [`@svgrid/grid/chart-trend.ts`](./svgrid-grid-chart-trend.md) - 2 exports\n- [`@svgrid/grid/chart-axes.ts`](./svgrid-grid-chart-axes.md) - 1 exports\n- [`@svgrid/grid/chart-cartesian.ts`](./svgrid-grid-chart-cartesian.md) - 5 exports\n- [`@svgrid/grid/chart-polar.ts`](./svgrid-grid-chart-polar.md) - 1 exports\n- [`@svgrid/grid/chart-hierarchy.ts`](./svgrid-grid-chart-hierarchy.md) - 2 exports\n- [`@svgrid/grid/chart-decimate.ts`](./svgrid-grid-chart-decimate.md) - 6 exports\n- [`@svgrid/grid/chart-financial.ts`](./svgrid-grid-chart-financial.md) - 8 exports\n- [`@svgrid/grid/chart-zoom.ts`](./svgrid-grid-chart-zoom.md) - 6 exports\n- [`@svgrid/grid/chart-motion.ts`](./svgrid-grid-chart-motion.md) - 1 exports\n- [`@svgrid/grid/chart-sync.svelte.ts`](./svgrid-grid-chart-sync.svelte.md) - 4 exports\n- [`@svgrid/grid/chart-indicators.ts`](./svgrid-grid-chart-indicators.md) - 14 exports\n- [`@svgrid/grid/chart-export-pdf.ts`](./svgrid-grid-chart-export-pdf.md) - 3 exports\n- [`@svgrid/grid/chart-samples.ts`](./svgrid-grid-chart-samples.md) - 3 exports\n- [`@svgrid/grid/SvGridChart.types.ts`](./svgrid-grid-SvGridChart.types.md) - 10 exports\n- [`@svgrid/grid/createTree.svelte.ts`](./svgrid-grid-createTree.svelte.md) - 12 exports\n- [`@svgrid/grid/editor-contract.ts`](./svgrid-grid-editor-contract.md) - 11 exports\n- [`@svgrid/grid/editor-registry.ts`](./svgrid-grid-editor-registry.md) - 9 exports\n- [`@svgrid/grid/list-option.ts`](./svgrid-grid-list-option.md) - 14 exports\n- [`@svgrid/grid/builtin-editors.ts`](./svgrid-grid-builtin-editors.md) - 1 exports\n- [`@svgrid/grid/advanced-filter.svelte.ts`](./svgrid-grid-advanced-filter.svelte.md) - 6 exports\n- [`@svgrid/grid/filtering/filter-operator-catalogue.ts`](./svgrid-grid-filter-operator-catalogue.md) - 8 exports\n- [`@svgrid/grid/filtering/row-predicate.ts`](./svgrid-grid-row-predicate.md) - 1 exports\n- [`@svgrid/grid/grid-messages.ts`](./svgrid-grid-grid-messages.md) - 4 exports\n- [`@svgrid/grid/chart-messages.ts`](./svgrid-grid-chart-messages.md) - 4 exports\n- [`@svgrid/grid/chart-panel-messages.ts`](./svgrid-grid-chart-panel-messages.md) - 4 exports\n- [`@svgrid/grid/chart-validate.ts`](./svgrid-grid-chart-validate.md) - 7 exports\n- [`@svgrid/grid/chart-summary.ts`](./svgrid-grid-chart-summary.md) - 2 exports\n- [`@svgrid/grid/chart-stream.ts`](./svgrid-grid-chart-stream.md) - 3 exports\n- [`@svgrid/grid/chart-pivot.ts`](./svgrid-grid-chart-pivot.md) - 6 exports\n- [`@svgrid/grid/chart-table.ts`](./svgrid-grid-chart-table.md) - 3 exports\n- [`@svgrid/grid/grid-icons.ts`](./svgrid-grid-grid-icons.md) - 4 exports\n- [`@svgrid/grid/cell-formatting.ts`](./svgrid-grid-cell-formatting.md) - 5 exports\n- [`@svgrid/grid/positioning.ts`](./svgrid-grid-positioning.md) - 10 exports\n- [`@svgrid/grid/toast-store.svelte.ts`](./svgrid-grid-toast-store.svelte.md) - 14 exports\n- [`@svgrid/grid/spreadsheet.ts`](./svgrid-grid-spreadsheet.md) - 7 exports\n- [`@svgrid/grid/chart-export.ts`](./svgrid-grid-chart-export.md) - 7 exports\n- [`@svgrid/grid/scheduler-ical.ts`](./svgrid-grid-scheduler-ical.md) - 5 exports\n- [`@svgrid/grid/duration.ts`](./svgrid-grid-duration.md) - 2 exports\n- [`@svgrid/grid/datetime/date-core.ts`](./svgrid-grid-date-core.md) - 22 exports\n- [`@svgrid/grid/datetime/timezone.ts`](./svgrid-grid-timezone.md) - 8 exports\n- [`@svgrid/grid/datetime/mask.ts`](./svgrid-grid-mask.md) - 3 exports\n- [`@svgrid/grid/datetime/date-format.ts`](./svgrid-grid-date-format.md) - 3 exports\n- [`@svgrid/grid/datetime/date-restrict.ts`](./svgrid-grid-date-restrict.md) - 5 exports\n- [`@svgrid/grid/server-data-source.ts`](./svgrid-grid-server-data-source.md) - 21 exports\n- [`@svgrid/grid/server-block-cache.ts`](./svgrid-grid-server-block-cache.md) - 8 exports\n- [`@svgrid/grid/row-model.ts`](./svgrid-grid-row-model.md) - 4 exports\n\n## @svgrid/enterprise\n\n- [`@svgrid/enterprise/export.ts`](./svgrid-enterprise-export.md) - 17 exports\n- [`@svgrid/enterprise/pivot.ts`](./svgrid-enterprise-pivot.md) - 10 exports\n- [`@svgrid/enterprise/pivot-chart.ts`](./svgrid-enterprise-pivot-chart.md) - 2 exports\n- [`@svgrid/enterprise/import.ts`](./svgrid-enterprise-import.md) - 13 exports\n- [`@svgrid/enterprise/install.ts`](./svgrid-enterprise-install.md) - 4 exports\n- [`@svgrid/enterprise/server/server-row-model.ts`](./svgrid-enterprise-server-row-model.md) - 19 exports\n- [`@svgrid/enterprise/server/server-selection.ts`](./svgrid-enterprise-server-selection.md) - 6 exports\n- [`@svgrid/enterprise/server/server-pivot.ts`](./svgrid-enterprise-server-pivot.md) - 2 exports\n- [`@svgrid/enterprise/server/svgrid-adapter.ts`](./svgrid-enterprise-svgrid-adapter.md) - 16 exports\n"
7667
+ "markdown": "# Auto-generated reference\n\n_Generated from the published TypeScript sources. Do not edit by hand - rerun `node tools/build-reference.mjs`._\n\nFor the hand-curated reference (with defaults + behaviour tables),\nsee [the main reference index](../index.md).\n\n## @svgrid/grid\n\n- [`@svgrid/grid/core.ts`](./svgrid-grid-core.md) - 70 exports\n- [`@svgrid/grid/svgrid-wrapper.types.ts`](./svgrid-grid-svgrid-wrapper.types.md) - 10 exports\n- [`@svgrid/grid/ai.ts`](./svgrid-grid-ai.md) - 42 exports\n- [`@svgrid/grid/scheduler-model.ts`](./svgrid-grid-scheduler-model.md) - 30 exports\n- [`@svgrid/grid/dock-model.ts`](./svgrid-grid-dock-model.md) - 25 exports\n- [`@svgrid/grid/dock-manager-model.ts`](./svgrid-grid-dock-manager-model.md) - 32 exports\n- [`@svgrid/grid/chart.ts`](./svgrid-grid-chart.md) - 19 exports\n- [`@svgrid/grid/chart-types.ts`](./svgrid-grid-chart-types.md) - 61 exports\n- [`@svgrid/grid/chart-scale.ts`](./svgrid-grid-chart-scale.md) - 7 exports\n- [`@svgrid/grid/chart-format.ts`](./svgrid-grid-chart-format.md) - 1 exports\n- [`@svgrid/grid/chart-stats.ts`](./svgrid-grid-chart-stats.md) - 17 exports\n- [`@svgrid/grid/chart-trend.ts`](./svgrid-grid-chart-trend.md) - 2 exports\n- [`@svgrid/grid/chart-axes.ts`](./svgrid-grid-chart-axes.md) - 1 exports\n- [`@svgrid/grid/chart-cartesian.ts`](./svgrid-grid-chart-cartesian.md) - 5 exports\n- [`@svgrid/grid/chart-polar.ts`](./svgrid-grid-chart-polar.md) - 1 exports\n- [`@svgrid/grid/chart-hierarchy.ts`](./svgrid-grid-chart-hierarchy.md) - 2 exports\n- [`@svgrid/grid/chart-decimate.ts`](./svgrid-grid-chart-decimate.md) - 6 exports\n- [`@svgrid/grid/chart-financial.ts`](./svgrid-grid-chart-financial.md) - 8 exports\n- [`@svgrid/grid/chart-zoom.ts`](./svgrid-grid-chart-zoom.md) - 6 exports\n- [`@svgrid/grid/chart-motion.ts`](./svgrid-grid-chart-motion.md) - 1 exports\n- [`@svgrid/grid/chart-sync.svelte.ts`](./svgrid-grid-chart-sync.svelte.md) - 4 exports\n- [`@svgrid/grid/chart-indicators.ts`](./svgrid-grid-chart-indicators.md) - 14 exports\n- [`@svgrid/grid/chart-export-pdf.ts`](./svgrid-grid-chart-export-pdf.md) - 5 exports\n- [`@svgrid/grid/chart-samples.ts`](./svgrid-grid-chart-samples.md) - 3 exports\n- [`@svgrid/grid/SvGridChart.types.ts`](./svgrid-grid-SvGridChart.types.md) - 10 exports\n- [`@svgrid/grid/createTree.svelte.ts`](./svgrid-grid-createTree.svelte.md) - 12 exports\n- [`@svgrid/grid/editor-contract.ts`](./svgrid-grid-editor-contract.md) - 11 exports\n- [`@svgrid/grid/editor-registry.ts`](./svgrid-grid-editor-registry.md) - 9 exports\n- [`@svgrid/grid/list-option.ts`](./svgrid-grid-list-option.md) - 14 exports\n- [`@svgrid/grid/builtin-editors.ts`](./svgrid-grid-builtin-editors.md) - 1 exports\n- [`@svgrid/grid/advanced-filter.svelte.ts`](./svgrid-grid-advanced-filter.svelte.md) - 6 exports\n- [`@svgrid/grid/filtering/filter-operator-catalogue.ts`](./svgrid-grid-filter-operator-catalogue.md) - 8 exports\n- [`@svgrid/grid/filtering/row-predicate.ts`](./svgrid-grid-row-predicate.md) - 1 exports\n- [`@svgrid/grid/grid-messages.ts`](./svgrid-grid-grid-messages.md) - 4 exports\n- [`@svgrid/grid/chart-messages.ts`](./svgrid-grid-chart-messages.md) - 4 exports\n- [`@svgrid/grid/chart-panel-messages.ts`](./svgrid-grid-chart-panel-messages.md) - 4 exports\n- [`@svgrid/grid/chart-validate.ts`](./svgrid-grid-chart-validate.md) - 7 exports\n- [`@svgrid/grid/chart-summary.ts`](./svgrid-grid-chart-summary.md) - 2 exports\n- [`@svgrid/grid/chart-stream.ts`](./svgrid-grid-chart-stream.md) - 3 exports\n- [`@svgrid/grid/chart-pivot.ts`](./svgrid-grid-chart-pivot.md) - 6 exports\n- [`@svgrid/grid/chart-table.ts`](./svgrid-grid-chart-table.md) - 3 exports\n- [`@svgrid/grid/grid-icons.ts`](./svgrid-grid-grid-icons.md) - 4 exports\n- [`@svgrid/grid/cell-formatting.ts`](./svgrid-grid-cell-formatting.md) - 5 exports\n- [`@svgrid/grid/positioning.ts`](./svgrid-grid-positioning.md) - 10 exports\n- [`@svgrid/grid/toast-store.svelte.ts`](./svgrid-grid-toast-store.svelte.md) - 14 exports\n- [`@svgrid/grid/spreadsheet.ts`](./svgrid-grid-spreadsheet.md) - 7 exports\n- [`@svgrid/grid/chart-export.ts`](./svgrid-grid-chart-export.md) - 8 exports\n- [`@svgrid/grid/scheduler-ical.ts`](./svgrid-grid-scheduler-ical.md) - 5 exports\n- [`@svgrid/grid/duration.ts`](./svgrid-grid-duration.md) - 2 exports\n- [`@svgrid/grid/datetime/date-core.ts`](./svgrid-grid-date-core.md) - 22 exports\n- [`@svgrid/grid/datetime/timezone.ts`](./svgrid-grid-timezone.md) - 8 exports\n- [`@svgrid/grid/datetime/mask.ts`](./svgrid-grid-mask.md) - 3 exports\n- [`@svgrid/grid/datetime/date-format.ts`](./svgrid-grid-date-format.md) - 3 exports\n- [`@svgrid/grid/datetime/date-restrict.ts`](./svgrid-grid-date-restrict.md) - 5 exports\n- [`@svgrid/grid/server-data-source.ts`](./svgrid-grid-server-data-source.md) - 21 exports\n- [`@svgrid/grid/server-block-cache.ts`](./svgrid-grid-server-block-cache.md) - 8 exports\n- [`@svgrid/grid/row-model.ts`](./svgrid-grid-row-model.md) - 4 exports\n\n## @svgrid/enterprise\n\n- [`@svgrid/enterprise/export.ts`](./svgrid-enterprise-export.md) - 20 exports\n- [`@svgrid/enterprise/pivot.ts`](./svgrid-enterprise-pivot.md) - 10 exports\n- [`@svgrid/enterprise/pivot-chart.ts`](./svgrid-enterprise-pivot-chart.md) - 2 exports\n- [`@svgrid/enterprise/import.ts`](./svgrid-enterprise-import.md) - 16 exports\n- [`@svgrid/enterprise/install.ts`](./svgrid-enterprise-install.md) - 4 exports\n- [`@svgrid/enterprise/server/server-row-model.ts`](./svgrid-enterprise-server-row-model.md) - 19 exports\n- [`@svgrid/enterprise/server/server-selection.ts`](./svgrid-enterprise-server-selection.md) - 6 exports\n- [`@svgrid/enterprise/server/server-pivot.ts`](./svgrid-enterprise-server-pivot.md) - 2 exports\n- [`@svgrid/enterprise/server/svgrid-adapter.ts`](./svgrid-enterprise-svgrid-adapter.md) - 16 exports\n- [`@svgrid/enterprise/review/model.svelte.ts`](./svgrid-enterprise-review-model.svelte.md) - 8 exports\n- [`@svgrid/enterprise/review/types.ts`](./svgrid-enterprise-review-types.md) - 7 exports\n- [`@svgrid/enterprise/review/agent.ts`](./svgrid-enterprise-review-agent.md) - 4 exports\n- [`@svgrid/enterprise/review/adapters.ts`](./svgrid-enterprise-review-adapters.md) - 8 exports\n- [`@svgrid/enterprise/review/cluster.ts`](./svgrid-enterprise-review-cluster.md) - 3 exports\n- [`@svgrid/enterprise/review/equal.ts`](./svgrid-enterprise-review-equal.md) - 2 exports\n- [`@svgrid/enterprise/review/messages.ts`](./svgrid-enterprise-review-messages.md) - 2 exports\n- [`@svgrid/enterprise/review/formats.ts`](./svgrid-enterprise-review-formats.md) - 5 exports\n- [`@svgrid/enterprise/review/ghost.ts`](./svgrid-enterprise-review-ghost.md) - 1 exports\n"
7660
7668
  },
7661
7669
  {
7662
7670
  "slug": "reference/auto/svgrid-enterprise-export",
7663
7671
  "path": "docs/reference/auto/svgrid-enterprise-export.md",
7664
7672
  "title": "@svgrid/enterprise · export.ts",
7665
7673
  "section": "API reference",
7666
- "markdown": "# `@svgrid/enterprise` · `export.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\export.ts`.\n\n### `type ExportFormat`\n\nExport target formats.\n - `xlsx` modern OOXML workbook (needs `jszip`),\n - `xls` legacy Excel 2003 XML Spreadsheet (no peer dependency),\n - `pdf` paginated document (needs `pdfmake`),\n - `csv` / `tsv` / `html` / `json` / `xml` / `md` native, no peer deps.\n\n```ts\nexport type ExportFormat =\n | 'xlsx'\n | 'xls'\n | 'pdf'\n | 'csv'\n | 'tsv'\n | 'html'\n | 'json'\n | 'xml'\n | 'md'\n```\n\n### `type ExportColumn`\n\nOne column in an export: which field to read, and how to label and format it.\n\n```ts\nexport type ExportColumn<TData = RowData> = {\n /** Data field name on the row object. */\n field: string\n /** Header label to render in the exported file. Defaults to `field`. */\n header?: string\n /**\n * Column format config. When set (and `rawValues` is off), the exporter\n * renders the value the way the grid does on screen - currency symbol,\n * date pattern, percent, etc. Auto-populated from the grid's own columns\n * when you don't pass `columns` explicitly.\n */\n format?: CellFormatConfig\n /** Cell alignment, carried into html / pdf output. */\n align?: 'left' | 'center' | 'right'\n /** Explicit column width in pixels (xlsx / xls). Overrides auto-fit. */\n width?: number\n /**\n * Turn this column's cells into hyperlinks. Return the URL for a row (or\n * null for no link). Rendered as clickable links in xls / html / pdf /\n * print. (xlsx via the vendored writer doesn't support cell links.)\n */\n link?: (row: TData) => string | null | undefined\n /**\n * Escape hatch for columns whose on-screen value comes from a custom cell\n * renderer (a snippet), a `fieldFn`, or a lookup the raw field can't\n * express. Return the value to write for this row. Takes precedence over\n * `format`. Return a number / Date to keep it typed in xlsx.\n */\n exportValue?: (row: TData) => string | number | Date | null | undefined\n}\n```\n\n### `type ExportProgress`\n\nProgress reported during an export. `phase` is 'project' while building\n rows, 'serialize' while writing text formats, 'write' around the xlsx/pdf\n writer. `ratio` is 0..1.\n\n```ts\nexport type ExportProgress =\n | SerializeProgress\n | { phase: 'project' | 'write'; ratio: number; row?: number; total?: number }\n```\n\n### `type ExportResult`\n\nThe built export file. Returned by `exportData` for the dependency-free\npaths (csv/tsv/html/json/xml/md, xls, pdf, single-sheet xlsx) so callers can\npreview / upload / email / attach it instead of (or as well as) downloading.\nWith `download: false`, nothing is downloaded and this is returned.\n\n```ts\nexport type ExportResult = {\n blob: Blob\n filename: string\n mime: string\n /** Number of data rows written (excludes the header). */\n rowCount: number\n byteSize: number\n}\n```\n\n### `type ExportCellStyle`\n\nPer-cell style descriptor. Mirrors a subset of CSS; the keys the\nunderlying exporter honours are font / colour / background / border /\nalignment. Anything else is ignored gracefully.\n\n```ts\nexport type ExportCellStyle = {\n color?: string\n backgroundColor?: string\n fontWeight?: 'normal' | 'bold' | number\n fontStyle?: 'normal' | 'italic'\n fontSize?: number | string\n fontFamily?: string\n border?: string\n textAlign?: 'left' | 'right' | 'center'\n verticalAlign?: 'top' | 'middle' | 'bottom'\n}\n```\n\n### `type ExportStyles`\n\nDocument-level style. Apply blanket styles to the header row, the\nvalue rows, or selectively per cell-reference (e.g. `'B2'`).\n\n```ts\nexport type ExportStyles = {\n /** Style applied to every header cell. */\n headerRow?: ExportCellStyle\n /** Style applied to every data row. Even / odd zebra are derived from this if `rowAlternate` is set. */\n rows?: ExportCellStyle\n /** Optional zebra background for odd-indexed rows. */\n rowAlternate?: ExportCellStyle\n /** Per-cell overrides keyed by Excel-style reference (`'A1'`, `'C3'`). */\n cells?: Record<string, ExportCellStyle>\n}\n```\n\n### `type ExportHeaderFooterLine`\n\nHeader / footer entries for xlsx + pdf. Each line is rendered top to\nbottom on the page. Embed an image with `{ image: dataUrl }`; embed\ntext with `{ text: '...', style?: ExportCellStyle }`.\n\n```ts\nexport type ExportHeaderFooterLine =\n | { text: string; style?: ExportCellStyle }\n | { image: string; width?: number; height?: number }\n | { left?: string; center?: string; right?: string }\n```\n\n### `type ExportSheet`\n\nOne tab of a multi-sheet workbook. Only formats with sheets (xlsx, xls) use these.\n\n```ts\nexport type ExportSheet<TData> = {\n /** Sheet/tab label. Required. */\n label: string\n /** Rows for this sheet. */\n rows: ReadonlyArray<TData>\n /** Per-sheet columns. Falls back to the top-level `columns` if omitted. */\n columns?: ReadonlyArray<ExportColumn<TData>>\n /** Per-sheet styles. */\n styles?: ExportStyles\n}\n```\n\n### `type ExportRowSource`\n\nWhich rows to export:\n 'displayed' (default) - the current filtered / sorted / paginated view,\n 'selected' - only checked rows,\n 'all' - the full underlying dataset (pre-filter),\n an explicit array - export exactly these.\n\n```ts\nexport type ExportRowSource<TData> = ReadonlyArray<TData> | 'displayed' | 'selected' | 'all'\n```\n\n### `type ExportOptions`\n\nEverything `exportGrid` accepts: the format, the filename, which rows and columns, and per-format tuning.\n\n```ts\nexport type ExportOptions<TData> = {\n format: ExportFormat\n /** Base filename (extension is appended if missing). Defaults to \"grid\". */\n filename?: string\n /**\n * Columns to include. If omitted, the grid's own visible columns are used\n * (carrying their header labels + `format`), falling back to the keys of\n * the first row.\n */\n columns?: ReadonlyArray<ExportColumn<TData>>\n /**\n * Source rows. Defaults to `'displayed'` (the current view). Pass\n * `'selected'` / `'all'`, or an explicit array to override.\n */\n rows?: ExportRowSource<TData>\n /**\n * By default the exporter writes the FORMATTED display value (what the user\n * sees) so the file matches the grid. Set `rawValues: true` to write the\n * underlying raw values instead (numbers stay numeric in xlsx; useful for\n * downstream data pipelines).\n */\n rawValues?: boolean\n /**\n * Auto-carry the grid's active row grouping into the export (xlsx outline\n * rows). On by default; set false to ignore grouping, or pass `groupBy`\n * explicitly to override. Ignored when you pass `groupBy` / `hierarchical`\n * / `sheets` yourself.\n */\n autoGroup?: boolean\n /** CSV / TSV tuning: delimiter, line ending, UTF-8 BOM. */\n csv?: CsvOptions\n /**\n * Freeze the header row so it stays visible when scrolling (xlsx / xls).\n * Default true.\n */\n freezeHeader?: boolean\n /** Freeze this many leading columns (xlsx / xls). Default 0. */\n freezeColumns?: number\n /**\n * Size columns to their content (xlsx / xls). Default true. A column's\n * explicit `width` always wins.\n */\n autoFitColumns?: boolean\n /**\n * Export long integer IDs (> 15 significant digits) as TEXT so Excel's\n * 15-digit float precision doesn't silently mangle them. Default false.\n * (xlsx / xls.)\n */\n precisionSafe?: boolean\n /**\n * Wrap the xlsx data in a native Excel Table (filter dropdowns, banded rows,\n * structured refs). `{ totalsRow: true }` adds a totals row with live\n * SUM/AVG formulas for numeric columns. Single-sheet xlsx only.\n */\n excelTable?: boolean | { totalsRow?: boolean; style?: string }\n /** Progress callback for large exports (row projection + serialization). */\n onProgress?: (progress: ExportProgress) => void\n /** Abort an in-flight export (checked between chunks). Throws `AbortError`. */\n signal?: AbortSignal\n /**\n * When false, don't trigger a browser download - just build the file and\n * return it as an {@link ExportResult} (`{ blob, filename, mime, rowCount,\n * byteSize }`) so the app can preview / upload / email it. Default true.\n * Not supported for the vendored-writer xlsx paths (grouped / multi-sheet /\n * images / blanket styles), which download directly.\n */\n download?: boolean\n /** PDF only. Page orientation. Defaults to \"portrait\" (auto-landscape for\n * wide grids). Shorthand for `pdf.pageOrientation`. */\n pageOrientation?: 'portrait' | 'landscape'\n /** PDF layout options: page size, margins, title / subtitle / logo, theme\n * colors, column widths, repeated header, page numbers. */\n pdf?: PdfExportOptions\n /**\n * Conditional formatting rules - the same array you pass to\n * `<SvGrid conditionalFormats>`. Carried into the styled formats (pdf, xlsx,\n * html): cell background / text color / bold, plus icon-set glyphs. Ignored\n * by the data formats (csv / tsv / json / xml / md).\n */\n conditionalFormats?: ReadonlyArray<ConditionalFormat<TData>>\n /**\n * Cell + row styles. Apply once to match a light/dark theme, or per-cell\n * for conditional formatting. xlsx and pdf honour these; csv/tsv ignore\n * them; html bakes them into inline `style=` attributes.\n */\n styles?: ExportStyles\n /** Page header lines (xlsx, pdf, html). Logos go here as `{ image: ... }`. */\n header?: ReadonlyArray<ExportHeaderFooterLine>\n /** Page footer lines. Common pattern: page number on the right. */\n footer?: ReadonlyArray<ExportHeaderFooterLine>\n /**\n * Multi-sheet export (xlsx only). When set, each entry becomes one\n * sheet/tab. The top-level `rows` / `columns` are ignored.\n */\n sheets?: ReadonlyArray<ExportSheet<TData>>\n /**\n * If a row has a column whose value matches one of these field names\n * AND the value looks like a URL or data URL, the cell is exported as\n * an embedded image (xlsx). Defaults to `[]` (no auto-detection).\n */\n imageFields?: ReadonlyArray<string>\n /**\n * Pixel dimensions used when embedding images. Smart's xlsx writer\n * draws the image at this size relative to the cell origin. Defaults\n * to `{ width: 32, height: 32 }`. Set larger for thumbnails, smaller\n * for inline icons.\n */\n imageSize?: { width: number; height: number }\n /**\n * Group flat rows by one or more field names. The exporter wraps each\n * group in an Excel outline row (with the +/- expand button), and\n * emits a `<value> <field>` group header above every cluster. Maps\n * straight to Smart DataExporter's constructor `groupBy` arg. xlsx\n * only; csv/tsv/html flatten the groups back out.\n */\n groupBy?: ReadonlyArray<string>\n /**\n * Mark rows as a hierarchical (tree) data source. Each row should\n * declare its own children either via the `subRows` convention or by\n * matching the parent/child shape Smart expects on the input rows.\n * Mutually exclusive with `groupBy`. xlsx only.\n */\n hierarchical?: boolean\n /**\n * Merged cells to write into the sheet (xlsx / pdf). Each entry spans\n * `colSpan` columns and `rowSpan` rows starting at the given zero-based\n * **body** row / column index (the header row is not counted). Mirrors the\n * grid's own `MergeSpec` shape closely, so grid merges map straight through -\n * convert a `MergeSpec` (`{ rowIndex, columnId, rowspan, colspan }`) by\n * resolving `columnId` to its column index. Mutually exclusive with\n * `groupBy` / `hierarchical`.\n */\n merges?: ReadonlyArray<ExportMerge>\n}\n```\n\n### `type ExportMerge`\n\nA merged cell region for {@link ExportOptions.merges}. `row` / `col` are\nzero-based indices into the exported body (header excluded). A cell that\nspans two columns to the right is `{ row, col, colSpan: 2 }`.\n\n```ts\nexport type ExportMerge = {\n row: number\n col: number\n /** Columns to span (default 1). */\n colSpan?: number\n /** Rows to span (default 1). */\n rowSpan?: number\n}\n```\n\n### `function resolveRowSource`\n\nResolve the {@link ExportRowSource} shorthand against the grid api.\n\n```ts\nexport function resolveRowSource<TFeatures extends TableFeatures, TData extends RowData>(\n api: SvGridApi<TFeatures, TData>,\n source: ExportRowSource<TData> | undefined,\n): ReadonlyArray<TData> {\n if (Array.isArray(source)) return source\n switch (source) {\n case 'selected':\n return api.getSelectedRows()\n case 'all':\n return api.getData()\n case 'displayed':\n case undefined:\n default:\n return api.getDisplayedRows()\n }\n}\n```\n\n### `function resolveColumns`\n\nResolve the export columns, carrying grid header labels + `format`.\n\n```ts\nexport function resolveColumns<TFeatures extends TableFeatures, TData extends RowData>(\n api: SvGridApi<TFeatures, TData>,\n opts: Pick<ExportOptions<TData>, 'columns'>,\n sourceRows: ReadonlyArray<TData>,\n): ReadonlyArray<ExportColumn<TData>> {\n if (opts.columns && opts.columns.length > 0) return opts.columns\n const gridCols = api.getColumns().filter((c) => c.visible && c.field)\n if (gridCols.length > 0) {\n return gridCols.map((c) => ({\n field: c.field!,\n header: c.header,\n format: c.format,\n align: c.align,\n }))\n }\n if (sourceRows.length > 0) {\n return Object.keys(sourceRows[0] as Record<string, unknown>)\n .filter((k) => !k.startsWith('_'))\n .map((field) => ({ field }) as ExportColumn<TData>)\n }\n return []\n}\n```\n\n### `function buildLinkResolver`\n\nA `(rowIdx, colIdx) => url` resolver from column `link` hooks, or undefined\n when no column defines links.\n\n```ts\nexport function buildLinkResolver<TData extends RowData>(\n cols: ReadonlyArray<ExportColumn<TData>>,\n rows: ReadonlyArray<TData>,\n): ((rowIdx: number, colIdx: number) => string | undefined) | undefined {\n if (!cols.some((c) => c.link)) return undefined\n return (rowIdx, colIdx) => {\n const col = cols[colIdx]\n const row = rows[rowIdx]\n if (!col?.link || !row) return undefined\n return col.link(row) || undefined\n }\n}\n```\n\n### `function buildGroupedPdfBody`\n\nBuild a grouped PDF body: a bold group header per cluster (nested for\nmulti-level grouping), the cluster's data rows, then a subtotal row summing\nthe numeric / currency columns. Values use the same formatting as the grid.\n\n```ts\nexport function buildGroupedPdfBody<TData extends RowData>(\n cols: ReadonlyArray<ExportColumn<TData>>,\n rows: ReadonlyArray<TData>,\n groupBy: ReadonlyArray<string>,\n): PdfBodyRow[] {\n const out: PdfBodyRow[] = []\n const headerOf = (field: string) => cols.find((c) => c.field === field)?.header ?? field\n // Put the \"Subtotal\" label in the first NON-numeric column; if every column\n // is numeric, -1 means \"don't overwrite a sum with the label\".\n const labelColIdx = cols.findIndex((c) => !isSummableColumn(c))\n\n const recurse = (subset: ReadonlyArray<TData>, level: number) => {\n if (level >= groupBy.length) {\n for (const r of subset) {\n out.push({ kind: 'data', cells: cols.map((c) => String(cellValueFor(c, r, false) ?? '')) })\n }\n return\n }\n const field = groupBy[level]!\n // Preserve first-seen order of group keys.\n const buckets = new Map<string, TData[]>()\n for (const r of subset) {\n const key = String((r as Record<string, unknown>)[field] ?? '')\n const bucket = buckets.get(key)\n if (bucket) bucket.push(r)\n else buckets.set(key, [r])\n }\n for (const [key, groupRows] of buckets) {\n out.push({ kind: 'group', label: `${headerOf(field)}: ${key} (${groupRows.length})`, level })\n recurse(groupRows, level + 1)\n // Subtotal row for the numeric columns of this cluster.\n const hasSummable = cols.some(isSummableColumn)\n if (hasSummable) {\n const cells = cols.map((c) => {\n if (!isSummableColumn(c)) return ''\n const sum = groupRows.reduce(\n (a, r) => a + (Number((r as Record<string, unknown>)[c.field]) || 0),\n 0,\n )\n return formatValueForExport(sum, c.format)\n })\n if (labelColIdx >= 0) cells[labelColIdx] = `Subtotal (${key})`\n out.push({ kind: 'subtotal', cells })\n }\n }\n }\n recurse(rows, 0)\n return out\n}\n```\n\n### `type ClipboardFormat`\n\nNative formats that can be placed on the clipboard.\n\n```ts\nexport type ClipboardFormat = 'csv' | 'tsv' | 'html' | 'json' | 'xml' | 'md'\n```\n\n### `type ClipboardExportOptions`\n\nOptions for copying a range to the clipboard, as opposed to writing a file.\n\n```ts\nexport type ClipboardExportOptions<TData> = {\n /** Clipboard payload format. Default 'tsv' (pastes cleanly into Excel / Sheets). */\n format?: ClipboardFormat\n columns?: ReadonlyArray<ExportColumn<TData>>\n rows?: ExportRowSource<TData>\n rawValues?: boolean\n csv?: CsvOptions\n onProgress?: (progress: ExportProgress) => void\n signal?: AbortSignal\n}\n```\n"
7674
+ "markdown": "# `@svgrid/enterprise` · `export.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\export.ts`.\n\n### `type ExportFormat`\n\nExport target formats.\n - `xlsx` modern OOXML workbook (needs `jszip`),\n - `xls` legacy Excel 2003 XML Spreadsheet (no peer dependency),\n - `pdf` paginated document (needs `pdfmake`),\n - `csv` / `tsv` / `html` / `json` / `xml` / `md` native, no peer deps.\n\n```ts\nexport type ExportFormat =\n | 'xlsx'\n | 'xls'\n | 'pdf'\n | 'csv'\n | 'tsv'\n | 'html'\n | 'json'\n | 'xml'\n | 'md'\n```\n\n### `type ExportColumn`\n\nOne column in an export: which field to read, and how to label and format it.\n\n```ts\nexport type ExportColumn<TData = RowData> = {\n /** Data field name on the row object. */\n field: string\n /** Header label to render in the exported file. Defaults to `field`. */\n header?: string\n /**\n * Column format config. When set (and `rawValues` is off), the exporter\n * renders the value the way the grid does on screen - currency symbol,\n * date pattern, percent, etc. Auto-populated from the grid's own columns\n * when you don't pass `columns` explicitly.\n */\n format?: CellFormatConfig\n /** Cell alignment, carried into html / pdf output. */\n align?: 'left' | 'center' | 'right'\n /** Explicit column width in pixels (xlsx / xls). Overrides auto-fit. */\n width?: number\n /**\n * Turn this column's cells into hyperlinks. Return the URL for a row (or\n * null for no link). Rendered as clickable links in xls / html / pdf /\n * print. (xlsx via the vendored writer doesn't support cell links.)\n */\n link?: (row: TData) => string | null | undefined\n /**\n * Escape hatch for columns whose on-screen value comes from a custom cell\n * renderer (a snippet), a `fieldFn`, or a lookup the raw field can't\n * express. Return the value to write for this row. Takes precedence over\n * `format`. Return a number / Date to keep it typed in xlsx.\n */\n exportValue?: (row: TData) => string | number | Date | null | undefined\n}\n```\n\n### `type ExportProgress`\n\nProgress reported during an export. `phase` is 'project' while building\n rows, 'serialize' while writing text formats, 'write' around the xlsx/pdf\n writer. `ratio` is 0..1.\n\n```ts\nexport type ExportProgress =\n | SerializeProgress\n | { phase: 'project' | 'write'; ratio: number; row?: number; total?: number }\n```\n\n### `type ExportResult`\n\nThe built export file. Returned by `exportData` for the dependency-free\npaths (csv/tsv/html/json/xml/md, xls, pdf, single-sheet xlsx) so callers can\npreview / upload / email / attach it instead of (or as well as) downloading.\nWith `download: false`, nothing is downloaded and this is returned.\n\n```ts\nexport type ExportResult = {\n blob: Blob\n filename: string\n mime: string\n /** Number of data rows written (excludes the header). */\n rowCount: number\n byteSize: number\n}\n```\n\n### `type ExportCellStyle`\n\nPer-cell style descriptor. Mirrors a subset of CSS; the keys the\nunderlying exporter honours are font / colour / background / border /\nalignment. Anything else is ignored gracefully.\n\n```ts\nexport type ExportCellStyle = {\n color?: string\n backgroundColor?: string\n fontWeight?: 'normal' | 'bold' | number\n fontStyle?: 'normal' | 'italic'\n fontSize?: number | string\n fontFamily?: string\n border?: string\n textAlign?: 'left' | 'right' | 'center'\n verticalAlign?: 'top' | 'middle' | 'bottom'\n}\n```\n\n### `type ExportStyles`\n\nDocument-level style. Apply blanket styles to the header row, the\nvalue rows, or selectively per cell-reference (e.g. `'B2'`).\n\n```ts\nexport type ExportStyles = {\n /** Style applied to every header cell. */\n headerRow?: ExportCellStyle\n /** Style applied to every data row. Even / odd zebra are derived from this if `rowAlternate` is set. */\n rows?: ExportCellStyle\n /** Optional zebra background for odd-indexed rows. */\n rowAlternate?: ExportCellStyle\n /** Per-cell overrides keyed by Excel-style reference (`'A1'`, `'C3'`). */\n cells?: Record<string, ExportCellStyle>\n}\n```\n\n### `type ExportHeaderFooterLine`\n\nHeader / footer entries for xlsx + pdf. Each line is rendered top to\nbottom on the page. Embed an image with `{ image: dataUrl }`; embed\ntext with `{ text: '...', style?: ExportCellStyle }`.\n\n```ts\nexport type ExportHeaderFooterLine =\n | { text: string; style?: ExportCellStyle }\n | { image: string; width?: number; height?: number }\n | { left?: string; center?: string; right?: string }\n```\n\n### `type ExportSheet`\n\nOne tab of a multi-sheet workbook. Only formats with sheets (xlsx, xls) use these.\n\n```ts\nexport type ExportSheet<TData> = {\n /** Sheet/tab label. Required. */\n label: string\n /** Rows for this sheet. */\n rows: ReadonlyArray<TData>\n /** Per-sheet columns. Falls back to the top-level `columns` if omitted. */\n columns?: ReadonlyArray<ExportColumn<TData>>\n /** Per-sheet styles. */\n styles?: ExportStyles\n}\n```\n\n### `type ExportRowSource`\n\nWhich rows to export:\n 'displayed' (default) - the current filtered / sorted / paginated view,\n 'selected' - only checked rows,\n 'all' - the full underlying dataset (pre-filter),\n an explicit array - export exactly these.\n\n```ts\nexport type ExportRowSource<TData> = ReadonlyArray<TData> | 'displayed' | 'selected' | 'all'\n```\n\n### `type ExportOptions`\n\nEverything `exportGrid` accepts: the format, the filename, which rows and columns, and per-format tuning.\n\n```ts\nexport type ExportOptions<TData> = {\n format: ExportFormat\n /** Base filename (extension is appended if missing). Defaults to \"grid\". */\n filename?: string\n /**\n * Columns to include. If omitted, the grid's own visible columns are used\n * (carrying their header labels + `format`), falling back to the keys of\n * the first row.\n */\n columns?: ReadonlyArray<ExportColumn<TData>>\n /**\n * Source rows. Defaults to `'displayed'` (the current view). Pass\n * `'selected'` / `'all'`, or an explicit array to override.\n */\n rows?: ExportRowSource<TData>\n /**\n * By default the exporter writes the FORMATTED display value (what the user\n * sees) so the file matches the grid. Set `rawValues: true` to write the\n * underlying raw values instead (numbers stay numeric in xlsx; useful for\n * downstream data pipelines).\n */\n rawValues?: boolean\n /**\n * Auto-carry the grid's active row grouping into the export (xlsx outline\n * rows). On by default; set false to ignore grouping, or pass `groupBy`\n * explicitly to override. Ignored when you pass `groupBy` / `hierarchical`\n * / `sheets` yourself.\n */\n autoGroup?: boolean\n /** CSV / TSV tuning: delimiter, line ending, UTF-8 BOM. */\n csv?: CsvOptions\n /**\n * Freeze the header row so it stays visible when scrolling (xlsx / xls).\n * Default true.\n */\n freezeHeader?: boolean\n /** Freeze this many leading columns (xlsx / xls). Default 0. */\n freezeColumns?: number\n /**\n * Size columns to their content (xlsx / xls). Default true. A column's\n * explicit `width` always wins.\n */\n autoFitColumns?: boolean\n /**\n * Export long integer IDs (> 15 significant digits) as TEXT so Excel's\n * 15-digit float precision doesn't silently mangle them. Default false.\n * (xlsx / xls.)\n */\n precisionSafe?: boolean\n /**\n * Wrap the xlsx data in a native Excel Table (filter dropdowns, banded rows,\n * structured refs). `{ totalsRow: true }` adds a totals row with live\n * SUM/AVG formulas for numeric columns. Single-sheet xlsx only.\n */\n excelTable?: boolean | { totalsRow?: boolean; style?: string }\n /** Progress callback for large exports (row projection + serialization). */\n onProgress?: (progress: ExportProgress) => void\n /** Abort an in-flight export (checked between chunks). Throws `AbortError`. */\n signal?: AbortSignal\n /**\n * When false, don't trigger a browser download - just build the file and\n * return it as an {@link ExportResult} (`{ blob, filename, mime, rowCount,\n * byteSize }`) so the app can preview / upload / email it. Default true.\n * Not supported for the vendored-writer xlsx paths (grouped / multi-sheet /\n * images / blanket styles), which download directly.\n */\n download?: boolean\n /** PDF only. Page orientation. Defaults to \"portrait\" (auto-landscape for\n * wide grids). Shorthand for `pdf.pageOrientation`. */\n pageOrientation?: 'portrait' | 'landscape'\n /** PDF layout options: page size, margins, title / subtitle / logo, theme\n * colors, column widths, repeated header, page numbers. */\n pdf?: PdfExportOptions\n /**\n * Conditional formatting rules - the same array you pass to\n * `<SvGrid conditionalFormats>`. Carried into the styled formats (pdf, xlsx,\n * html): cell background / text color / bold, plus icon-set glyphs. Ignored\n * by the data formats (csv / tsv / json / xml / md).\n */\n conditionalFormats?: ReadonlyArray<ConditionalFormat<TData>>\n /**\n * Cell + row styles. Apply once to match a light/dark theme, or per-cell\n * for conditional formatting. xlsx and pdf honour these; csv/tsv ignore\n * them; html bakes them into inline `style=` attributes.\n */\n styles?: ExportStyles\n /** Page header lines (xlsx, pdf, html). Logos go here as `{ image: ... }`. */\n header?: ReadonlyArray<ExportHeaderFooterLine>\n /** Page footer lines. Common pattern: page number on the right. */\n footer?: ReadonlyArray<ExportHeaderFooterLine>\n /**\n * Multi-sheet export (xlsx only). When set, each entry becomes one\n * sheet/tab. The top-level `rows` / `columns` are ignored.\n */\n sheets?: ReadonlyArray<ExportSheet<TData>>\n /**\n * If a row has a column whose value matches one of these field names\n * AND the value looks like a URL or data URL, the cell is exported as\n * an embedded image (xlsx). Defaults to `[]` (no auto-detection).\n */\n imageFields?: ReadonlyArray<string>\n /**\n * Pixel dimensions used when embedding images. Smart's xlsx writer\n * draws the image at this size relative to the cell origin. Defaults\n * to `{ width: 32, height: 32 }`. Set larger for thumbnails, smaller\n * for inline icons.\n */\n imageSize?: { width: number; height: number }\n /**\n * Group flat rows by one or more field names. The exporter wraps each\n * group in an Excel outline row (with the +/- expand button), and\n * emits a `<value> <field>` group header above every cluster. Maps\n * straight to Smart DataExporter's constructor `groupBy` arg. xlsx\n * only; csv/tsv/html flatten the groups back out.\n */\n groupBy?: ReadonlyArray<string>\n /**\n * Mark rows as a hierarchical (tree) data source. Each row should\n * declare its own children either via the `subRows` convention or by\n * matching the parent/child shape Smart expects on the input rows.\n * Mutually exclusive with `groupBy`. xlsx only.\n */\n hierarchical?: boolean\n /**\n * Merged cells to write into the sheet (xlsx / pdf). Each entry spans\n * `colSpan` columns and `rowSpan` rows starting at the given zero-based\n * **body** row / column index (the header row is not counted). Mirrors the\n * grid's own `MergeSpec` shape closely, so grid merges map straight through -\n * convert a `MergeSpec` (`{ rowIndex, columnId, rowspan, colspan }`) by\n * resolving `columnId` to its column index. Mutually exclusive with\n * `groupBy` / `hierarchical`.\n */\n merges?: ReadonlyArray<ExportMerge>\n}\n```\n\n### `type ExportMerge`\n\nA merged cell region for {@link ExportOptions.merges}. `row` / `col` are\nzero-based indices into the exported body (header excluded). A cell that\nspans two columns to the right is `{ row, col, colSpan: 2 }`.\n\n```ts\nexport type ExportMerge = {\n row: number\n col: number\n /** Columns to span (default 1). */\n colSpan?: number\n /** Rows to span (default 1). */\n rowSpan?: number\n}\n```\n\n### `function resolveRowSource`\n\nResolve the {@link ExportRowSource} shorthand against the grid api.\n\n```ts\nexport function resolveRowSource<TFeatures extends TableFeatures, TData extends RowData>(\n api: SvGridApi<TFeatures, TData>,\n source: ExportRowSource<TData> | undefined,\n): ReadonlyArray<TData>\n```\n\n### `function resolveColumns`\n\nResolve the export columns, carrying grid header labels + `format`.\n\n```ts\nexport function resolveColumns<TFeatures extends TableFeatures, TData extends RowData>(\n api: SvGridApi<TFeatures, TData>,\n opts: Pick<ExportOptions<TData>, 'columns'>,\n sourceRows: ReadonlyArray<TData>,\n): ReadonlyArray<ExportColumn<TData>>\n```\n\n### `function projectRows`\n\nProject source rows into the `[header, ...records]` shape the writers\nconsume, applying per-column formatting / `exportValue`. Async so it can\nyield to the event loop (and honour an abort) on large datasets.\n\n```ts\nexport async function projectRows<TData extends RowData>(\n sourceRows: ReadonlyArray<TData>,\n cols: ReadonlyArray<ExportColumn<TData>>,\n opts: Pick<ExportOptions<TData>, 'rawValues' | 'onProgress' | 'signal'>,\n): Promise<Array<Record<string, unknown>>>\n```\n\n### `function buildLinkResolver`\n\nA `(rowIdx, colIdx) => url` resolver from column `link` hooks, or undefined\n when no column defines links.\n\n```ts\nexport function buildLinkResolver<TData extends RowData>(\n cols: ReadonlyArray<ExportColumn<TData>>,\n rows: ReadonlyArray<TData>,\n): ((rowIdx: number, colIdx: number) => string | undefined) | undefined\n```\n\n### `function buildGroupedPdfBody`\n\nBuild a grouped PDF body: a bold group header per cluster (nested for\nmulti-level grouping), the cluster's data rows, then a subtotal row summing\nthe numeric / currency columns. Values use the same formatting as the grid.\n\n```ts\nexport function buildGroupedPdfBody<TData extends RowData>(\n cols: ReadonlyArray<ExportColumn<TData>>,\n rows: ReadonlyArray<TData>,\n groupBy: ReadonlyArray<string>,\n): PdfBodyRow[]\n```\n\n### `function exportGrid`\n\nExport a grid's rows to a file: xlsx, xls, pdf, csv, tsv, html, json, xml\nor md, picked by `opts.format`. It reads the columns and rows through the\ngrid api, so sorting, filtering and grouping carry over, and downloads the\nfile unless `opts.download` is false. Resolves with the file (`ExportResult`)\non the paths that build it in memory, undefined on the others.\n\n```ts\nexport async function exportGrid<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(api: SvGridApi<TFeatures, TData>, opts: ExportOptions<TData>): Promise<ExportResult | undefined>\n```\n\n### `type ClipboardFormat`\n\nNative formats that can be placed on the clipboard.\n\n```ts\nexport type ClipboardFormat = 'csv' | 'tsv' | 'html' | 'json' | 'xml' | 'md'\n```\n\n### `type ClipboardExportOptions`\n\nOptions for copying a range to the clipboard, as opposed to writing a file.\n\n```ts\nexport type ClipboardExportOptions<TData> = {\n /** Clipboard payload format. Default 'tsv' (pastes cleanly into Excel / Sheets). */\n format?: ClipboardFormat\n columns?: ReadonlyArray<ExportColumn<TData>>\n rows?: ExportRowSource<TData>\n rawValues?: boolean\n csv?: CsvOptions\n onProgress?: (progress: ExportProgress) => void\n signal?: AbortSignal\n}\n```\n\n### `function copyExportToClipboard`\n\nCopy the grid (current view / selection / all) to the clipboard in a native\ntext format instead of downloading a file. Defaults to `tsv`, which pastes\nstraight into Excel / Google Sheets as real columns. `html` writes rich\n`text/html` so pasted cells keep their table structure.\n\n```ts\nexport async function copyExportToClipboard<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(api: SvGridApi<TFeatures, TData>, opts: ClipboardExportOptions<TData> = {}): Promise<void>\n```\n"
7667
7675
  },
7668
7676
  {
7669
7677
  "slug": "reference/auto/svgrid-enterprise-import",
7670
7678
  "path": "docs/reference/auto/svgrid-enterprise-import.md",
7671
7679
  "title": "@svgrid/enterprise · import.ts",
7672
7680
  "section": "API reference",
7673
- "markdown": "# `@svgrid/enterprise` · `import.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\import.ts`.\n\n### `type ImportFormat`\n\nSource formats `importGrid` reads. `'auto'` picks one from the file extension.\n\n```ts\nexport type ImportFormat = 'xlsx' | 'csv' | 'tsv' | 'json' | 'auto'\n```\n\n### `type ImportColumnMap`\n\nMaps a source header to the row field it populates, for files whose columns do not match your data.\n\n```ts\nexport type ImportColumnMap = Record<string, string | null>\n```\n\n### `type ImportFieldType`\n\nDeclared data type per target field. When `columnTypes` is set on\n`ImportOptions`, the parser tries to coerce each non-empty cell into\nthe declared shape and emits an `ImportRowError` when it can't -\nstricter than the ad-hoc \"looks like a number\" fallback.\n\n```ts\nexport type ImportFieldType =\n | 'string'\n | 'number'\n | 'integer'\n | 'boolean'\n | 'date' // returns ISO yyyy-mm-dd\n | 'datetime' // returns ISO yyyy-mm-ddThh:mm:ss\n | 'json' // parses the cell as JSON (object / array / primitive)\n```\n\n### `type ImportColumnTypes`\n\nPer-field coercion, so a column of `\"42\"` strings arrives as numbers.\n\n```ts\nexport type ImportColumnTypes = Record<string, ImportFieldType>\n```\n\n### `type ImportGridColumn`\n\nThe slice of a grid column the auto-mapper needs: its target `field`,\na human `header` to match source headers against, and the `format`\nconfig to infer a column type from. Shaped to accept the output of\n`api.getColumns()` directly.\n\n```ts\nexport type ImportGridColumn = {\n field?: string\n header?: string\n format?: { type?: string } | null\n}\n```\n\n### `type ImportProgress`\n\nProgress ticks emitted during a large import so a UI can show a bar.\n\n```ts\nexport type ImportProgress = {\n /** Which stage is running. */\n phase: 'parse' | 'map'\n /** 0..1 completion of the current phase. */\n ratio: number\n /** Rows processed so far in this phase. */\n done: number\n /** Total rows this phase will process (0 when unknown, e.g. mid-parse). */\n total: number\n}\n```\n\n### `type ImportRowError`\n\nOne row that failed validation, with the reason and where it came from.\n\n```ts\nexport type ImportRowError = {\n /** 0-based row index in the SOURCE file (excluding the header). */\n rowIndex: number\n /** Target field name (the grid's column field), or '*' for whole-row errors. */\n field: string\n message: string\n}\n```\n\n### `type ImportValidator`\n\nPer-row check run during import. Return an error message to reject the row, or nothing to accept it.\n\n```ts\nexport type ImportValidator<TData> = (\n row: TData,\n rowIndex: number,\n) => Array<{ field: string; message: string }>\n```\n\n### `type ImportOptions`\n\nEverything `importGrid` accepts: the format, the column mapping and types, and the validator.\n\n```ts\nexport type ImportOptions<TData> = {\n /** The file to read. A `File`/`Blob` works for xlsx; a string is treated as\n * inline CSV/TSV/JSON text. */\n file: File | Blob | string\n /** When 'auto', the format is sniffed from `file.name`'s extension (Files\n * only), otherwise the function inspects the first characters of the\n * text payload. */\n format?: ImportFormat\n /**\n * Map source-header -> target-field. Missing entries fall back to the\n * source header verbatim (lowercased + trimmed). Pass `null` for a\n * source header you want to drop on the floor.\n */\n columnMap?: ImportColumnMap\n /**\n * Declared data types per target field. When set, the importer uses\n * strict per-type coercion (`'2024-03-15'` -> ISO date; `'$1,234'`\n * -> 1234 for `number` fields) and emits an `ImportRowError` whenever\n * a value can't be coerced. Fields not listed fall back to the\n * built-in best-effort coercion (currency / number / date sniffing\n * by value shape).\n */\n columnTypes?: ImportColumnTypes\n /** Per-row validator. Returned errors land in `result.errors`. */\n validator?: ImportValidator<TData>\n /**\n * When true, source headers are fuzzy-matched to the grid's own columns\n * (by header label or field name) to build the `columnMap` automatically,\n * and `columnTypes` are inferred from each matched column's `format`\n * (currency / number / percent -> number, date -> date, datetime ->\n * datetime). Anything you pass explicitly in `columnMap` / `columnTypes`\n * wins over the guess. This is what powers \"drop a file and it lines up\n * with my grid\" in `SvImportDialog`.\n */\n autoMap?: boolean\n /** When true, the parsed rows are appended to the grid via\n * `api.addRows(...)` automatically. Defaults to false (preview mode). */\n commit?: boolean\n /** Where to insert when `commit` is true. Defaults to 'bottom'. */\n commitAt?: 'top' | 'bottom' | number\n /**\n * Drop duplicate rows by this key field, keeping the LAST occurrence\n * (upsert-style, so a later row in the file wins). Runs after mapping,\n * so pass the TARGET field name. Rows with a null/undefined key are kept.\n */\n dedupeBy?: keyof TData | (string & {})\n // --- Enterprise guard-rails ----------------------------------------------\n /** Reject the import if the source has more than this many data rows.\n * Guards against a runaway upload locking up the tab. */\n maxRows?: number\n /**\n * What to do when the source exceeds `maxRows`. `'reject'` (default)\n * throws so no data is silently lost; `'truncate'` keeps the first\n * `maxRows` rows and sets `result.truncated` so you can warn the user.\n * Only affects `maxRows` - `maxBytes` always rejects (a partial binary /\n * CSV can't be truncated safely).\n */\n overLimit?: 'reject' | 'truncate'\n /** Reject a File/Blob larger than this many bytes before it is read. */\n maxBytes?: number\n /** Stop collecting validation errors past this many (keeps memory bounded\n * on a pathological file). `result.errorsTruncated` flags when it hit. */\n maxErrors?: number\n /** Text encoding for CSV/TSV/JSON read from a File/Blob. Default 'utf-8'.\n * Set e.g. 'windows-1252' / 'latin1' for legacy Excel CSV exports. */\n encoding?: string\n /** Abort a long parse/map (wire to an AbortController). Throws an\n * AbortError, matching the export API. */\n signal?: AbortSignal\n /** Progress callback for large files (parse + map phases). */\n onProgress?: (progress: ImportProgress) => void\n}\n```\n\n### `type ImportResult`\n\nThe outcome of an import: the rows that parsed, and the ones that did not with their errors.\n\n```ts\nexport type ImportResult<TData> = {\n /** Source headers as found in the file, in their original order. */\n headers: string[]\n /** Parsed + mapped rows. Order matches the source. */\n rows: TData[]\n /** All validation errors (zero-length if the file passed clean). */\n errors: ImportRowError[]\n /** Rows skipped because they were entirely blank. */\n skipped: number\n /** Total source rows the parser saw (including blanks and bad rows). */\n total: number\n /** Detected format (resolved from 'auto'). */\n format: Exclude<ImportFormat, 'auto'>\n /** True when `maxErrors` capped the error list (there were more). */\n errorsTruncated?: boolean\n /** Rows dropped by `dedupeBy` (0 when not deduping). */\n deduped?: number\n /** True when `maxRows` + `overLimit:'truncate'` dropped trailing rows.\n * `total` still reports the original source row count. */\n truncated?: boolean\n}\n```\n\n### `function mapImportMatrix`\n\nApply a column map + declared types + validator to an already-parsed\nmatrix. The pure, synchronous half of `importData` - no I/O, no license\ngate - so a preview UI can call it on every mapping change. For very large\nfiles prefer `mapImportMatrixAsync`, which yields to keep the UI live.\n\n```ts\nexport function mapImportMatrix<TData extends RowData>(\n matrix: string[][],\n opts: MapMatrixOptions<TData> = {},\n): MapMatrixResult<TData> {\n const built = buildRecords<TData>(matrix, opts.columnMap, opts.columnTypes, opts.maxErrors)\n const errors = built.errors\n // Type-coercion errors come first; the validator runs on the rows we\n // managed to build, so its errors share the same `rowIndex` basis.\n let errorsTruncated = built.errorsTruncated\n if (applyValidator(built.rows, errors, opts.validator, opts.maxErrors)) errorsTruncated = true\n let rows = built.rows\n let deduped = 0\n if (opts.dedupeBy) {\n const r = dedupeRows(rows, opts.dedupeBy as string)\n rows = r.rows\n deduped = r.deduped\n }\n return {\n headers: built.headers,\n rows,\n errors,\n skipped: built.skipped,\n total: matrix.length > 0 ? matrix.length - 1 : 0,\n errorsTruncated,\n deduped,\n }\n}\n```\n\n### `function autoMapColumns`\n\nFuzzy-match each source header to one of the grid's columns (by header\nlabel first, then field name) and return a `source header -> target\nfield` map. Headers with no confident match are left OUT of the map, so\n`buildRecords` falls back to its snake_case default for them.\n\n```ts\nexport function autoMapColumns(\n headers: string[],\n columns: ReadonlyArray<ImportGridColumn>,\n): ImportColumnMap {\n const byKey = new Map<string, string>()\n for (const c of columns) {\n const field = c.field ?? c.header\n if (!field) continue\n // Field name is the strongest signal, so register header first then let\n // the field key overwrite on a collision.\n if (c.header) byKey.set(normalizeHeader(c.header), field)\n if (c.field) byKey.set(normalizeHeader(c.field), c.field)\n }\n const map: ImportColumnMap = {}\n for (const h of headers) {\n const hit = byKey.get(normalizeHeader(h))\n if (hit) map[h] = hit\n }\n return map\n}\n```\n\n### `function inferImportColumnTypes`\n\nInfer strict import types from each grid column's `format`, so a currency\n/ number / percent column parses \"$1,234\" -> 1234 and a date column parses\n\"2026-03-04\" -> an ISO date. Columns with no informative format are left\nout (best-effort coercion applies).\n\n```ts\nexport function inferImportColumnTypes(\n columns: ReadonlyArray<ImportGridColumn>,\n): ImportColumnTypes {\n const types: ImportColumnTypes = {}\n for (const c of columns) {\n if (!c.field) continue\n const t = c.format?.type\n if (t === 'number' || t === 'currency' || t === 'percent') types[c.field] = 'number'\n else if (t === 'date') types[c.field] = 'date'\n else if (t === 'datetime') types[c.field] = 'datetime'\n }\n return types\n}\n```\n"
7681
+ "markdown": "# `@svgrid/enterprise` · `import.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\import.ts`.\n\n### `type ImportFormat`\n\nSource formats `importGrid` reads. `'auto'` picks one from the file extension.\n\n```ts\nexport type ImportFormat = 'xlsx' | 'csv' | 'tsv' | 'json' | 'auto'\n```\n\n### `type ImportColumnMap`\n\nMaps a source header to the row field it populates, for files whose columns do not match your data.\n\n```ts\nexport type ImportColumnMap = Record<string, string | null>\n```\n\n### `type ImportFieldType`\n\nDeclared data type per target field. When `columnTypes` is set on\n`ImportOptions`, the parser tries to coerce each non-empty cell into\nthe declared shape and emits an `ImportRowError` when it can't -\nstricter than the ad-hoc \"looks like a number\" fallback.\n\n```ts\nexport type ImportFieldType =\n | 'string'\n | 'number'\n | 'integer'\n | 'boolean'\n | 'date' // returns ISO yyyy-mm-dd\n | 'datetime' // returns ISO yyyy-mm-ddThh:mm:ss\n | 'json' // parses the cell as JSON (object / array / primitive)\n```\n\n### `type ImportColumnTypes`\n\nPer-field coercion, so a column of `\"42\"` strings arrives as numbers.\n\n```ts\nexport type ImportColumnTypes = Record<string, ImportFieldType>\n```\n\n### `type ImportGridColumn`\n\nThe slice of a grid column the auto-mapper needs: its target `field`,\na human `header` to match source headers against, and the `format`\nconfig to infer a column type from. Shaped to accept the output of\n`api.getColumns()` directly.\n\n```ts\nexport type ImportGridColumn = {\n field?: string\n header?: string\n format?: { type?: string } | null\n}\n```\n\n### `type ImportProgress`\n\nProgress ticks emitted during a large import so a UI can show a bar.\n\n```ts\nexport type ImportProgress = {\n /** Which stage is running. */\n phase: 'parse' | 'map'\n /** 0..1 completion of the current phase. */\n ratio: number\n /** Rows processed so far in this phase. */\n done: number\n /** Total rows this phase will process (0 when unknown, e.g. mid-parse). */\n total: number\n}\n```\n\n### `type ImportRowError`\n\nOne row that failed validation, with the reason and where it came from.\n\n```ts\nexport type ImportRowError = {\n /** 0-based row index in the SOURCE file (excluding the header). */\n rowIndex: number\n /** Target field name (the grid's column field), or '*' for whole-row errors. */\n field: string\n message: string\n}\n```\n\n### `type ImportValidator`\n\nPer-row check run during import. Return an error message to reject the row, or nothing to accept it.\n\n```ts\nexport type ImportValidator<TData> = (\n row: TData,\n rowIndex: number,\n) => Array<{ field: string; message: string }>\n```\n\n### `type ImportOptions`\n\nEverything `importGrid` accepts: the format, the column mapping and types, and the validator.\n\n```ts\nexport type ImportOptions<TData> = {\n /** The file to read. A `File`/`Blob` works for xlsx; a string is treated as\n * inline CSV/TSV/JSON text. */\n file: File | Blob | string\n /** When 'auto', the format is sniffed from `file.name`'s extension (Files\n * only), otherwise the function inspects the first characters of the\n * text payload. */\n format?: ImportFormat\n /**\n * Map source-header -> target-field. Missing entries fall back to the\n * source header verbatim (lowercased + trimmed). Pass `null` for a\n * source header you want to drop on the floor.\n */\n columnMap?: ImportColumnMap\n /**\n * Declared data types per target field. When set, the importer uses\n * strict per-type coercion (`'2024-03-15'` -> ISO date; `'$1,234'`\n * -> 1234 for `number` fields) and emits an `ImportRowError` whenever\n * a value can't be coerced. Fields not listed fall back to the\n * built-in best-effort coercion (currency / number / date sniffing\n * by value shape).\n */\n columnTypes?: ImportColumnTypes\n /** Per-row validator. Returned errors land in `result.errors`. */\n validator?: ImportValidator<TData>\n /**\n * When true, source headers are fuzzy-matched to the grid's own columns\n * (by header label or field name) to build the `columnMap` automatically,\n * and `columnTypes` are inferred from each matched column's `format`\n * (currency / number / percent -> number, date -> date, datetime ->\n * datetime). Anything you pass explicitly in `columnMap` / `columnTypes`\n * wins over the guess. This is what powers \"drop a file and it lines up\n * with my grid\" in `SvImportDialog`.\n */\n autoMap?: boolean\n /** When true, the parsed rows are appended to the grid via\n * `api.addRows(...)` automatically. Defaults to false (preview mode). */\n commit?: boolean\n /** Where to insert when `commit` is true. Defaults to 'bottom'. */\n commitAt?: 'top' | 'bottom' | number\n /**\n * Drop duplicate rows by this key field, keeping the LAST occurrence\n * (upsert-style, so a later row in the file wins). Runs after mapping,\n * so pass the TARGET field name. Rows with a null/undefined key are kept.\n */\n dedupeBy?: keyof TData | (string & {})\n // --- Enterprise guard-rails ----------------------------------------------\n /** Reject the import if the source has more than this many data rows.\n * Guards against a runaway upload locking up the tab. */\n maxRows?: number\n /**\n * What to do when the source exceeds `maxRows`. `'reject'` (default)\n * throws so no data is silently lost; `'truncate'` keeps the first\n * `maxRows` rows and sets `result.truncated` so you can warn the user.\n * Only affects `maxRows` - `maxBytes` always rejects (a partial binary /\n * CSV can't be truncated safely).\n */\n overLimit?: 'reject' | 'truncate'\n /** Reject a File/Blob larger than this many bytes before it is read. */\n maxBytes?: number\n /** Stop collecting validation errors past this many (keeps memory bounded\n * on a pathological file). `result.errorsTruncated` flags when it hit. */\n maxErrors?: number\n /** Text encoding for CSV/TSV/JSON read from a File/Blob. Default 'utf-8'.\n * Set e.g. 'windows-1252' / 'latin1' for legacy Excel CSV exports. */\n encoding?: string\n /** Abort a long parse/map (wire to an AbortController). Throws an\n * AbortError, matching the export API. */\n signal?: AbortSignal\n /** Progress callback for large files (parse + map phases). */\n onProgress?: (progress: ImportProgress) => void\n}\n```\n\n### `type ImportResult`\n\nThe outcome of an import: the rows that parsed, and the ones that did not with their errors.\n\n```ts\nexport type ImportResult<TData> = {\n /** Source headers as found in the file, in their original order. */\n headers: string[]\n /** Parsed + mapped rows. Order matches the source. */\n rows: TData[]\n /** All validation errors (zero-length if the file passed clean). */\n errors: ImportRowError[]\n /** Rows skipped because they were entirely blank. */\n skipped: number\n /** Total source rows the parser saw (including blanks and bad rows). */\n total: number\n /** Detected format (resolved from 'auto'). */\n format: Exclude<ImportFormat, 'auto'>\n /** True when `maxErrors` capped the error list (there were more). */\n errorsTruncated?: boolean\n /** Rows dropped by `dedupeBy` (0 when not deduping). */\n deduped?: number\n /** True when `maxRows` + `overLimit:'truncate'` dropped trailing rows.\n * `total` still reports the original source row count. */\n truncated?: boolean\n}\n```\n\n### `function readImportMatrix`\n\nRead a file (or inline text) into a raw `string[][]` matrix - header row\nfirst - without any mapping, coercion, or validation. The cheap half of\n`importData`: parse the bytes once, then feed the matrix to\n`mapImportMatrix` as many times as the mapping UI needs.\n\n```ts\nexport async function readImportMatrix(\n file: File | Blob | string,\n format: ImportFormat = 'auto',\n opts: { maxBytes?: number; encoding?: string; signal?: AbortSignal } = {},\n): Promise<{ format: Exclude<ImportFormat, 'auto'>; matrix: string[][] }>\n```\n\n### `function mapImportMatrix`\n\nApply a column map + declared types + validator to an already-parsed\nmatrix. The pure, synchronous half of `importData` - no I/O, no license\ngate - so a preview UI can call it on every mapping change. For very large\nfiles prefer `mapImportMatrixAsync`, which yields to keep the UI live.\n\n```ts\nexport function mapImportMatrix<TData extends RowData>(\n matrix: string[][],\n opts: MapMatrixOptions<TData> = {},\n): MapMatrixResult<TData>\n```\n\n### `function mapImportMatrixAsync`\n\nNon-blocking sibling of `mapImportMatrix`: yields to the event loop every\nfew thousand rows and reports progress, so mapping a 100k-row file never\nfreezes the tab. Honors an AbortSignal. Used by `importData` and the\nSvImportDialog preview.\n\n```ts\nexport async function mapImportMatrixAsync<TData extends RowData>(\n matrix: string[][],\n opts: MapMatrixOptions<TData> & {\n signal?: AbortSignal\n onProgress?: (progress: ImportProgress) => void\n /** Rows per chunk before yielding. Default 5000. */\n chunkSize?: number\n } = {},\n): Promise<MapMatrixResult<TData>>\n```\n\n### `function autoMapColumns`\n\nFuzzy-match each source header to one of the grid's columns (by header\nlabel first, then field name) and return a `source header -> target\nfield` map. Headers with no confident match are left OUT of the map, so\n`buildRecords` falls back to its snake_case default for them.\n\n```ts\nexport function autoMapColumns(\n headers: string[],\n columns: ReadonlyArray<ImportGridColumn>,\n): ImportColumnMap\n```\n\n### `function inferImportColumnTypes`\n\nInfer strict import types from each grid column's `format`, so a currency\n/ number / percent column parses \"$1,234\" -> 1234 and a date column parses\n\"2026-03-04\" -> an ISO date. Columns with no informative format are left\nout (best-effort coercion applies).\n\n```ts\nexport function inferImportColumnTypes(\n columns: ReadonlyArray<ImportGridColumn>,\n): ImportColumnTypes\n```\n\n### `function importData`\n\nRead a file (or inline text), parse, optionally validate + commit. The\nsister function of `exportGrid`.\n\n```ts\nexport async function importData<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n api: SvGridApi<TFeatures, TData>,\n opts: ImportOptions<TData>,\n): Promise<ImportResult<TData>>\n```\n"
7674
7682
  },
7675
7683
  {
7676
7684
  "slug": "reference/auto/svgrid-enterprise-install",
7677
7685
  "path": "docs/reference/auto/svgrid-enterprise-install.md",
7678
7686
  "title": "@svgrid/enterprise · install.ts",
7679
7687
  "section": "API reference",
7680
- "markdown": "# `@svgrid/enterprise` · `install.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\install.ts`.\n\n### `type EnterpriseAIApi`\n\nThe `api.ai.*` namespace added by the enterprise install.\n\n```ts\nexport type EnterpriseAIApi<TData extends RowData> = {\n /** Natural-language -> filter + sort plan (and optionally apply it). */\n filter(query: string, opts?: AIFilterOptions): Promise<AIFilterResult>\n /** Propose values for empty cells based on a few worked examples. */\n smartFill<TValue = unknown>(opts: AISmartFillOptions): Promise<AISmartFillResult<TValue>>\n /** One-paragraph + bullets summary of a row, selection, group, or the whole view. */\n summarize(opts: AISummarizeOptions): Promise<AISummary>\n /** Classify free-text cells into one of a known set of labels. */\n classify(opts: AIClassifyOptions): Promise<AIClassifyResult>\n /** Natural-language export: \"export EU orders from Q2 as a grouped PDF\". */\n export(query: string, opts?: AIExportOptions): Promise<AIExportPlan>\n /** Scan a slice for anomalies / outliers, returning a structured list. */\n findAnomalies(opts?: AIAnomalyOptions): Promise<AIAnomalyResult>\n /** Natural-language chart: \"revenue by region, stacked by product\". */\n chart(query: string, opts?: AIChartOptions): Promise<AIChartPlan>\n // TData is referenced so the type stays bound to the row shape even\n // though the helpers all read through `api.getData()`. Lets callers\n // get correct inference downstream without explicit generics.\n readonly _rowType?: TData\n}\n```\n\n### `type EnterprisePivotApi`\n\nThe `api.pivot.*` namespace added by the enterprise install.\n\n```ts\nexport type EnterprisePivotApi<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = {\n /**\n * Build a pivot row/column model from the grid's current data. Returns\n * `{ rows, columns }` you can feed to a separate `<SvGrid>` instance\n * (the typical pattern - the source grid stays unmodified). Pure: no\n * mutation, no DOM access.\n */\n build(config: PivotConfig<TData>): PivotResult<TFeatures>\n /**\n * Build a pivot from an arbitrary array (not necessarily the grid's\n * data). Useful for previewing a designer's config against a sample\n * before committing.\n */\n buildFrom<TIn extends RowData>(\n data: ReadonlyArray<TIn>,\n config: PivotConfig<TIn>,\n ): PivotResult<TFeatures>\n}\n```\n\n### `type EnterpriseGridApi`\n\nThe grid API plus everything enterprise adds - what `installEnterprise` hands back.\n\n```ts\nexport type EnterpriseGridApi<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = SvGridApi<TFeatures, TData> & {\n /** Export the current visible rows to the chosen format. Returns the built\n * file ({@link ExportResult}) for the dependency-free paths (undefined for\n * the vendored-writer xlsx paths, which download directly). */\n exportData(opts: ExportOptions<TData>): Promise<ExportResult | undefined>\n /** Copy the grid (view / selection / all) to the clipboard in a native text\n * format (default `tsv`, pastes into Excel / Sheets as columns). */\n copyExport(opts?: ClipboardExportOptions<TData>): Promise<void>\n /** Open a printable view of the current visible rows in a new window. */\n print(opts?: PrintOptions<TData>): Promise<void>\n /** Read an Excel / CSV / TSV / JSON file (or inline text) into typed\n * rows. Caller decides whether to commit into the grid or preview\n * the parsed result first via the returned `ImportResult`. */\n importData(opts: ImportOptions<TData>): Promise<ImportResult<TData>>\n /** AI helpers (Pro). All calls route through a consumer-registered\n * AIProvider via setAIProvider(); no model client is bundled. */\n ai: EnterpriseAIApi<TData>\n /** Pivot table builder (Pro). Pure - returns `{ rows, columns }` you\n * hand to a separate `<SvGrid>` instance. */\n pivot: EnterprisePivotApi<TFeatures, TData>\n}\n```\n\n### `function installEnterprise`\n\nAugment a SvGridApi instance with Pro methods (`exportData`, `print`,\n`ai.*`). Mutates and returns the same object so existing references\nkeep working.\n\nIf no license key has been set, the Pro methods still function but the\ngrid shows a small \"unlicensed\" watermark linking to jqwidgets.com and\nthe console emits a one-time nudge. Revoked or malformed keys throw on\nfirst call.\n\n```ts\nexport function installEnterprise<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(api: SvGridApi<TFeatures, TData>): EnterpriseGridApi<TFeatures, TData> {\n const pro = api as EnterpriseGridApi<TFeatures, TData>\n pro.exportData = (opts) => exportGrid(pro, opts)\n pro.copyExport = (opts) => copyExportToClipboard(pro, opts)\n pro.print = (opts) => printGrid(pro, opts)\n pro.importData = (opts) => importData(pro, opts)\n pro.ai = {\n filter: (query, opts) => aiFilter(pro, query, opts),\n smartFill: (opts) => aiSmartFill(pro, opts),\n summarize: (opts) => aiSummarize(pro, opts),\n classify: (opts) => aiClassify(pro, opts),\n export: (query, opts) => aiExport(pro, query, opts),\n findAnomalies: (opts) => aiFindAnomalies(pro, opts),\n chart: (query, opts) => aiChart(pro, query, opts),\n }\n // Wire the built-in chart panel's AI button (no-op without the `charting` prop).\n enableAiCharting(pro)\n // Register the scheduler / calendar view (no-op without the `scheduler` prop).\n enableSchedulerView()\n // Register the Kanban board view (no-op without the `board` prop).\n enableBoardView()\n // Register the gallery view (no-op without the `gallery` prop).\n enableGalleryView()\n // Register the Gantt view (no-op without the `gantt` prop).\n enableGanttView()\n enableSelectionBar()\n // Register the export engine so built-in AI exports (aiExport) can write the\n // enterprise formats (xlsx / pdf / ...); free grids without it get the plan only.\n registerExportProvider(exportGrid as never)\n enablePivot()\n enableAdvancedFilter()\n // Register the Excel keymap (Ctrl+Arrow, Ctrl+D, Ctrl+A and the rest). The\n // grid interprets a key itself only when nothing claims it, so a free grid\n // is unaffected.\n enableSheet()\n // Raise the unlicensed nudge for the server-side row model. No registry to fill -\n // the model hands the grid ordinary rows - so this only nudges when unlicensed.\n enableServerRowModel()\n pro.pivot = {\n build: (config) =>\n createPivotModel<TFeatures, TData>(pro.getData(), config),\n buildFrom: <TIn extends RowData>(data: ReadonlyArray<TIn>, config: PivotConfig<TIn>) =>\n // PivotConfig is variance-strict in TIn; the runtime call only needs\n // the row shape to match config.rows / config.cols field names, which\n // the caller-side generic enforces.\n createPivotModel<TFeatures, TIn>(data, config),\n }\n // Surface the unlicensed state at install time so the watermark appears\n // alongside the grid, not just after the user clicks Export.\n if (!hasValidLicense()) emitUnlicensedNudge()\n return pro\n}\n```\n"
7688
+ "markdown": "# `@svgrid/enterprise` · `install.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\install.ts`.\n\n### `type EnterpriseAIApi`\n\nThe `api.ai.*` namespace added by the enterprise install.\n\n```ts\nexport type EnterpriseAIApi<TData extends RowData> = {\n /** Natural-language -> filter + sort plan (and optionally apply it). */\n filter(query: string, opts?: AIFilterOptions): Promise<AIFilterResult>\n /** Propose values for empty cells based on a few worked examples. */\n smartFill<TValue = unknown>(opts: AISmartFillOptions): Promise<AISmartFillResult<TValue>>\n /** One-paragraph + bullets summary of a row, selection, group, or the whole view. */\n summarize(opts: AISummarizeOptions): Promise<AISummary>\n /** Classify free-text cells into one of a known set of labels. */\n classify(opts: AIClassifyOptions): Promise<AIClassifyResult>\n /** Natural-language export: \"export EU orders from Q2 as a grouped PDF\". */\n export(query: string, opts?: AIExportOptions): Promise<AIExportPlan>\n /** Scan a slice for anomalies / outliers, returning a structured list. */\n findAnomalies(opts?: AIAnomalyOptions): Promise<AIAnomalyResult>\n /** Natural-language chart: \"revenue by region, stacked by product\". */\n chart(query: string, opts?: AIChartOptions): Promise<AIChartPlan>\n // TData is referenced so the type stays bound to the row shape even\n // though the helpers all read through `api.getData()`. Lets callers\n // get correct inference downstream without explicit generics.\n readonly _rowType?: TData\n}\n```\n\n### `type EnterprisePivotApi`\n\nThe `api.pivot.*` namespace added by the enterprise install.\n\n```ts\nexport type EnterprisePivotApi<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = {\n /**\n * Build a pivot row/column model from the grid's current data. Returns\n * `{ rows, columns }` you can feed to a separate `<SvGrid>` instance\n * (the typical pattern - the source grid stays unmodified). Pure: no\n * mutation, no DOM access.\n */\n build(config: PivotConfig<TData>): PivotResult<TFeatures>\n /**\n * Build a pivot from an arbitrary array (not necessarily the grid's\n * data). Useful for previewing a designer's config against a sample\n * before committing.\n */\n buildFrom<TIn extends RowData>(\n data: ReadonlyArray<TIn>,\n config: PivotConfig<TIn>,\n ): PivotResult<TFeatures>\n}\n```\n\n### `type EnterpriseGridApi`\n\nThe grid API plus everything enterprise adds - what `installEnterprise` hands back.\n\n```ts\nexport type EnterpriseGridApi<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = SvGridApi<TFeatures, TData> & {\n /** Export the current visible rows to the chosen format. Returns the built\n * file ({@link ExportResult}) for the dependency-free paths (undefined for\n * the vendored-writer xlsx paths, which download directly). */\n exportData(opts: ExportOptions<TData>): Promise<ExportResult | undefined>\n /** Copy the grid (view / selection / all) to the clipboard in a native text\n * format (default `tsv`, pastes into Excel / Sheets as columns). */\n copyExport(opts?: ClipboardExportOptions<TData>): Promise<void>\n /** Open a printable view of the current visible rows in a new window. */\n print(opts?: PrintOptions<TData>): Promise<void>\n /** Read an Excel / CSV / TSV / JSON file (or inline text) into typed\n * rows. Caller decides whether to commit into the grid or preview\n * the parsed result first via the returned `ImportResult`. */\n importData(opts: ImportOptions<TData>): Promise<ImportResult<TData>>\n /** AI helpers (Pro). All calls route through a consumer-registered\n * AIProvider via setAIProvider(); no model client is bundled. */\n ai: EnterpriseAIApi<TData>\n /** Pivot table builder (Pro). Pure - returns `{ rows, columns }` you\n * hand to a separate `<SvGrid>` instance. */\n pivot: EnterprisePivotApi<TFeatures, TData>\n}\n```\n\n### `function installEnterprise`\n\nAugment a SvGridApi instance with Pro methods (`exportData`, `print`,\n`ai.*`). Mutates and returns the same object so existing references\nkeep working.\n\nIf no license key has been set, the Pro methods still function but the\ngrid shows a small \"unlicensed\" watermark linking to jqwidgets.com and\nthe console emits a one-time nudge. Revoked or malformed keys throw on\nfirst call.\n\n```ts\nexport function installEnterprise<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(api: SvGridApi<TFeatures, TData>): EnterpriseGridApi<TFeatures, TData>\n```\n"
7681
7689
  },
7682
7690
  {
7683
7691
  "slug": "reference/auto/svgrid-enterprise-pivot-chart",
7684
7692
  "path": "docs/reference/auto/svgrid-enterprise-pivot-chart.md",
7685
7693
  "title": "@svgrid/enterprise · pivot-chart.ts",
7686
7694
  "section": "API reference",
7687
- "markdown": "# `@svgrid/enterprise` · `pivot-chart.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\pivot-chart.ts`.\n\n### `type PivotChartOptions`\n\nOptions for {@link pivotToChartSpec}: the chart type and stacking, whether totals chart, a category cap, the measure's format and the value-axis name.\n\n```ts\nexport type PivotChartOptions = {\n /** Chart type. Default `'bar'`. */\n type?: ChartType\n /** Stack the series. Default false. */\n stacked?: boolean\n /** Stack to 100%. Implies `stacked`. Default false. */\n stacked100?: boolean\n /** Include the grand-total column / row as a series / category. Default false. */\n includeTotals?: boolean\n /** Cap the number of categories (row leaves) charted. */\n maxCategories?: number\n /**\n * The measure's cell format, carried to the chart as `valueFormat` (with\n * `currency` and `locale`), so a cell the table shows as \"$469,662\" charts\n * as \"$470k\" on the axis and \"$469,662\" in the tooltip rather than \"470k\".\n * The designer passes the first value chip's format; with several\n * measures in different formats, pass none and the chart formats plainly.\n */\n format?: CellFormatConfig\n /**\n * Name the value axis. Default: the measure's label when the layout has\n * one measure, nothing otherwise.\n */\n yAxisTitle?: string | null\n}\n```\n\n### `function pivotToChartSpec`\n\nA computed pivot as a `ChartSpec` for the free chart: row leaves become\ncategories (nested rows a grouped axis), column leaves the series, totals\nleft out unless asked for, the measure's format carried over and an empty\ncell read as a gap. The designer's Chart view is this function, and the\ngrid's own Chart panel runs the same mapping (`pivotResultToChartSpec` in\n`@svgrid/grid`) in pivot mode.\n\n```ts\nexport function pivotToChartSpec<TFeatures extends TableFeatures>(\n result: PivotResult<TFeatures>,\n opts: PivotChartOptions = {},\n): ChartSpec {\n return pivotResultToChartSpec(result as unknown as PivotResultLike, opts)\n}\n```\n"
7695
+ "markdown": "# `@svgrid/enterprise` · `pivot-chart.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\pivot-chart.ts`.\n\n### `type PivotChartOptions`\n\nOptions for {@link pivotToChartSpec}: the chart type and stacking, whether totals chart, a category cap, the measure's format and the value-axis name.\n\n```ts\nexport type PivotChartOptions = {\n /** Chart type. Default `'bar'`. */\n type?: ChartType\n /** Stack the series. Default false. */\n stacked?: boolean\n /** Stack to 100%. Implies `stacked`. Default false. */\n stacked100?: boolean\n /** Include the grand-total column / row as a series / category. Default false. */\n includeTotals?: boolean\n /** Cap the number of categories (row leaves) charted. */\n maxCategories?: number\n /**\n * The measure's cell format, carried to the chart as `valueFormat` (with\n * `currency` and `locale`), so a cell the table shows as \"$469,662\" charts\n * as \"$470k\" on the axis and \"$469,662\" in the tooltip rather than \"470k\".\n * The designer passes the first value chip's format; with several\n * measures in different formats, pass none and the chart formats plainly.\n */\n format?: CellFormatConfig\n /**\n * Name the value axis. Default: the measure's label when the layout has\n * one measure, nothing otherwise.\n */\n yAxisTitle?: string | null\n}\n```\n\n### `function pivotToChartSpec`\n\nA computed pivot as a `ChartSpec` for the free chart: row leaves become\ncategories (nested rows a grouped axis), column leaves the series, totals\nleft out unless asked for, the measure's format carried over and an empty\ncell read as a gap. The designer's Chart view is this function, and the\ngrid's own Chart panel runs the same mapping (`pivotResultToChartSpec` in\n`@svgrid/grid`) in pivot mode.\n\n```ts\nexport function pivotToChartSpec<TFeatures extends TableFeatures>(\n result: PivotResult<TFeatures>,\n opts: PivotChartOptions = {},\n): ChartSpec\n```\n"
7688
7696
  },
7689
7697
  {
7690
7698
  "slug": "reference/auto/svgrid-enterprise-pivot",
7691
7699
  "path": "docs/reference/auto/svgrid-enterprise-pivot.md",
7692
7700
  "title": "@svgrid/enterprise · pivot.ts",
7693
7701
  "section": "API reference",
7694
- "markdown": "# `@svgrid/enterprise` · `pivot.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\pivot.ts`.\n\n### `type PivotAggregatorId`\n\nBuilt-in pivot measures, named in {@link PivotValueConfig}.\n\n```ts\nexport type PivotAggregatorId =\n | 'sum'\n | 'avg'\n | 'min'\n | 'max'\n | 'count'\n | 'countDistinct'\n | 'first'\n | 'last'\n```\n\n### `type PivotAggregator`\n\nA custom measure: reduce the values under one cell to the number to display.\n\n```ts\nexport type PivotAggregator = (values: ReadonlyArray<unknown>) => unknown\n```\n\n### `type PivotValueConfig`\n\nOne measure: the field to aggregate and how to aggregate it.\n\n```ts\nexport type PivotValueConfig<TData> = {\n /** Row field whose values get aggregated. */\n field: keyof TData & string\n /** Built-in aggregator id, or a custom reducer. */\n agg: PivotAggregatorId | PivotAggregator\n /** Display name in the column header. Defaults to `${field} (${agg})`. */\n label?: string\n /** Optional cell formatter. */\n format?: CellFormatConfig\n}\n```\n\n### `type PivotConfig`\n\nA pivot definition: the row axis, the column axis, and the measures at their intersections.\n\n```ts\nexport type PivotConfig<TData> = {\n /** Outer-most first. Each entry becomes one level of row grouping. */\n rows: ReadonlyArray<keyof TData & string>\n /** Outer-most first. Each entry becomes one level of column grouping. */\n cols: ReadonlyArray<keyof TData & string>\n /** One or more measures aggregated under each column-axis leaf. */\n values: ReadonlyArray<PivotValueConfig<TData>>\n /** Grand-total row at the bottom. Default `true`. */\n grandTotalRow?: boolean\n /** Grand-total column on the right. Default `true`. */\n grandTotalCol?: boolean\n /** Subtotal rows between row groups. Default `true`. */\n rowSubtotals?: boolean\n /** Optional sort for column-axis values per dim level (defaults to alpha). */\n colSort?: (a: unknown, b: unknown, level: number) => number\n /** Optional sort for row-axis values per dim level (defaults to alpha). */\n rowSort?: (a: unknown, b: unknown, level: number) => number\n}\n```\n\n### `type PivotRowKind`\n\nWhat a pivot row represents - a group header, a subtotal, a leaf, or the grand total.\n\n```ts\nexport type PivotRowKind = 'group' | 'subtotal' | 'leaf' | 'grandTotal'\n```\n\n### `type PivotRow`\n\nShape of one entry in `result.rows`. The first-column label lives at\n`__pivotLabel`; every value cell lives at the column id matching the\nleaf column generated for its (col-path × measure).\n\n`__pivotParentId` is the `__pivotId` of the row's row-axis parent\n(or `null` for top-level groups, the grand-total row, and the one\nsynthetic \"All\" row when no row dims are configured). Use it with\n`filterCollapsedPivotRows` to hide leaves whose ancestor is\ncollapsed - that's how expandable pivots are built on top of the\nmodel.\n\n`__pivotExpandable` is `true` for `group` rows that have at least\none descendant. A renderer uses this to decide whether to show a\nchevron next to the label.\n\n```ts\nexport type PivotRow = {\n __pivotId: string\n __pivotKind: PivotRowKind\n __pivotDepth: number\n __pivotLabel: string\n __pivotParentId: string | null\n __pivotExpandable: boolean\n /** Aggregated value cells - keyed by leaf column id. */\n [columnId: string]: unknown\n}\n```\n\n### `type PivotResult`\n\nA built pivot: the rows to display, and the generated column definitions for its column axis.\n\n```ts\nexport type PivotResult<TFeatures extends TableFeatures> = {\n rows: PivotRow[]\n columns: Array<ColumnDef<TFeatures, PivotRow>>\n}\n```\n\n### `function createPivotModel`\n\nBuild a pivot table from flat rows: cross the row axis with the column axis,\naggregate each intersection, and return rows plus generated columns ready to\nhand to `<SvGrid>`.\n\n```ts\nexport function createPivotModel<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n data: ReadonlyArray<TData>,\n config: PivotConfig<TData>,\n): PivotResult<TFeatures> {\n if (config.values.length === 0) {\n throw new Error('pivot: at least one value config is required')\n }\n\n const rowFields = config.rows as ReadonlyArray<string>\n const colFields = config.cols as ReadonlyArray<string>\n const values = config.values as ReadonlyArray<PivotValueConfig<unknown>>\n\n // 1. axis trees\n const rowRoot = buildAxisTree(data, rowFields, config.rowSort)\n const colRoot = buildAxisTree(data, colFields, config.colSort)\n\n // 2. collect col-axis leaf paths (one per value column header chain)\n const colLeafPaths: Array<ReadonlyArray<unknown>> = []\n collectColLeafPaths(colRoot, colLeafPaths)\n\n // 3. flatten row-axis to pivot rows\n const rows: PivotRow[] = []\n if (rowFields.length === 0) {\n // No row dims: one synthetic \"All\" row.\n rows.push({\n __pivotId: 'row__all',\n __pivotKind: 'leaf',\n __pivotDepth: 0,\n __pivotLabel: '(All)',\n __pivotParentId: null,\n __pivotExpandable: false,\n ...computeRowValues(\n data as unknown as ReadonlyArray<Record<string, unknown>>,\n colLeafPaths,\n colFields,\n values,\n config.grandTotalCol !== false,\n ),\n })\n } else {\n walkRowTree(\n rowRoot, rows, colLeafPaths, colFields, values,\n config as PivotConfig<unknown>, rowFields, null,\n )\n }\n\n // 4. grand-total row at bottom\n if (config.grandTotalRow !== false) {\n rows.push({\n __pivotId: 'row__grand_total',\n __pivotKind: 'grandTotal',\n __pivotDepth: 0,\n __pivotLabel: 'Grand total',\n __pivotParentId: null,\n __pivotExpandable: false,\n ...computeRowValues(\n data as unknown as ReadonlyArray<Record<string, unknown>>,\n colLeafPaths,\n colFields,\n values,\n config.grandTotalCol !== false,\n ),\n })\n }\n\n // 5. column tree\n const columns = buildColumnTree<TFeatures>(\n colRoot,\n values,\n config as PivotConfig<unknown>,\n rowFields.length > 0 ? rowFields.join(' / ') : '',\n )\n\n return { rows, columns }\n}\n```\n\n### `const pivotAggregators`\n\nPublic registry of built-in aggregators. Useful for surfacing the\navailable options in a pivot designer UI.\n\n```ts\nexport const pivotAggregators: Record<PivotAggregatorId, PivotAggregator> = { ...BUILT_IN_AGGS }\n```\n\n### `function filterCollapsedPivotRows`\n\nFilter a `result.rows` array down to only the rows the user should\nsee given the current expansion state. A row stays in the output if\nits entire ancestor chain (via `__pivotParentId`) is in `expandedIds`.\n\nPass `true` to bypass filtering (everything visible - the default\nshape `createPivotModel` already returns). Pass an empty array /\nempty Set to collapse every group to its subtotal row.\n\nThe result is a new array; the input is not mutated.\n\n```ts\nexport function filterCollapsedPivotRows(\n rows: ReadonlyArray<PivotRow>,\n expandedIds: ReadonlyArray<string> | Set<string> | true,\n): PivotRow[] {\n if (expandedIds === true) return rows.slice()\n const expanded =\n expandedIds instanceof Set ? expandedIds : new Set(expandedIds)\n // Parent-of index so the ancestor walk is O(depth) instead of O(rows × depth).\n const parentOf = new Map<string, string | null>()\n for (const r of rows) parentOf.set(r.__pivotId, r.__pivotParentId)\n\n const out: PivotRow[] = []\n for (const row of rows) {\n // The grand-total row, top-level groups, and the (All) row are\n // always visible (their parent is null).\n if (row.__pivotParentId === null) {\n out.push(row)\n continue\n }\n let parentId: string | null = row.__pivotParentId\n let visible = true\n while (parentId !== null) {\n if (!expanded.has(parentId)) { visible = false; break }\n parentId = parentOf.get(parentId) ?? null\n }\n if (visible) out.push(row)\n }\n return out\n}\n```\n"
7702
+ "markdown": "# `@svgrid/enterprise` · `pivot.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\pivot.ts`.\n\n### `type PivotAggregatorId`\n\nBuilt-in pivot measures, named in {@link PivotValueConfig}.\n\n```ts\nexport type PivotAggregatorId =\n | 'sum'\n | 'avg'\n | 'min'\n | 'max'\n | 'count'\n | 'countDistinct'\n | 'first'\n | 'last'\n```\n\n### `type PivotAggregator`\n\nA custom measure: reduce the values under one cell to the number to display.\n\n```ts\nexport type PivotAggregator = (values: ReadonlyArray<unknown>) => unknown\n```\n\n### `type PivotValueConfig`\n\nOne measure: the field to aggregate and how to aggregate it.\n\n```ts\nexport type PivotValueConfig<TData> = {\n /** Row field whose values get aggregated. */\n field: keyof TData & string\n /** Built-in aggregator id, or a custom reducer. */\n agg: PivotAggregatorId | PivotAggregator\n /** Display name in the column header. Defaults to `${field} (${agg})`. */\n label?: string\n /** Optional cell formatter. */\n format?: CellFormatConfig\n}\n```\n\n### `type PivotConfig`\n\nA pivot definition: the row axis, the column axis, and the measures at their intersections.\n\n```ts\nexport type PivotConfig<TData> = {\n /** Outer-most first. Each entry becomes one level of row grouping. */\n rows: ReadonlyArray<keyof TData & string>\n /** Outer-most first. Each entry becomes one level of column grouping. */\n cols: ReadonlyArray<keyof TData & string>\n /** One or more measures aggregated under each column-axis leaf. */\n values: ReadonlyArray<PivotValueConfig<TData>>\n /** Grand-total row at the bottom. Default `true`. */\n grandTotalRow?: boolean\n /** Grand-total column on the right. Default `true`. */\n grandTotalCol?: boolean\n /** Subtotal rows between row groups. Default `true`. */\n rowSubtotals?: boolean\n /** Optional sort for column-axis values per dim level (defaults to alpha). */\n colSort?: (a: unknown, b: unknown, level: number) => number\n /** Optional sort for row-axis values per dim level (defaults to alpha). */\n rowSort?: (a: unknown, b: unknown, level: number) => number\n}\n```\n\n### `type PivotRowKind`\n\nWhat a pivot row represents - a group header, a subtotal, a leaf, or the grand total.\n\n```ts\nexport type PivotRowKind = 'group' | 'subtotal' | 'leaf' | 'grandTotal'\n```\n\n### `type PivotRow`\n\nShape of one entry in `result.rows`. The first-column label lives at\n`__pivotLabel`; every value cell lives at the column id matching the\nleaf column generated for its (col-path × measure).\n\n`__pivotParentId` is the `__pivotId` of the row's row-axis parent\n(or `null` for top-level groups, the grand-total row, and the one\nsynthetic \"All\" row when no row dims are configured). Use it with\n`filterCollapsedPivotRows` to hide leaves whose ancestor is\ncollapsed - that's how expandable pivots are built on top of the\nmodel.\n\n`__pivotExpandable` is `true` for `group` rows that have at least\none descendant. A renderer uses this to decide whether to show a\nchevron next to the label.\n\n```ts\nexport type PivotRow = {\n __pivotId: string\n __pivotKind: PivotRowKind\n __pivotDepth: number\n __pivotLabel: string\n __pivotParentId: string | null\n __pivotExpandable: boolean\n /** Aggregated value cells - keyed by leaf column id. */\n [columnId: string]: unknown\n}\n```\n\n### `type PivotResult`\n\nA built pivot: the rows to display, and the generated column definitions for its column axis.\n\n```ts\nexport type PivotResult<TFeatures extends TableFeatures> = {\n rows: PivotRow[]\n columns: Array<ColumnDef<TFeatures, PivotRow>>\n}\n```\n\n### `function createPivotModel`\n\nBuild a pivot table from flat rows: cross the row axis with the column axis,\naggregate each intersection, and return rows plus generated columns ready to\nhand to `<SvGrid>`.\n\n```ts\nexport function createPivotModel<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n data: ReadonlyArray<TData>,\n config: PivotConfig<TData>,\n): PivotResult<TFeatures>\n```\n\n### `const pivotAggregators`\n\nPublic registry of built-in aggregators. Useful for surfacing the\navailable options in a pivot designer UI.\n\n```ts\nexport const pivotAggregators: Record<PivotAggregatorId, PivotAggregator> = { ...BUILT_IN_AGGS }\n```\n\n### `function filterCollapsedPivotRows`\n\nFilter a `result.rows` array down to only the rows the user should\nsee given the current expansion state. A row stays in the output if\nits entire ancestor chain (via `__pivotParentId`) is in `expandedIds`.\n\nPass `true` to bypass filtering (everything visible - the default\nshape `createPivotModel` already returns). Pass an empty array /\nempty Set to collapse every group to its subtotal row.\n\nThe result is a new array; the input is not mutated.\n\n```ts\nexport function filterCollapsedPivotRows(\n rows: ReadonlyArray<PivotRow>,\n expandedIds: ReadonlyArray<string> | Set<string> | true,\n): PivotRow[]\n```\n"
7703
+ },
7704
+ {
7705
+ "slug": "reference/auto/svgrid-enterprise-review-adapters",
7706
+ "path": "docs/reference/auto/svgrid-enterprise-review-adapters.md",
7707
+ "title": "@svgrid/enterprise · review/adapters.ts",
7708
+ "section": "API reference",
7709
+ "markdown": "# `@svgrid/enterprise` · `review/adapters.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\review\\adapters.ts`.\n\n### `type AdapterResult`\n\nA change set built from another tool's output, ready for `review.add`, with\na count of the predictions that could not become proposals.\n\n```ts\nexport type AdapterResult = {\n source: ProposalSource\n title: string\n proposals: ProposalInput[]\n /** Predictions dropped: an index outside the request or the snapshot. */\n dropped: number\n}\n```\n\n### `const blankTargets`\n\nBlank cells of `field`: what `aiSmartFill` targets when given no indices.\n\n```ts\nexport const blankTargets = (snapshot: ReadonlyArray<unknown>, field: string): number[] => ...\n```\n\n### `function fromSmartFill`\n\nProposals from an `aiSmartFill` result, its row indices resolved to row ids\nthrough the snapshot the call ran on.\n\n```ts\nexport function fromSmartFill<TData>(\n result: AISmartFillResult,\n snapshot: ReadonlyArray<TData>,\n opts: { api: RowIdApi; targets?: ReadonlyArray<number>; source?: ProposalSource },\n): AdapterResult\n```\n\n### `function fromClassify`\n\nProposals from an `aiClassify` result, its row indices resolved to row ids\nthrough the snapshot the call ran on.\n\n```ts\nexport function fromClassify<TData>(\n result: AIClassifyResult,\n snapshot: ReadonlyArray<TData>,\n opts: { api: RowIdApi; targets?: ReadonlyArray<number>; source?: ProposalSource },\n): AdapterResult\n```\n\n### `function fromRows`\n\nDiff incoming rows (an import, a sync) against the grid's data by `key`:\none proposal per field that differs. Incoming rows with no match, and\nfields not in `fields` when it is given, are not proposed; unmatched rows\nare returned so the app can show them (adding rows comes in a later release).\n\n```ts\nexport function fromRows<TData>(\n incoming: ReadonlyArray<Partial<TData>>,\n opts: {\n api: Pick<ReviewGridApi, 'getOption' | 'getData'>\n key: keyof TData & string\n source: ProposalSource\n title?: string\n fields?: ReadonlyArray<keyof TData & string>\n },\n): AdapterResult & { unmatched: Array<Partial<TData>> }\n```\n\n### `function reviewSmartFill`\n\nSnapshot, run `aiSmartFill`, and add the result to `review` as proposals.\n\n```ts\nexport async function reviewSmartFill(\n review: Addable,\n api: ReviewGridApi,\n opts: AISmartFillOptions,\n): Promise<AdapterResult>\n```\n\n### `function reviewClassify`\n\nSnapshot, run `aiClassify`, and add the result to `review` as proposals.\n\n```ts\nexport async function reviewClassify(\n review: Addable,\n api: ReviewGridApi,\n opts: AIClassifyOptions,\n): Promise<AdapterResult>\n```\n\n### `function fromStaged`\n\nLift a `createStagedEditing` buffer into proposals, to route a person's\nstaged edits to someone else for approval instead of committing them.\n\nStaged editing has already written its values into the grid, and a\nproposal is checked against the value it saw (`before`). So revert the\nstage first (`stage.revert(...)`), then add these: the cells hold the\noriginal values again and the proposals carry the staged ones.\n\n```ts\nexport function fromStaged(\n changes: ReadonlyArray<{ rowId: string; columnId: string; original: unknown; staged: unknown }>,\n opts: { api: Pick<ReviewGridApi, 'getColumns'>; source: ProposalSource; title?: string },\n): AdapterResult\n```\n"
7710
+ },
7711
+ {
7712
+ "slug": "reference/auto/svgrid-enterprise-review-agent",
7713
+ "path": "docs/reference/auto/svgrid-enterprise-review-agent.md",
7714
+ "title": "@svgrid/enterprise · review/agent.ts",
7715
+ "section": "API reference",
7716
+ "markdown": "# `@svgrid/enterprise` · `review/agent.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\review\\agent.ts`.\n\n### `type GridTool`\n\nOne agent tool in the shape tool-use loops take: a name, a description, a\nJSON Schema for its input, and `execute`.\n\n```ts\nexport type GridTool = {\n name: string\n description: string\n /** JSON Schema of the input object. */\n inputSchema: Record<string, unknown>\n execute: (input: any) => Promise<unknown>\n}\n```\n\n### `type GridToolsOptions`\n\nOptions for `createGridTools`: the review edits are proposed into, the grid\napi, and the fields the agent may edit.\n\n```ts\nexport type GridToolsOptions = {\n review: ToolReview\n /** The grid api, or a getter for it. */\n api: ToolApi | (() => ToolApi | null | undefined)\n /** Who the proposals are from. Default: an agent named \"Agent\". */\n source?: ProposalSource\n /** Fields the agent may propose edits to. Default: every column with a field. */\n fields?: ReadonlyArray<string>\n /** Most rows one query returns. Default 200. */\n maxRows?: number\n /** Prefix for tool names. Default 'grid_'. */\n prefix?: string\n /** Most edits one grid_propose_edits call may carry. Default 500. */\n maxEdits?: number\n}\n```\n\n### `function createGridTools`\n\nThe tools an agent edits a grid through: `grid_describe`, `grid_query_rows`,\n`grid_propose_edits` and `grid_review_status`. None of them writes the data:\nedits arrive in the review as proposals for a person to accept.\n\n```ts\nexport function createGridTools(opts: GridToolsOptions): GridTool[]\n```\n\n### `function registerWebMcpTools`\n\nRegister tools with the browser's WebMCP API, so an agent driving the page\ncan call them. Experimental: WebMCP is a draft (`document.modelContext`,\nearlier `navigator.modelContext`), and this does nothing where it is\nmissing. Abort `signal`, or call `unregister`, to remove them.\n\n```ts\nexport function registerWebMcpTools(\n tools: ReadonlyArray<GridTool>,\n opts: { signal?: AbortSignal } = {},\n): { supported: boolean; unregister: () => void }\n```\n"
7717
+ },
7718
+ {
7719
+ "slug": "reference/auto/svgrid-enterprise-review-cluster",
7720
+ "path": "docs/reference/auto/svgrid-enterprise-review-cluster.md",
7721
+ "title": "@svgrid/enterprise · review/cluster.ts",
7722
+ "section": "API reference",
7723
+ "markdown": "# `@svgrid/enterprise` · `review/cluster.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\review\\cluster.ts`.\n\n### `type ClusterOptions`\n\nHow `clusterProposals` labels and splits groups: field labels, the size a\nscale group needs, the confidence below which a proposal counts as unsure,\nand the wording.\n\n```ts\nexport type ClusterOptions = {\n /** Wording of the group labels (the `label*`, `case*`, `punct*` keys); English by default. */\n messages?: Partial<ReviewMessages>\n /** The header to show for a field in group labels. Default: the field itself. */\n fieldLabel?: (field: string) => string\n /** Fewest members a `scale` group needs. Default 5. */\n minScale?: number\n /** Below this, a judgment group sorts with the risky ones. Default 0.6. */\n lowConfidence?: number\n}\n```\n\n### `function clusterProposals`\n\nGroup proposals by the change they make (trim, case, reformat, scale, one\nmapping, fill empty, one target, no pattern), the groups that need a person\nfirst. What the panel lists.\n\n```ts\nexport function clusterProposals(\n proposals: ReadonlyArray<Proposal>,\n opts: ClusterOptions = {},\n): ProposalGroup[]\n```\n\n### `function showValue`\n\nA value as a group label shows it: short, `(empty)` for blank, spaces\nvisible. A string is quoted only where the quotes tell something: around\nspaces at its ends, or when it reads as a number, a boolean or the blank mark.\n\n```ts\nexport function showValue(v: unknown, empty = '(empty)'): string\n```\n"
7724
+ },
7725
+ {
7726
+ "slug": "reference/auto/svgrid-enterprise-review-equal",
7727
+ "path": "docs/reference/auto/svgrid-enterprise-review-equal.md",
7728
+ "title": "@svgrid/enterprise · review/equal.ts",
7729
+ "section": "API reference",
7730
+ "markdown": "# `@svgrid/enterprise` · `review/equal.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\review\\equal.ts`.\n\n### `const isBlank`\n\nWhether a cell value is blank: null, undefined or the empty string.\n\n```ts\nexport const isBlank = (v: unknown): boolean => ...\n```\n\n### `function sameValue`\n\nWhether two cell values are the same for a review: `Object.is`, Dates by\ntime, arrays and plain objects by structure, and any two blanks.\n\n```ts\nexport function sameValue(a: unknown, b: unknown): boolean\n```\n"
7731
+ },
7732
+ {
7733
+ "slug": "reference/auto/svgrid-enterprise-review-formats",
7734
+ "path": "docs/reference/auto/svgrid-enterprise-review-formats.md",
7735
+ "title": "@svgrid/enterprise · review/formats.ts",
7736
+ "section": "API reference",
7737
+ "markdown": "# `@svgrid/enterprise` · `review/formats.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\review\\formats.ts`.\n\n### `const PENDING_BG`\n\nTheme it with `--sg-review-pending-bg`. The default is a light amber wash\nfrom `--sg-warning`, kept apart from the accent, which themes use for\nselection and focus.\n\n```ts\nexport const PENDING_BG = 'var(--sg-review-pending-bg, color-mix(in srgb, var(--sg-warning, #d97706) 13%, transparent))'\n```\n\n### `const PENDING_ICON`\n\nDrawn before the value, so a pending cell is never marked by colour alone.\n\n```ts\nexport const PENDING_ICON = '•'\n```\n\n### `const CONFLICT_BG`\n\nA cell two sources disagree on: a red wash (`--sg-review-conflict-bg`) and\na \"!\" before the value, so the grid shows where the panel's conflicts are.\n\n```ts\nexport const CONFLICT_BG = 'var(--sg-review-conflict-bg, color-mix(in srgb, var(--sg-danger, #dc2626) 12%, transparent))'\n```\n\n### `const CONFLICT_ICON`\n\nDrawn before the value of a cell two sources disagree on.\n\n```ts\nexport const CONFLICT_ICON = '!'\n```\n\n### `function pendingFormats`\n\n`conditionalFormats` rules that tint the cells of the given proposals, one\nrule per field, scoped to that field's columns. `review.formats` is built\nfrom it.\n\n```ts\nexport function pendingFormats<TData>(\n pending: ReadonlyArray<Proposal>,\n rowId: (row: TData, index: number) => string,\n columns: ReadonlyArray<{ id: string; field?: string }>,\n look: { background: string; icon: string } = { background: PENDING_BG, icon: PENDING_ICON },\n): ConditionalFormat<any>[]\n```\n"
7738
+ },
7739
+ {
7740
+ "slug": "reference/auto/svgrid-enterprise-review-ghost",
7741
+ "path": "docs/reference/auto/svgrid-enterprise-review-ghost.md",
7742
+ "title": "@svgrid/enterprise · review/ghost.ts",
7743
+ "section": "API reference",
7744
+ "markdown": "# `@svgrid/enterprise` · `review/ghost.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\review\\ghost.ts`.\n\n### `function canGhost`\n\nWhether wrapping this column's `cell` keeps the rest of its cells as they\nwere. `columns` is every leaf column, which a field type's fill may read.\n\n```ts\nexport function canGhost(raw: any, sample?: unknown, columns: ReadonlyArray<any> = []): boolean\n```\n"
7745
+ },
7746
+ {
7747
+ "slug": "reference/auto/svgrid-enterprise-review-messages",
7748
+ "path": "docs/reference/auto/svgrid-enterprise-review-messages.md",
7749
+ "title": "@svgrid/enterprise · review/messages.ts",
7750
+ "section": "API reference",
7751
+ "markdown": "# `@svgrid/enterprise` · `review/messages.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\review\\messages.ts`.\n\n### `const REVIEW_MESSAGES`\n\nEvery string change review shows: the panel, the group labels, the card and\ncell marks. English defaults; pass any subset as `createReview({ messages })`\n(and `<SvReviewPanel messages>` for one panel), unset keys stay English. The\nidiom of the grid's own `localization.text`: a flat map, `{name}`\nplaceholders. Kept free of imports: the clustering uses it in plain Node.\n\n```ts\nexport const REVIEW_MESSAGES = {\n // Panel header\n title: 'Review changes',\n decided: '{decided} of {total} decided',\n pendingInGroups: '{count} pending in {groups} groups',\n pendingInOneGroup: '{count} pending in 1 group',\n nothingPending: 'Nothing pending',\n inConflict: ', {count} in conflict',\n acceptAll: 'Accept all',\n rejectAll: 'Reject all',\n acceptRuleGroups: 'Accept rule groups ({count})',\n resolveFirst: 'Resolve the conflicts before accepting everything.',\n onlyRowsWithChanges: 'Only rows with changes',\n // Confirm\n confirmAcceptGroup: 'Accept {count} changes: {label}?',\n confirmRejectGroup: 'Reject {count} changes: {label}?',\n confirmAcceptAll: 'Accept all {count} changes?',\n confirmRejectAll: 'Reject all {count} changes?',\n confirmAcceptRules: 'Accept {groups} rule groups ({count} changes)?',\n confirmYes: 'Yes, {count}',\n cancel: 'Cancel',\n // Conflicts\n conflictsTitle: 'Two sources disagree',\n conflictCell: '{row}, {field}: now {value}',\n keep: 'Keep {value}',\n // Groups\n badgeRule: 'Rule',\n hintRule: 'Every change in this group follows the rule.',\n hintMapping: 'Check the mapping before accepting.',\n hintFill: 'Check the sample: the least sure ones come first.',\n hintConstant: 'Many different values set to one: check what they were.',\n hintEach: 'No shared pattern: look at each change.',\n oneChange: '{count} change',\n changes: '{count} changes',\n sure: '{pct} sure',\n sureRange: '{min} to {avg} sure',\n accept: 'Accept',\n reject: 'Reject',\n acceptGroupLabel: 'Accept {count}: {label}',\n rejectGroupLabel: 'Reject {count}: {label}',\n from: 'From',\n otherValues: 'other values',\n sampleOf: 'Sample of {count}',\n everyChange: 'Every change',\n firstN: 'First {count}',\n showRow: 'Show {row} in the grid',\n rowId: 'Row {row}',\n acceptOne: 'Accept this change',\n rejectOne: 'Reject this change',\n showAll: 'Show all {count}',\n keysHint: 'J / K move between groups, Enter opens one, A accepts it, R rejects it.',\n showInGrid: 'Show in grid',\n nextInGrid: 'Next in grid',\n hiddenRows: '{count} hidden by filters or grouping',\n // Empty and done\n allReviewed: 'All {count} reviewed',\n reviewedSummary: '{accepted} accepted, {rejected} rejected',\n reviewedStale: ', {count} not written because the cell changed',\n noProposals: 'No proposals yet',\n noProposalsHint: 'Edits an agent, an import or an AI helper proposes show up here, grouped by what they change.',\n notWritten: '{count} not written',\n rowField: '{row}, {field}',\n decidedLabel: 'Decided',\n // Why a proposal was not written or is waiting (shown in the panel)\n noteCellChanged: 'the cell changed after this was proposed',\n noteRowGone: 'the row no longer exists',\n noteRowEditing: 'the row is being edited',\n noteGridNotReady: 'the grid is not ready',\n noteSavedStale: 'saved, but the cell changed before it was written here',\n noteConflict: 'another source proposed a different value',\n undoHint: 'Ctrl+Z in the grid undoes the last decision.',\n // Announced after a decision\n announceAccepted: '{count} accepted',\n announceRejected: '{count} rejected',\n announceStale: '{count} not written: the cell changed',\n announceSkipped: '{count} left pending',\n announceCommittedStale: '{count} saved but not shown: the cell changed while saving',\n announceNotSaved: 'not saved: {error}',\n announceNothing: 'Nothing to decide',\n undoFailed: 'Undo not saved: {error}',\n redoFailed: 'Redo not saved: {error}',\n // Marks\n cardProposed: '{count} proposed',\n proposes: '{source} proposes {value}',\n nowValue: 'Now: {value}',\n empty: '(empty)',\n // Group labels ({field} is the column header)\n labelWhitespace: 'Trim spaces in {field}',\n labelCase: 'Change {field} to {case}',\n caseUpper: 'UPPER CASE',\n caseLower: 'lower case',\n caseTitle: 'Title Case',\n caseMixed: 'a different case',\n labelToNumber: 'Convert {field} text to numbers',\n labelDates: 'Reformat {field} dates as {shape}',\n datesAsDates: 'dates',\n labelShape: 'Reformat {field} as {shape}',\n labelPunct: '{change} in {field}',\n punctRemove: 'remove {chars}',\n punctAdd: 'add {chars}',\n punctSpaces: 'spaces',\n labelDivide: 'Divide {field} by {n}',\n labelMultiply: 'Multiply {field} by {n}',\n labelMapping: '{field}: {from} → {to}',\n mappingValues: '{count} values',\n labelFill: 'Fill empty {field} with {value}',\n labelFillVarious: 'Fill empty {field} (different values)',\n labelConstant: 'Set {field} to {value}',\n labelUnpatterned: '{field}: no shared pattern',\n}\n```\n\n### `type ReviewMessages`\n\nEvery string the review shows, with the keys of `REVIEW_MESSAGES`.\n\n```ts\nexport type ReviewMessages = typeof REVIEW_MESSAGES\n```\n"
7752
+ },
7753
+ {
7754
+ "slug": "reference/auto/svgrid-enterprise-review-model.svelte",
7755
+ "path": "docs/reference/auto/svgrid-enterprise-review-model.svelte.md",
7756
+ "title": "@svgrid/enterprise · review/model.svelte.ts",
7757
+ "section": "API reference",
7758
+ "markdown": "# `@svgrid/enterprise` · `review/model.svelte.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\review\\model.svelte.ts`.\n\n### `type ReviewGridApi`\n\nThe part of the grid api a review uses. Any `SvGridApi` satisfies it.\n\n```ts\nexport type ReviewGridApi = Pick<\n SvGridApi<any, any>,\n | 'getData' | 'getOption' | 'getActiveCell' | 'getRowId' | 'getColumns' | 'getCommandContext' | 'stopEditing' | 'scrollToRow' | 'getDisplayedRows'\n | 'getAdvancedFilter' | 'setAdvancedFilter'\n | 'getRowPosition' | 'getPageInfo' | 'setPage' | 'getState'\n```\n\n### `type ReviewOptions`\n\nOptions for `createReview`: the grid it reviews, how accepted values are\nwritten (`setRows`, or `server` with `onCommit`), and what to call as\ndecisions are made.\n\n```ts\nexport type ReviewOptions<TData> = {\n /** The grid api, or a getter for it (it is bound after mount). */\n api: ReviewGridApi | (() => ReviewGridApi | undefined | null)\n /** Replace the app's rows. Required unless `server` is set. Must apply synchronously. */\n setRows?: (next: TData[]) => void\n /**\n * Server row model: the controller passed to the grid as `rowModel`.\n * Accept and undo commit through `onCommit` and then refresh it.\n */\n server?: { refresh(): void }\n /** Persist accepted values. Reject (throw) to keep them pending. Required with `server`. */\n onCommit?: (accepted: Proposal[]) => void | Promise<void>\n /** Who decides, stamped on each decided proposal. */\n user?: string\n cluster?: ClusterOptions\n /** Wording of everything the review shows (panel, group labels, marks); English by default. */\n messages?: Partial<ReviewMessages>\n /**\n * Called after every decision, its undo and its redo, with copies of the\n * proposals it moved. Write these to an audit log of your own.\n */\n onDecision?: (decision: ReviewDecision) => void\n /**\n * Called as accepted values (or an undo / redo of them) are written, with\n * the proposals and the new rows just before they go to `setRows`, so\n * bookkeeping that edits a row lands in the same write. SvGrid Base stamps\n * \"last modified\" and notes the record's activity with\n * `baseReviewApplied(api)` from `@svgrid/enterprise/base`. With a server\n * row model there are no rows to edit: `rows` is undefined.\n */\n onApply?: (applied: Proposal[], how: 'accept' | 'undo' | 'redo', rows?: TData[]) => void\n /**\n * An undo or redo whose `onCommit` failed: nothing was written and the\n * decision stands. Also kept as `review.lastError`, which the panel announces.\n */\n onError?: (error: unknown, during: 'undo' | 'redo') => void\n /**\n * What names a row on the panel's lines, such as its company, so a reviewer\n * knows whose record a change is in. Default: the row's first visible text\n * column, left out when that column is the one the change is to.\n */\n rowLabel?: (row: TData) => string | null | undefined\n}\n```\n\n### `type ReviewDecision`\n\nOne decision, its undo or its redo, as `onDecision` receives it, with copies\nof the proposals it moved. Write these to an audit log.\n\n```ts\nexport type ReviewDecision = {\n action: 'accept' | 'reject' | 'undo' | 'redo'\n /** For undo / redo: which decision was undone or redone. */\n of?: 'accept' | 'reject'\n proposals: Proposal[]\n by?: string\n at: number\n}\n```\n\n### `type ReviewOutcome`\n\nWhat an accept or a reject did, by proposal id: accepted, rejected, stale\n(the cell changed before the write), committed and then found stale, or\nskipped; and what `onCommit` threw, if it did.\n\n```ts\nexport type ReviewOutcome = {\n accepted: string[]\n rejected: string[]\n /** The cell changed since the proposal was made, or its row is gone. Never written. */\n stale: string[]\n /** Left pending: the row is being edited, the proposal is already being accepted, or the grid is not ready. */\n skipped: string[]\n /**\n * Saved by `onCommit`, then not written here because the cell changed while\n * it was saving. The backend holds the proposed value; reload or save the\n * cell's value back.\n */\n committedStale: string[]\n /** What `onCommit` threw; nothing was written and the proposals stay pending. */\n error?: unknown\n}\n```\n\n### `type AddInput`\n\nA change set for `review.add`: where it came from, an optional title and\nid, and its proposals.\n\n```ts\nexport type AddInput = {\n source: ProposalSource\n title?: string\n id?: string\n proposals: ReadonlyArray<ProposalInput>\n}\n```\n\n### `type ReviewJSON`\n\nA review's change sets as `review.toJSON()` writes them and `review.load` /\n`review.merge` read them, to route a review to an approver.\n\n```ts\nexport type ReviewJSON = { v: 1; sets: ChangeSet[] }\n```\n\n### `interface Review`\n\nWhat `createReview` returns: the proposals, their groups, the decisions,\nand what the grid takes (`columns`, `formats`). Every read is reactive.\n\n```ts\nexport interface Review<TData = unknown> {\n /** Bumped on every change, for code that caches what it reads. */\n readonly version: number\n /** The wording in effect: English with `messages` laid over it. */\n readonly messages: ReviewMessages\n /** The last undo or redo whose save failed, or null. */\n readonly lastError: { error: unknown; during: 'undo' | 'redo'; at: number } | null\n /** Add a change set; a cell that already has a live proposal from another source becomes a conflict. */\n add(input: AddInput): ChangeSet\n /** One proposal by id. */\n get(id: string): Proposal | undefined\n /** Every proposal of the session, whatever its status. */\n proposals(): Proposal[]\n /** What names a proposal's row (`rowLabel`), or null. */\n rowLabel(p: Proposal): string | null\n /** A field's column header, as the group labels show it. */\n fieldLabel(field: string): string\n /** The proposals waiting for a decision. */\n pending(): Proposal[]\n /** The proposals two sources disagree on, to settle with `resolveConflict`. */\n conflicts(): Proposal[]\n /** The pending proposals grouped by the change they make, the groups that need a person first. */\n groups(): ProposalGroup[]\n /** The pending proposal for one cell, if there is one. */\n pendingFor(rowId: string, field: string): Proposal | undefined\n /** Write these proposals: checks each cell still holds `before`, before and after `onCommit`. One undo step. */\n accept(ids: ReadonlyArray<string>): Promise<ReviewOutcome>\n /** Decide against these proposals; nothing is written. One undo step. */\n reject(ids: ReadonlyArray<string>): ReviewOutcome\n /** Accept a group, limited to the ids the person was shown, so a proposal added since is not decided unseen. */\n acceptGroup(key: string, shownIds: ReadonlyArray<string>): Promise<ReviewOutcome>\n /** Reject a group, limited to the ids the person was shown. */\n rejectGroup(key: string, shownIds: ReadonlyArray<string>): ReviewOutcome\n /** Keep one of a cell's conflicting proposals (it becomes pending) and reject the rest, as one undo step. */\n resolveConflict(keepId: string): void\n /** `conditionalFormats` for the grid: pending cells tinted, conflicting cells marked, the row \"Show in grid\" lands on lit. */\n readonly formats: ConditionalFormat<any>[]\n /** The grid's columns with the proposed value drawn in each pending cell. */\n columns<C extends ReadonlyArray<any>>(cols: C): C\n /** Show the next proposal of `ids` after `fromId` in the grid, on whatever page it is. */\n reveal(ids: ReadonlyArray<string>, fromId?: string): { id: string | null; hidden: number }\n /** Show only rows with a pending or conflicting proposal, on top of the user's own filters. */\n showPendingOnly(on: boolean): void\n /** Whether `showPendingOnly` is on (the grid's own Clear turns it off too). */\n readonly pendingOnly: boolean\n /** Every set with its proposals and their status, as plain JSON; `setIds` exports only some. */\n toJSON(opts?: { setIds?: ReadonlyArray<string> }): ReviewJSON\n /** Replace everything with an export; returns how many malformed proposals were dropped. */\n load(json: ReviewJSON): { dropped: number }\n /** Add the sets of an export, keeping what is here; returns how many were dropped. */\n merge(json: ReviewJSON): { dropped: number }\n /** Every decided proposal (accepted, rejected or stale), oldest decision first. */\n log(): Proposal[]\n /** Propose undoing what a set wrote, as a new set to review; null when nothing of it was accepted. */\n revertSet(setId: string): ChangeSet | null\n /** The sets in this review, newest last, without their proposals. */\n sets(): Array<Omit<ChangeSet, 'proposals'> & { count: number }>\n /** Forget every proposal and set. */\n clear(): void\n}\n```\n\n### `function createReview`\n\nHold writes nobody typed (an agent's edits, an import, an AI helper's\noutput) as proposals, grouped by the change they make, and write them only\nwhen a person accepts them. Give the grid `review.columns(columns)` and\n`review.formats`, and render `<SvReviewPanel {review} />` beside it. Each\ndecision is one Ctrl+Z in the grid.\n\n```ts\nexport function createReview<TData = unknown>(opts: ReviewOptions<TData>): Review<TData>\n```\n"
7759
+ },
7760
+ {
7761
+ "slug": "reference/auto/svgrid-enterprise-review-types",
7762
+ "path": "docs/reference/auto/svgrid-enterprise-review-types.md",
7763
+ "title": "@svgrid/enterprise · review/types.ts",
7764
+ "section": "API reference",
7765
+ "markdown": "# `@svgrid/enterprise` · `review/types.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\review\\types.ts`.\n\n### `type ProposalSource`\n\nWhat produced a proposal. `id` keeps two runs of the same kind apart.\n\n```ts\nexport type ProposalSource = {\n kind: 'agent' | 'ai' | 'import' | 'bulk' | 'sync' | 'rule' | 'user'\n id: string\n label: string\n}\n```\n\n### `type ProposalStatus`\n\nWhere a proposal stands: waiting, accepted, rejected, stale (its cell\nchanged first), or in conflict with another source's proposal for the same\ncell.\n\n```ts\nexport type ProposalStatus = 'pending' | 'accepted' | 'rejected' | 'stale' | 'conflict'\n```\n\n### `type Proposal`\n\nOne proposed change to one cell, with where it came from and where it\nstands.\n\n```ts\nexport type Proposal = {\n id: string\n /** Only `update` in this release; inserts and deletes come later. */\n op: 'update'\n /** The grid's row id (its `getRowId`), never a row index. */\n rowId: string\n /** The field on the row object the value is written to. */\n field: string\n /** The value when the proposal was made, which is what staleness compares with. */\n before: unknown\n after: unknown\n source: ProposalSource\n /** Why, in the producer's words (an AI rationale, an import file name). */\n reason?: string\n /** 0..1, when the producer has one. */\n confidence?: number\n createdAt: number\n status: ProposalStatus\n /** Why a proposal is stale, skipped or in conflict, for the panel. */\n note?: string\n decidedBy?: string\n decidedAt?: number\n}\n```\n\n### `type ProposalInput`\n\nWhat a producer hands over: a proposal without the fields the review fills in.\n\n```ts\nexport type ProposalInput = Omit<Proposal, 'id' | 'op' | 'source' | 'createdAt' | 'status' | 'note' | 'decidedBy' | 'decidedAt'> & {\n id?: string\n confidence?: number\n}\n```\n\n### `type ChangeSet`\n\nOne batch from one producer.\n\n```ts\nexport type ChangeSet = {\n id: string\n title: string\n source: ProposalSource\n createdAt: number\n proposals: Proposal[]\n}\n```\n\n### `type GroupKind`\n\nHow a group's members relate. The first four are rule groups: every member\nis proven to follow the rule. The rest are judgment groups, where a person\nhas to look.\n\n```ts\nexport type GroupKind =\n | 'whitespace'\n | 'case'\n | 'format'\n | 'scale'\n | 'same-mapping'\n | 'fill-empty'\n | 'constant-target'\n | 'unpatterned'\n```\n\n### `type ProposalGroup`\n\nProposals that make the same change, as the panel lists them: a label, a\nkind, whether a rule proves every member, and a sample to check.\n\n```ts\nexport type ProposalGroup = {\n /** Stable while the group's members do not change: source, field, kind and param. */\n key: string\n kind: GroupKind\n /** True for the four rule kinds. */\n rule: boolean\n /** What the members share, in the detector's terms ('upper', '100', a value...). */\n param: string\n label: string\n field: string\n sourceId: string\n ids: string[]\n count: number\n /** Lowest and mean confidence over the members that have one; undefined when none do. */\n minConfidence?: number\n avgConfidence?: number\n /** Up to five ids to look at first: the least confident, then spread across the group. */\n sample: string[]\n /**\n * For `constant-target` and `same-mapping`: the five most common `before`\n * values and how many of each, then one `other` entry for the rest.\n */\n beforeDistribution?: Array<{ value: unknown; count: number; other?: true }>\n}\n```\n"
7695
7766
  },
7696
7767
  {
7697
7768
  "slug": "reference/auto/svgrid-enterprise-server-pivot",
7698
7769
  "path": "docs/reference/auto/svgrid-enterprise-server-pivot.md",
7699
7770
  "title": "@svgrid/enterprise · server/server-pivot.ts",
7700
7771
  "section": "API reference",
7701
- "markdown": "# `@svgrid/enterprise` · `server/server-pivot.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\server\\server-pivot.ts`.\n\n### `type PivotResultColumnOptions`\n\nHow `buildPivotResultColumns` names, sizes and post-processes the generated value columns.\n\n```ts\nexport type PivotResultColumnOptions = {\n /** The string between key segments and the value column. Default `_`. */\n separator?: string\n /** Header text for a value column. Default: the aggregation as `sum(amount)`. */\n valueHeader?: (aggregation: ServerAggregation) => string\n /**\n * Post-process each generated leaf column - set a width, a format, an align.\n * Receives the field it reads and the default definition.\n */\n pivotResultColumn?: (field: string, column: ColumnDef<any, any>) => ColumnDef<any, any>\n /** Width for a generated value column. Default 120. */\n width?: number\n /**\n * Append a header group of row totals after the pivot keys: one column\n * per aggregation reading the plain aggregate field (`amount`, not\n * `2024_amount`), which the backend puts on every group row in pivot\n * mode beside the per-key fields. `true` labels the group `Total`; a\n * string is the label.\n */\n rowTotals?: boolean | string\n}\n```\n\n### `function buildPivotResultColumns`\n\nParse `pivotResultFields` into a column tree. Fields whose suffix matches no\naggregation are skipped - they are not pivoted values.\n\n```ts\nexport function buildPivotResultColumns(\n fields: ReadonlyArray<string>,\n aggregations: ReadonlyArray<ServerAggregation>,\n options: PivotResultColumnOptions = {},\n): Array<ColumnDef<any, any>> {\n const sep = options.separator ?? '_'\n const width = options.width ?? 120\n const header = options.valueHeader ?? ((a) => `${a.fn}(${a.col})`)\n const root: Node = { key: '', children: new Map(), leaves: [] }\n\n // Longest aggregation column first, so `net_amount` wins over `amount` for\n // a field ending in `_net_amount`.\n const aggs = [...aggregations].sort((a, b) => b.col.length - a.col.length)\n\n for (const field of fields) {\n const agg = aggs.find((a) => field === a.col || field.endsWith(sep + a.col))\n if (!agg) continue\n const keyPart = field === agg.col ? '' : field.slice(0, field.length - agg.col.length - sep.length)\n const keys = keyPart === '' ? [] : keyPart.split(sep)\n let node = root\n for (const key of keys) {\n let next = node.children.get(key)\n if (!next) {\n next = { key, children: new Map(), leaves: [] }\n node.children.set(key, next)\n }\n node = next\n }\n node.leaves.push({ field, agg })\n }\n\n const leafColumn = (field: string, agg: ServerAggregation): ColumnDef<any, any> => {\n const base = { id: field, field, header: header(agg), width, align: 'right' } as ColumnDef<any, any>\n return options.pivotResultColumn ? options.pivotResultColumn(field, base) : base\n }\n\n const emit = (node: Node, path: string[]): Array<ColumnDef<any, any>> => {\n const out: Array<ColumnDef<any, any>> = []\n for (const child of node.children.values()) {\n const childPath = [...path, child.key]\n out.push({\n id: `pv_group_${childPath.join(sep)}`,\n header: child.key,\n columns: emit(child, childPath),\n } as unknown as ColumnDef<any, any>)\n }\n for (const leaf of node.leaves) out.push(leafColumn(leaf.field, leaf.agg))\n return out\n }\n\n const out = emit(root, [])\n if (options.rowTotals) {\n out.push({\n id: 'pv_group_total',\n header: typeof options.rowTotals === 'string' ? options.rowTotals : 'Total',\n columns: aggregations.map((a) => leafColumn(a.col, a)),\n } as unknown as ColumnDef<any, any>)\n }\n return out\n}\n```\n"
7772
+ "markdown": "# `@svgrid/enterprise` · `server/server-pivot.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\server\\server-pivot.ts`.\n\n### `type PivotResultColumnOptions`\n\nHow `buildPivotResultColumns` names, sizes and post-processes the generated value columns.\n\n```ts\nexport type PivotResultColumnOptions = {\n /** The string between key segments and the value column. Default `_`. */\n separator?: string\n /** Header text for a value column. Default: the aggregation as `sum(amount)`. */\n valueHeader?: (aggregation: ServerAggregation) => string\n /**\n * Post-process each generated leaf column - set a width, a format, an align.\n * Receives the field it reads and the default definition.\n */\n pivotResultColumn?: (field: string, column: ColumnDef<any, any>) => ColumnDef<any, any>\n /** Width for a generated value column. Default 120. */\n width?: number\n /**\n * Append a header group of row totals after the pivot keys: one column\n * per aggregation reading the plain aggregate field (`amount`, not\n * `2024_amount`), which the backend puts on every group row in pivot\n * mode beside the per-key fields. `true` labels the group `Total`; a\n * string is the label.\n */\n rowTotals?: boolean | string\n}\n```\n\n### `function buildPivotResultColumns`\n\nParse `pivotResultFields` into a column tree. Fields whose suffix matches no\naggregation are skipped - they are not pivoted values.\n\n```ts\nexport function buildPivotResultColumns(\n fields: ReadonlyArray<string>,\n aggregations: ReadonlyArray<ServerAggregation>,\n options: PivotResultColumnOptions = {},\n): Array<ColumnDef<any, any>>\n```\n"
7702
7773
  },
7703
7774
  {
7704
7775
  "slug": "reference/auto/svgrid-enterprise-server-row-model",
7705
7776
  "path": "docs/reference/auto/svgrid-enterprise-server-row-model.md",
7706
7777
  "title": "@svgrid/enterprise · server/server-row-model.ts",
7707
7778
  "section": "API reference",
7708
- "markdown": "# `@svgrid/enterprise` · `server/server-row-model.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\server\\server-row-model.ts`.\n\n### `type ServerLevelParams`\n\nPer-level cache settings, from `levelParams`.\n\n```ts\nexport type ServerLevelParams = {\n /** Rows per request at this level. Default: the model's `blockSize`. */\n blockSize?: number\n /** Loaded blocks to keep at this level. Default: the model's `maxBlocksInCache`. */\n maxBlocksInCache?: number\n /**\n * `false` loads the whole level as soon as it opens (block by block, still\n * under the concurrency cap) instead of waiting for the viewport. A level\n * that is fully loaded can also be sorted in the browser - see\n * `clientSideSort`.\n */\n infinite?: boolean\n /**\n * Children arrive one block at a time behind a \"Load N more\" row instead\n * of by scroll: the level shows what it has loaded, then a `more` row\n * while the server holds more. `loadMoreChildren(route)` - or the row's\n * own toggle - fetches the next block. Wins over `infinite`.\n */\n loadMore?: boolean\n /**\n * Rows this level claims before its first block lands, as placeholders.\n * Default: the model's `skeletonRows`. Set it to the count you expect at\n * the root of flat data and `api.scrollToRow(900000)` works before\n * anything has loaded: the scrollbar is already the right length, the\n * rows there are placeholders, and the block under them is what loads.\n */\n initialRowCount?: number\n}\n```\n\n### `type ServerRowModelPaginationOptions`\n\nPaging the top level instead of scrolling it. See `ServerRowModelOptions.pagination`.\n\n```ts\nexport type ServerRowModelPaginationOptions = {\n /** Rows per page. Default 100. */\n pageSize?: number\n /** Choices for the footer's page-size selector. */\n pageSizes?: number[]\n /**\n * Fit the page to the grid: as many rows as its body shows without\n * scrolling, re-measured when the grid resizes. `pageSize` is then the\n * size until the first measurement.\n */\n autoPageSize?: boolean\n /**\n * Count every row of the flattened tree towards the page, children\n * included. Off, a page is `pageSize` top-level rows, each shown with\n * whatever is open beneath it.\n */\n paginateChildRows?: boolean\n}\n```\n\n### `type ServerRowModelPagination`\n\nWhere the pager stands.\n\n```ts\nexport type ServerRowModelPagination = {\n pageIndex: number\n pageSize: number\n /** Top-level rows, or flattened rows with `paginateChildRows`. */\n rowCount: number\n pageCount: number\n}\n```\n\n### `type ServerLevelState`\n\nWhere a route's rows stand, for diagnostics.\n\n```ts\nexport type ServerLevelState = {\n route: string[]\n level: number\n rowCount: number | null\n lastRowKnown: boolean\n loading: boolean\n failedBlocks: number[]\n blocks: BlockState[]\n}\n```\n\n### `type ServerRowModelOptions`\n\nEverything `createServerRowModel` is built from: grouping, tree, pivot, blocks per level, totals, paging, selection, transactions and events.\n\n```ts\nexport type ServerRowModelOptions<TData> = {\n /** Columns to group on, outer to inner. Leave empty for a flat list or a tree. */\n groupBy?: string[]\n /** Value columns to roll up per group. */\n aggregations?: ServerAggregation[]\n /**\n * Server-side pivot: the columns whose distinct values become columns.\n * Takes effect with `pivotMode`; see `setPivot`.\n */\n pivotBy?: string[]\n pivotMode?: boolean\n /**\n * In pivot mode, a `Total` header group after the pivot keys with the\n * row's plain aggregates (`amount` beside `2024_amount`, `2025_amount`).\n * The backend puts those fields on every group row and on the grand\n * total in pivot mode; the reference sources do. A string is the label.\n */\n pivotRowTotals?: boolean | string\n /** How a backend joins pivot keys and the value column into a field name. Default `_`. */\n pivotFieldSeparator?: string\n /** Post-process each generated pivot value column. */\n pivotResultColumn?: PivotResultColumnOptions['pivotResultColumn']\n /**\n * Columns to put BEFORE the generated pivot columns in pivot mode -\n * the group column with its expander, typically. The pivot columns\n * replace the grid's `columns` wholesale, so this is where the\n * app's own leading columns come back in.\n */\n pivotLeadingColumns?: ReadonlyArray<unknown>\n /**\n * Self-referential tree: each row is a node whose children load on expand.\n * Needs `getRowId` (the node id, which builds the `groupKeys` path) and\n * `hasChildren`.\n */\n treeData?: boolean\n /** Stable row id. Needed for tree data, selection and transactions. */\n getRowId?: (row: TData) => string\n /** Tree data: whether a node can be expanded. */\n hasChildren?: (row: TData) => boolean\n /**\n * How many rows a group holds, read off its response row. Shown beside the\n * key, and used to size the group's scrollbar before its first block lands.\n */\n childCount?: (row: TData) => number | undefined\n /** Open a group as soon as it arrives. Receives the route and the row. */\n isGroupOpenByDefault?: (route: string[], row: TData) => boolean\n /** Per-level cache settings. Called once per route when its store is created. */\n levelParams?: (level: number, route: string[]) => ServerLevelParams\n /** Rows per request, unless `levelParams` says otherwise. Default 100. */\n blockSize?: number\n /** Loaded blocks to keep per level, unless `levelParams` says otherwise. Unlimited by default. */\n maxBlocksInCache?: number\n /** Requests open at once, across every level. Default 2. */\n maxConcurrentRequests?: number\n /** Wait for the scroll to settle this long before fetching. Default 0. */\n blockLoadDebounceMs?: number\n /**\n * Placeholder rows shown for a level before its first block lands - so an\n * expand never opens onto nothing. Default 3.\n */\n skeletonRows?: number\n /**\n * Page the top level instead of scrolling it. Blocks stay independent of\n * pages: a page of 20 over blocks of 100 costs one request per five\n * pages. Omit for infinite scrolling.\n */\n pagination?: ServerRowModelPaginationOptions\n /** Emit a subtotal \"footer\" row after each expanded group's children. */\n groupFooters?: boolean\n /**\n * A grand-total row across the whole result. The root request then carries\n * `needsGrandTotal` and the source answers with `grandTotal`. `top` /\n * `bottom` put it in the scrolling list; the pinned variants hand it to the\n * grid's pinned rows so it stays in view.\n */\n grandTotalRow?: 'top' | 'bottom' | 'pinnedTop' | 'pinnedBottom'\n /**\n * Milliseconds to keep the rows on screen after a sort, a filter or a\n * regroup while the new answer loads. If its first block lands in that\n * time, the grid goes straight from the old rows to the new ones: no\n * frame of skeletons between them, and one update instead of two. A fast\n * source (a worker, a local database) never shows a skeleton; a slow one\n * shows them once the time is up. Default 0: skeletons at once.\n */\n keepRowsWhileLoading?: number\n /** Drop a group's cached children when it is collapsed. Default false. */\n purgeClosedGroups?: boolean\n /**\n * Hide a group row once it is open, so its children stand at its level.\n * The classic \"multi-column group\" look.\n */\n hideOpenParents?: boolean\n /**\n * Treat a group whose key is empty as unbalanced: always open, its group\n * row hidden, its rows shown among the siblings. Costs one extra request\n * per such group.\n */\n allowUnbalancedGroups?: boolean\n /**\n * Which levels a sort re-fetches. The default is selective: a column that\n * is neither grouped nor aggregated only re-orders leaves; a grouped column\n * re-fetches its own level; an aggregated column re-fetches everything.\n * `true` always re-fetches everything.\n */\n sortAllLevels?: boolean\n /**\n * Sort a fully loaded level in the browser instead of asking the server.\n * Plain type-aware comparison; a backend with collation rules of its own\n * should leave this off.\n */\n clientSideSort?: boolean\n /**\n * Re-fetch only the levels a filter touches instead of everything. Cheaper,\n * but the levels above keep their old counts and aggregates, so a group can\n * end up showing zero children. A filter on an aggregated column always\n * re-fetches everything.\n */\n onlyRefreshFilteredGroups?: boolean\n /**\n * Row selection as a RULE rather than a list of ids, so \"select all\" can\n * mean a million rows the grid never loaded. `self` treats a group row as\n * one row; `descendants` makes ticking a group select everything beneath\n * it. Off by default; the grid then keeps selection itself, over loaded\n * rows only. See `ctl.selection`, `getSelectionState`, `bulkUpdate`.\n */\n selection?: { groupSelects?: ServerSelectionGroupMode }\n /**\n * Apply `updateRow` and `deleteRow` to the loaded rows before the server\n * answers, and put them back if it rejects: the same contract as the\n * free controller's `optimistic`. A create waits for the server either\n * way, since the row has no id until then. Off by default, so a cell\n * shows a new value only once the server has it.\n */\n optimistic?: boolean\n /** Forwarded on every request as `ServerRequest.context`. Keep it serialisable. */\n context?: unknown\n /** Distinct values for a column's set filter, for `<SvGrid rowModel>` to use. */\n filterValues?: (columnId: string) => Promise<Array<string>>\n /** Log every block requested, loaded, failed and evicted, with its route. */\n debug?: boolean\n /**\n * Veto a transaction. Return false and it is reported `cancelled` and\n * nothing changes - the hook for \"a refresh is in flight, drop this\".\n */\n isApplyTransaction?: (transaction: ServerTransaction<TData>) => boolean\n /** How long `applyTransactionAsync` batches before flushing. Default 50 ms. */\n asyncTransactionWaitMs?: number\n onChange?: (state: ServerRowModelState<TData>) => void\n /** A batch of async transactions was applied, in order. */\n onAsyncTransactionsFlushed?: (results: ServerTransactionResult[]) => void\n /** A level finished re-fetching after `refresh()` (not after a purge). */\n onStoreRefreshed?: (route: string[]) => void\n /** A group was opened, by the user or by `isGroupOpenByDefault`. */\n onGroupOpened?: (route: string[]) => void\n /** A block failed to load. The row shows a Retry; this is for logging. */\n onLoadError?: (route: string[], error: unknown) => void\n}\n```\n\n### `type ServerRowModelDisplayRow`\n\nWhat this model puts on screen: every shared display row, plus placeholders.\n\n```ts\nexport type ServerRowModelDisplayRow<TData> = ServerDisplayRow<TData> | ServerPlaceholderRow\n```\n\n### `type ServerRowModelState`\n\nWhat the model emits on every change: the flattened display list, the grid rows, the counts and the current layout.\n\n```ts\nexport type ServerRowModelState<TData> = {\n /**\n * The flattened tree, one entry per row the grid shows: groups with their\n * expanded children spliced in, footers, the grand total, and a shared\n * placeholder object for every row not yet loaded.\n */\n displayRows: ReadonlyArray<ServerRowModelDisplayRow<TData>>\n /** `displayRows` mapped to grid rows - each row's data spread, plus `__group`. */\n gridRows: ReadonlyArray<ServerRowModelGridRow<TData>>\n groupBy: string[]\n aggregations: ServerAggregation[]\n /** Rows at the top level, or null until the root has answered. */\n rowCount: number | null\n /** True while the root has never loaded. */\n loading: boolean\n /** True while a `createRow`, `updateRow` or `deleteRow` is in flight. */\n saving: boolean\n /** The rejection from the last failed top-level fetch, else null. */\n error: unknown\n sortModel: ServerSortModel\n filterModel: ServerFilterModel\n /** Ids (JSON of the route) of the expanded groups. */\n expandedGroups: string[]\n /** Ids (by `getRowId`) of the leaves whose detail panel is open. */\n openDetails: string[]\n /** The grand-total row, when one is configured and has arrived. */\n grandTotal: TData | null\n pivotBy: string[]\n pivotMode: boolean\n /** The pivoted value fields the backend has reported so far, in pivot mode. */\n pivotResultFields: string[]\n /** The pager, or null when the top level scrolls. */\n pagination: ServerRowModelPagination | null\n}\n```\n\n### `type ServerRowModelGridRow`\n\nWhat the grid renders: the row's own fields at the top level (so a plain\n`field` column shows a subtotal on a group row and the value on a leaf)\nplus the display row under `__group`. Placeholders carry only the marker.\n\n```ts\nexport type ServerRowModelGridRow<TData> = (TData | Record<string, never>) & {\n __group: ServerRowModelDisplayRow<TData>\n}\n```\n\n### `type ServerTransaction`\n\nAdd, update and remove rows in one level without a request.\n\nRows are matched by `getRowId` at a leaf level, and by the group column's\nvalue at a group level (a group row IS its key). The grand total answers\nto the fixed id `sv-grand-total`.\n\n```ts\nexport type ServerTransaction<TData> = {\n /** The level to apply to. Omit for the top level. */\n route?: string[]\n add?: ReadonlyArray<TData>\n /** Where `add` goes. Default: the end of the level. */\n addIndex?: number\n update?: ReadonlyArray<TData>\n /** Rows to remove, or their ids. */\n remove?: ReadonlyArray<TData | string>\n /**\n * The level's row count afterwards, when you know it better than the\n * arithmetic does - a delete that also removed rows outside the cache,\n * say. Applied last.\n */\n rowCount?: number\n}\n```\n\n### `type ServerTransactionStatus`\n\nHow a transaction went. `applied`: every part that could be applied was.\n`storeNotFound`: no level exists for `route` (nothing has been expanded\nthere). `cancelled`: `isApplyTransaction` said no. `storeLoading`: the\nlevel's first block is still in flight. `storeWaitingToLoad`: the level\nexists but nothing has been requested from it yet. `storeLoadingFailed`:\nthe level's load failed; retry it before applying.\n\n```ts\nexport type ServerTransactionStatus =\n | 'applied'\n | 'storeNotFound'\n | 'cancelled'\n | 'storeLoading'\n | 'storeWaitingToLoad'\n | 'storeLoadingFailed'\n```\n\n### `type ServerTransactionResult`\n\nWhat `applyTransaction` returns: the status and the ids it placed, patched and removed.\n\n```ts\nexport type ServerTransactionResult = {\n status: ServerTransactionStatus\n /** Ids of the rows placed in the cache. */\n add: string[]\n /** Ids of the rows found and updated. */\n update: string[]\n /** Ids of the rows found and removed. */\n remove: string[]\n}\n```\n\n### `type RefreshOptions`\n\nWhat `refresh` takes: the level to re-read (`[]` is the root) and whether to drop its cache first.\n\n```ts\nexport type RefreshOptions = {\n /** The group whose children to reload. Omit for the top level. */\n route?: string[]\n /**\n * Drop the cache for that level and everything beneath it and start over.\n * Without it the loaded blocks re-fetch in place: the count, the scroll\n * position and every expanded descendant survive.\n */\n purge?: boolean\n}\n```\n\n### `type ServerRowModel`\n\nThe Server-Side Row Model: the controller surface plus the `GridRowModel` shape, so one object drives the grid through `rowModel`.\n\n```ts\nexport type ServerRowModel<TData> = GridRowModel<ServerRowModelGridRow<TData>> & {\n /** The group accessors the grid's treegrid keyboard and `SvGroupCell` use. Always present on this model. */\n group: NonNullable<GridRowModel<ServerRowModelGridRow<TData>>['group']>\n /** Load the top level, or reload a level. See {@link RefreshOptions}. */\n refresh(options?: RefreshOptions): void\n /** Re-fetch every block that failed, at every level. */\n retryLoads(): void\n /** Replace the sort and re-fetch the levels it affects. Takes either filter shape. */\n setSort(sortModel: ServerSortModel): void\n setFilter(filterModel: ServerFilterModel | GridFilterState): void\n /** Change the grouping. Collapses everything and reloads the top level. */\n setGroupBy(groupBy: string[]): void\n /** Change the aggregations. Reloads every level. */\n setAggregations(aggregations: ServerAggregation[]): void\n /**\n * Change the pivot columns and / or switch pivot mode. Reloads every\n * level. In pivot mode the innermost group level cannot be opened: its\n * rows are the pivoted aggregates, and there are no leaves under them.\n */\n setPivot(pivot: { pivotBy?: string[]; pivotMode?: boolean }): void\n /**\n * Change any of group-by, aggregations and pivot in one go, with ONE\n * reload - what a designer sends on Apply. A field left out keeps its\n * value; a layout equal to the current one does nothing at all.\n */\n setLayout(layout: {\n groupBy?: string[]\n aggregations?: ServerAggregation[]\n pivotBy?: string[]\n pivotMode?: boolean\n pivotRowTotals?: boolean | string\n }): void\n /** Go to a page (clamped to what exists). No-op without `pagination`. */\n setPage(pageIndex: number): void\n /** Change the page size; the current first row stays on screen. */\n setPageSize(pageSize: number): void\n /** Fetch the next block of a `loadMore` level (the \"Load N more\" row). */\n loadMoreChildren(route: string[]): void\n toggleGroup(row: ServerGroupRow<TData>): void\n expandGroup(route: string[]): void\n collapseGroup(route: string[]): void\n /**\n * Open every group. With `includeUnloaded`, groups that arrive later open\n * on arrival too, until the next `collapseAll()`.\n */\n expandAll(options?: { includeUnloaded?: boolean }): void\n collapseAll(): void\n isExpanded(route: string[]): boolean\n /**\n * Master-detail: open or close the detail panel under a leaf, by the id\n * `getRowId` gives it. The panel is a display row of kind `detail` right\n * under its leaf, carrying the leaf as `master`; mark it for the grid\n * with `isDetailRow: (row) => row.__group?.kind === 'detail'` and draw\n * it with `renderDetailRow` (give `detailRowHeight` under\n * virtualization). Closes with the group that holds the leaf, and goes\n * when the leaf is removed.\n */\n toggleDetail(id: string, open?: boolean): void\n isDetailOpen(id: string): boolean\n /** Close every open detail panel. */\n closeAllDetails(): void\n /**\n * Write rows straight into a level, bypassing the datasource: children\n * that came with their parent, a socket that pushed a whole level. Creates\n * the level's store if it does not exist. `startRow` must sit on a block\n * boundary for that level.\n */\n applyRowData(input: {\n route?: string[]\n rows: ReadonlyArray<TData>\n rowCount?: number\n startRow?: number\n }): void\n /** Apply a transaction now. See {@link ServerTransaction}. */\n applyTransaction(transaction: ServerTransaction<TData>): ServerTransactionResult\n /**\n * Queue a transaction and apply it with whatever else arrives within\n * `asyncTransactionWaitMs`, so a burst of updates re-renders once. A\n * transaction whose level is still loading waits for it. The callback\n * gets that transaction's result when the batch flushes.\n */\n applyTransactionAsync(\n transaction: ServerTransaction<TData>,\n callback?: (result: ServerTransactionResult) => void,\n ): void\n /** Apply every queued async transaction now. */\n flushAsyncTransactions(): void\n /**\n * Patch one loaded row in place, on whatever level holds it, without a\n * request and without changing its id. The path for a socket-driven\n * tick; `applyTransaction` is for adding and removing. `replace` swaps\n * the whole row instead of merging the patch. Returns whether it was found.\n */\n updateRowData(id: string, patch: Partial<TData>, options?: { replace?: boolean }): boolean\n /**\n * Write through the source, then update the cache with what it returned\n * (no refetch). Throws when the source lacks the method. Aggregates are\n * NOT recomputed - `refresh({ route })` the parent when a subtotal must\n * follow. A created row lands at `addIndex` within its level, else at the\n * end, which in a level of thousands is out of sight: pass `0` for the\n * top, or the index a deleted row had to put it back where it was.\n */\n createRow(input: Partial<TData>, route?: string[], addIndex?: number): Promise<TData>\n updateRow(id: string, patch: Partial<TData>): Promise<TData>\n deleteRow(id: string): Promise<void>\n /**\n * Move a loaded row to another level: a file dragged into a folder, an\n * order into another region. With `patch` the move is written through\n * `source.updateRow` first (the parent field, typically) and the saved\n * row is what lands; without it the cache alone moves. The row leaves\n * its level as a transaction and joins `toRoute` at `addIndex` (the end\n * by default). A group takes its open children with it in the sense\n * that their cached level is dropped: they are read again under the\n * new route. A target level nothing has opened reports `storeNotFound`\n * and holds the row once it opens; the parent counts follow either way.\n */\n moveRow(\n id: string,\n toRoute: string[],\n options?: { patch?: Partial<TData>; addIndex?: number },\n ): Promise<{ row: TData; status: ServerTransactionStatus }>\n /** Tell the model which display rows are on screen. `<SvGrid rowModel>` does this. */\n setViewport(startIndex: number, endIndex: number): void\n /** The selection rule, when `selection` was configured. */\n readonly selectionModel: ServerSelectionModel | null\n /** The rule as plain data, for saving or for sending to a bulk endpoint. */\n getSelectionState(): ServerSelectionState | ServerGroupSelectionNode | null\n /**\n * Restore a saved rule. The callback-style shape (`toggledNodes`) is\n * accepted as it is, with group ids read as group keys; pass it through\n * `fromCallbackSelectionState(state, mapping)` first when they differ.\n */\n setSelectionState(\n state: ServerSelectionState | ServerGroupSelectionNode | CallbackSelectionState | CallbackGroupSelectionState,\n ): void\n /**\n * Apply one patch to every selected row, loaded or not, through the\n * datasource's `updateWhere`, then reload every level so the rows and\n * their aggregates reflect it. Resolves with how many rows changed.\n * Throws when the source has no `updateWhere` - a bulk edit is refused\n * rather than silently applied to the loaded rows only.\n */\n bulkUpdate(patch: Partial<TData>): Promise<number>\n getLevelState(route?: string[]): ServerLevelState | null\n levelStates(): ServerLevelState[]\n /** Every block at every level, for logging and tests. */\n getCacheState(): Array<BlockState & { route: string[] }>\n getState(): ServerRowModelState<TData>\n /** Abort what is in flight, close the source, stop emitting. Call on unmount. */\n dispose(): void\n /** The grand-total row for `pinnedTop` / `pinnedBottom`, or nothing. */\n readonly pinnedTopRows: ReadonlyArray<ServerRowModelGridRow<TData>> | undefined\n readonly pinnedBottomRows: ReadonlyArray<ServerRowModelGridRow<TData>> | undefined\n}\n```\n\n### `const GRAND_TOTAL_ROW_ID`\n\nThe fixed id of the grand-total display row, so a transaction can address it.\n\n```ts\nexport const GRAND_TOTAL_ROW_ID = 'sv-grand-total' as const\n```\n\n### `const GROUP_TOTAL_ROW_ID_PREFIX`\n\nThe prefix of a group footer's id; the rest is the group route.\n\n```ts\nexport const GROUP_TOTAL_ROW_ID_PREFIX = 'sv-group-total:' as const\n```\n\n### `function createServerRowModel`\n\nBuild the Server-Side Row Model over a `ServerDataSource`: lazy grouping\nand tree data one level at a time, a block cache per level, aggregates,\nchild counts, grand totals, pivot, paging, transactions and a selection\nthat reaches rows the grid never loaded. Hand the result to\n`<SvGrid rowModel>`. Enterprise: nudges when no licence key is set.\n\n```ts\nexport function createServerRowModel<TData>(\n source: ServerDataSource<TData>,\n options: ServerRowModelOptions<TData>,\n): ServerRowModel<TData> {\n // Runs without a key; shows the watermark + one console notice.\n nudgeServerRowModel()\n\n let groupBy = [...(options.groupBy ?? [])]\n let aggregations = [...(options.aggregations ?? [])]\n let pivotBy = [...(options.pivotBy ?? [])]\n let pivotMode = !!options.pivotMode\n let pivotRowTotals: boolean | string = options.pivotRowTotals ?? false\n const pivotSeparator = options.pivotFieldSeparator ?? '_'\n /** The union of every `pivotResultFields` seen since the last reset, in order. */\n let pivotFields: string[] = []\n /** Verbatim column defs from the backend, when it sent them instead of fields. */\n let pivotColumnsFromSource: ReadonlyArray<unknown> | null = null\n const treeData = !!options.treeData\n if (treeData && (!options.getRowId || !options.hasChildren)) {\n throw new Error('createServerRowModel: treeData requires getRowId and hasChildren')\n }\n const getRowId = options.getRowId\n const hasChildren = options.hasChildren\n const childCountOf = options.childCount\n const skeletonRows = Math.max(1, options.skeletonRows ?? 3)\n const paging = options.pagination ?? null\n let pageIndex = 0\n let pageSize = Math.max(1, paging?.pageSize ?? 100)\n /** Rows the pager counts, as of the last flatten. */\n let pagerRowCount = 0\n const groupFooters = !!options.groupFooters\n const grandTotalRow = options.grandTotalRow\n const debug = !!options.debug\n\n let sortModel: ServerSortModel = []\n let filterModel: ServerFilterModel = {}\n\n const stores = new Map<string, Store<TData>>()\n const expanded = new Set<string>()\n /** Group routes that have been through `isGroupOpenByDefault` once. */\n const seenGroups = new Set<string>()\n let autoExpand = false\n\n let grandTotal: TData | null | undefined = undefined\n /**\n * The grand total on hand is from before an in-place refresh of the top\n * level or a bulk edit, so the next root block asks for a fresh one. The\n * old one stays on screen until it lands rather than blinking out.\n */\n let grandTotalStale = false\n /** Leaves whose detail panel is open, by the id `getRowId` gives them. */\n const openDetails = new Set<string>()\n let rootError: unknown = null\n let disposed = false\n /** Writes the server has not answered yet; `saving` is \"any\". */\n let writesInFlight = 0\n\n // Generation guard: bumped on any reset so responses for the previous shape\n // are discarded when they land.\n let generation = 0\n\n // A single in-flight budget across every level. The block cache caps\n // concurrency per instance; with one instance per route that would let ten\n // open groups fire twenty requests, so the gate lives here.\n const maxConcurrent = Math.max(1, options.maxConcurrentRequests ?? 2)\n let inFlight = 0\n const waiting: Array<() => void> = []\n const acquire = (): Promise<void> => {\n if (inFlight < maxConcurrent) {\n inFlight += 1\n return Promise.resolve()\n }\n return new Promise((resolve) => waiting.push(() => { inFlight += 1; resolve() }))\n }\n const release = (): void => {\n inFlight -= 1\n waiting.shift()?.()\n }\n\n const subscribers = new Set<() => void>()\n let lastViewport: [number, number] = [0, 0]\n let segments: Segment<TData>[] = []\n let emitScheduled = false\n\n // ----------------------------------------------------------- stores\n\n function levelOf(route: ReadonlyArray<string>): number {\n return route.length\n }\n\n function isLeafLevel(level: number): boolean {\n return !treeData && level >= groupBy.length\n }\n\n /** The group row `route` names, if its parent level has it loaded. */\n function parentRowOf(route: string[]): TData | undefined {\n if (route.length === 0) return undefined\n const parent = stores.get(routeKey(route.slice(0, -1)))\n if (!parent) return undefined\n const key = route[route.length - 1]\n const rows = parent.cache.rows()\n for (const child of rows) {\n if (rowPlaceholderState(child)) continue\n if (child.kind === 'group' && child.key === key) return child.data\n }\n return undefined\n }\n\n function toChildren(route: string[], startRow: number, rows: ReadonlyArray<TData>): Child<TData>[] {\n const level = levelOf(route)\n const groupField = groupBy[level]\n const storeKey = routeKey(route)\n return rows.map((data, i): Child<TData> => {\n const isGroup = treeData ? hasChildren!(data) : level < groupBy.length\n if (isGroup) {\n const key = treeData\n ? getRowId!(data)\n : ((v) => (v == null ? '' : String(v)))((data as Record<string, unknown>)[groupField!])\n const agg: Record<string, unknown> = {}\n for (const a of aggregations) agg[a.col] = (data as Record<string, unknown>)[a.col]\n return {\n kind: 'group',\n key,\n field: treeData ? '' : groupField!,\n aggregates: agg,\n childCount: childCountOf?.(data),\n data,\n }\n }\n const id = getRowId ? `${storeKey}:${getRowId(data)}` : `${storeKey}:${startRow + i}`\n return { kind: 'leaf', id, data }\n })\n }\n\n function createStore(route: string[]): Store<TData> {\n const level = levelOf(route)\n const params = options.levelParams?.(level, route) ?? {}\n const blockSize = Math.max(1, params.blockSize ?? options.blockSize ?? 100)\n const loadMore = !!params.loadMore\n const infinite = !loadMore && params.infinite !== false\n const key = routeKey(route)\n const gen = generation\n\n const store: Store<TData> = {\n route,\n key,\n level,\n infinite,\n loadMore,\n blockSize,\n refreshPending: false,\n seenBlocks: new Map(),\n cache: null as unknown as BlockCache<Child<TData>>,\n }\n\n store.cache = createBlockCache<Child<TData>>({\n blockSize,\n maxBlocksInCache: params.maxBlocksInCache ?? options.maxBlocksInCache,\n // The model gates concurrency itself, across levels.\n maxConcurrentRequests: Number.MAX_SAFE_INTEGER,\n blockLoadDebounceMs: options.blockLoadDebounceMs,\n initialRowCount: Math.max(1, params.initialRowCount ?? skeletonRows),\n fetch: async (startRow, endRow, signal) => {\n await acquire()\n try {\n if (disposed || gen !== generation || signal.aborted) {\n throw new Error('stale')\n }\n const needsGrandTotal =\n route.length === 0 && grandTotalRow != null && (grandTotal === undefined || grandTotalStale)\n const request: ServerRequest = {\n startRow,\n endRow,\n pageIndex: Math.floor(startRow / blockSize),\n pageSize: blockSize,\n sortModel,\n filterModel,\n groupBy,\n groupKeys: route,\n aggregations,\n ...(pivotMode ? { pivotBy, pivotMode: true } : {}),\n ...(needsGrandTotal ? { needsGrandTotal: true } : {}),\n ...(route.length ? { parentRow: parentRowOf(route) } : {}),\n ...(options.context !== undefined ? { context: options.context } : {}),\n signal,\n }\n let result\n try {\n result = await source.getRows(request)\n } catch (err) {\n if (!disposed && gen === generation) {\n if (route.length === 0) rootError = err\n options.onLoadError?.(route, err)\n }\n throw err\n }\n if (disposed || gen !== generation) throw new Error('stale')\n if (route.length === 0) {\n rootError = null\n if ('grandTotal' in result) {\n grandTotal = result.grandTotal ?? null\n grandTotalStale = false\n }\n }\n if (pivotMode) {\n if (result.pivotResultColumns) pivotColumnsFromSource = result.pivotResultColumns\n for (const f of result.pivotResultFields ?? []) {\n if (!pivotFields.includes(f)) pivotFields.push(f)\n }\n }\n return {\n rows: toChildren(route, startRow, result.rows),\n rowCount: result.rowCount >= 0 ? result.rowCount : undefined,\n }\n } finally {\n release()\n }\n },\n onChange: (s) => {\n if (disposed || gen !== generation) return\n // Runs once per block that just landed: open-by-default, and the\n // debug log. Scanning only those blocks keeps this O(blockSize)\n // rather than O(rows) on every change.\n for (const index of diffBlocks(store)) openByDefaultIn(store, index)\n if (store.refreshPending && !s.loading) {\n store.refreshPending = false\n options.onStoreRefreshed?.(route)\n }\n // A level that is not infinite loads itself completely once it knows\n // how big it is.\n if (!infinite && !loadMore && s.lastRowKnown && s.rowCount != null) {\n store.cache.setViewport(0, Math.max(0, s.rowCount - 1))\n }\n scheduleEmit()\n },\n })\n stores.set(key, store)\n return store\n }\n\n function ensureStore(route: string[]): Store<TData> {\n return stores.get(routeKey(route)) ?? createStore(route)\n }\n\n function dropSubtree(route: string[]): void {\n const prefix = routeKey(route)\n for (const [key, store] of [...stores]) {\n if (key === prefix || isUnder(key, route)) {\n store.cache.dispose()\n stores.delete(key)\n }\n }\n }\n\n function isUnder(key: string, route: string[]): boolean {\n // Routes are JSON arrays; a descendant's key starts with the parent's\n // elements. Compare structurally rather than by string prefix so that\n // [\"a\"] is not mistaken for a parent of [\"ab\"].\n const parsed = JSON.parse(key) as string[]\n if (parsed.length <= route.length) return false\n return route.every((seg, i) => parsed[i] === seg)\n }\n\n /** Block indices that became `loaded` since the last call. Logs when `debug`. */\n function diffBlocks(store: Store<TData>): number[] {\n const now = new Map(store.cache.getCacheState().map((b) => [b.blockIndex, b.status]))\n const landed: number[] = []\n for (const [index, status] of now) {\n const before = store.seenBlocks.get(index)\n if (before === status) continue\n if (status === 'loaded') landed.push(index)\n // eslint-disable-next-line no-console -- opt-in diagnostics, see the debug option\n if (debug) console.debug(`[svgrid ssrm] ${routeKey(store.route)} block ${index}: ${status}`)\n }\n if (debug) {\n for (const index of store.seenBlocks.keys()) {\n // eslint-disable-next-line no-console -- opt-in diagnostics, see the debug option\n if (!now.has(index)) console.debug(`[svgrid ssrm] ${routeKey(store.route)} block ${index}: evicted`)\n }\n }\n store.seenBlocks = now\n return landed\n }\n\n /**\n * Open the groups in a freshly landed block that should start open: by\n * `isGroupOpenByDefault`, by an `expandAll({ includeUnloaded })` in force,\n * or because they are unbalanced. Once per group, so a block that is\n * re-fetched does not re-open something the user closed.\n */\n function openByDefaultIn(store: Store<TData>, blockIndex: number): void {\n const start = blockIndex * store.blockSize\n for (let i = start; i < start + store.blockSize; i += 1) {\n const raw = store.cache.getRow(i)\n if (rowPlaceholderState(raw)) continue\n const child = raw as Child<TData>\n if (child.kind !== 'group') continue\n const childRoute = [...store.route, child.key]\n const ck = routeKey(childRoute)\n if (seenGroups.has(ck)) continue\n seenGroups.add(ck)\n const unbalanced = !!options.allowUnbalancedGroups && child.key === ''\n if (unbalanced || autoExpand || options.isGroupOpenByDefault?.(childRoute, child.data)) {\n expandGroup(childRoute)\n }\n }\n }\n\n // ---------------------------------------------------------- flatten\n\n /**\n * A level's rows as display and grid rows, kept from one emit to the next.\n *\n * A level of leaves maps each cached row to one display row that depends on\n * nothing but that row, so the mapping only has to be redone where the\n * cache changed - and every cache write (a landed block, a patch, a purge)\n * puts a new object at the index it touches. Comparing identities is a\n * tight loop; mapping a million rows per landed block of a hundred was most\n * of what a block cost on the main thread. Keeping the grid row objects also\n * lets the grid keep its own row objects for them.\n *\n * Null for a level holding groups (a group row's display depends on what is\n * expanded beneath it) and while any detail is open (a detail adds a row).\n */\n type LeafRun = {\n rows: ReadonlyArray<Child<TData>>\n display: Array<ServerRowModelDisplayRow<TData>>\n grid: Array<ServerRowModelGridRow<TData>>\n }\n const leafRuns = new WeakMap<Store<TData>, LeafRun>()\n\n function leafRun(store: Store<TData>, rows: ReadonlyArray<Child<TData>>): LeafRun | null {\n if (openDetails.size) return null\n const prev = leafRuns.get(store)\n if (prev && prev.rows === rows) return prev\n const n = rows.length\n // Same length (a block landed, a row was patched): update the kept\n // arrays in place. The flatten only ever copies out of them.\n const inPlace = !!prev && prev.rows.length === n\n const display = inPlace ? prev!.display : new Array<ServerRowModelDisplayRow<TData>>(n)\n const grid = inPlace ? prev!.grid : new Array<ServerRowModelGridRow<TData>>(n)\n const old = prev?.rows\n const oldLength = old ? old.length : 0\n for (let i = 0; i < n; i += 1) {\n const child = rows[i]!\n if (i < oldLength && old![i] === child) {\n if (!inPlace) {\n display[i] = prev!.display[i]!\n grid[i] = prev!.grid[i]!\n }\n continue\n }\n const ph = rowPlaceholderState(child)\n if (ph) {\n const d = ph === 'failed' ? FAILED_ROW : LOADING_ROW\n display[i] = d\n grid[i] = toGridRow(d)\n continue\n }\n if (child.kind !== 'leaf') {\n // Written in place up to here, so the kept run is no longer whole.\n leafRuns.delete(store)\n return null\n }\n const d: ServerLeafRow<TData> = { kind: 'leaf', id: child.id, level: store.level, route: store.route, data: child.data }\n display[i] = d\n grid[i] = toGridRow(d, child.data)\n }\n const run = { rows, display, grid }\n leafRuns.set(store, run)\n return run\n }\n\n /**\n * A level made only of data rows maps one to one: its i-th display row is\n * its i-th child. Such a level is not walked or copied - the flatten records\n * it as one lazy piece and `lazyLeafAt` builds a row when the grid reads it,\n * so a 100M-row level costs the rows on screen, not 100M. Groups, tree\n * data, pivot, load-more, detail rows and child-row paging still walk.\n */\n function isLazyLeafLevel(store: Store<TData>): boolean {\n return (\n !treeData &&\n !pivotMode &&\n store.level >= groupBy.length &&\n !store.loadMore &&\n openDetails.size === 0 &&\n !paging?.paginateChildRows\n )\n }\n type LazyEntry = {\n child: unknown\n d: ServerRowModelDisplayRow<TData>\n g: ServerRowModelGridRow<TData>\n }\n // Replaced when a write settles (see `saving`): the grid writes a cell edit\n // into the row object it was handed, so a row the server refused would keep\n // showing the refused value while its child, which nothing changed, still\n // matched the memo.\n let lazyMemo = new WeakMap<Store<TData>, Map<number, LazyEntry>>()\n const LAZY_MEMO_CAP = 20_000\n /** Row `index` of a lazy leaf level, built once per child object it holds. */\n function lazyLeafAt(store: Store<TData>, index: number): LazyEntry {\n const child = store.cache.getRow(index) as Child<TData>\n const ph = rowPlaceholderState(child)\n if (ph) {\n const d = ph === 'failed' ? FAILED_ROW : LOADING_ROW\n return { child, d, g: toGridRow(d) }\n }\n let memo = lazyMemo.get(store)\n if (!memo) {\n memo = new Map()\n lazyMemo.set(store, memo)\n }\n const hit = memo.get(index)\n if (hit && hit.child === child) return hit\n const leaf = child as Extract<Child<TData>, { kind: 'leaf' }>\n const d: ServerLeafRow<TData> = { kind: 'leaf', id: leaf.id, level: store.level, route: store.route, data: leaf.data }\n const entry: LazyEntry = { child, d, g: toGridRow(d, leaf.data) }\n memo.set(index, entry)\n if (memo.size > LAZY_MEMO_CAP) {\n let drop = LAZY_MEMO_CAP / 4\n for (const key of memo.keys()) {\n if (drop-- <= 0) break\n memo.delete(key)\n }\n }\n return entry\n }\n\n function flatten(): {\n display: ServerRowModelDisplayRow<TData>[]\n grid: ServerRowModelGridRow<TData>[]\n } {\n // The output is a list of pieces: explicit rows (group rows, footers, a\n // walked level) and lazy leaf levels. Small or walked lists come back as\n // plain arrays; a list with a lazy piece comes back windowed.\n type Piece = {\n start: number\n length: number\n display?: ServerRowModelDisplayRow<TData>[]\n grid?: ServerRowModelGridRow<TData>[]\n store?: Store<TData>\n from?: number\n }\n const pieces: Piece[] = []\n let total = 0\n let open: Piece | null = null\n segments = []\n\n const pushRow = (d: ServerRowModelDisplayRow<TData>, data?: TData): void => {\n if (!open) {\n open = { start: total, length: 0, display: [], grid: [] }\n pieces.push(open)\n }\n open.display!.push(d)\n open.grid!.push(toGridRow(d, data))\n open.length += 1\n total += 1\n }\n const pushPiece = (piece: Piece): void => {\n open = null\n pieces.push(piece)\n total += piece.length\n }\n\n if (grandTotalRow === 'top' && grandTotal) pushRow(grandTotalDisplay(grandTotal), grandTotal)\n const bodyStart = total\n\n /**\n * A `loadMore` level shows its loaded prefix and a \"more\" row; rows\n * past the first placeholder are not the grid's to scroll into.\n */\n const loadedPrefix = (rows: ReadonlyArray<Child<TData>>): number => {\n let n = 0\n while (n < rows.length && !rowPlaceholderState(rows[n])) n += 1\n return n\n }\n\n const walk = (store: Store<TData>, from = 0, to = Number.POSITIVE_INFINITY): void => {\n if (isLazyLeafLevel(store)) {\n // A pure leaf level: one lazy piece, nothing copied.\n const end = Math.min(store.cache.windowedRows().length, to)\n if (end > from) {\n segments.push({ store, displayStart: total, storeStart: from, length: end - from })\n pushPiece({ start: total, length: end - from, store, from })\n }\n return\n }\n const rows = store.cache.rows()\n const run = store.loadMore ? null : leafRun(store, rows)\n if (run) {\n // A level of leaves maps one to one: copy the range out of the run.\n const end = Math.min(rows.length, to)\n if (end > from) {\n segments.push({ store, displayStart: total, storeStart: from, length: end - from })\n pushPiece({\n start: total,\n length: end - from,\n display: run.display.slice(from, end),\n grid: run.grid.slice(from, end),\n })\n }\n return\n }\n const end = Math.min(rows.length, to, store.loadMore ? loadedPrefix(rows) : Number.POSITIVE_INFINITY)\n let segStart = from\n let dispStart = total\n const flushSegment = (upTo: number): void => {\n if (upTo > segStart) {\n segments.push({ store, displayStart: dispStart, storeStart: segStart, length: upTo - segStart })\n }\n }\n for (let i = from; i < end; i += 1) {\n const child = rows[i]!\n const ph = rowPlaceholderState(child)\n if (ph) {\n pushRow(ph === 'failed' ? FAILED_ROW : LOADING_ROW)\n continue\n }\n if (child.kind === 'leaf') {\n pushRow(\n { kind: 'leaf', id: child.id, level: store.level, route: store.route, data: child.data },\n child.data,\n )\n if (openDetails.size) {\n const masterId = childId(child)\n if (openDetails.has(masterId)) {\n pushRow(\n { kind: 'detail', id: `${child.id}:detail`, level: store.level, route: store.route, masterId, master: child.data },\n child.data,\n )\n }\n }\n continue\n }\n const childRoute = [...store.route, child.key]\n const ck = routeKey(childRoute)\n const childStore = stores.get(ck)\n const isExp = expanded.has(ck)\n const unbalanced = !!options.allowUnbalancedGroups && child.key === ''\n const hidden = isExp && (unbalanced || !!options.hideOpenParents)\n if (!hidden) {\n pushRow(\n {\n kind: 'group',\n id: ck,\n path: childRoute,\n field: child.field,\n key: child.key,\n level: store.level,\n expanded: isExp,\n ...(pivotMode && !treeData && childRoute.length >= groupBy.length ? { expandable: false } : {}),\n // The expander shows a spinner for the level opening, not for\n // a block far down an open level that a deep scroll asked for.\n loading: !!childStore && childStore.cache.getCacheState().some((b) => b.blockIndex === 0 && b.status === 'loading'),\n aggregates: child.aggregates,\n ...(child.childCount != null ? { childCount: child.childCount } : {}),\n data: child.data,\n },\n child.data,\n )\n }\n if (isExp && childStore) {\n // This store's run ends here; the child's rows follow, then a new\n // run of this store begins.\n flushSegment(i + 1)\n walk(childStore)\n if (groupFooters && !hidden) {\n pushRow(\n {\n kind: 'footer',\n id: GROUP_TOTAL_ROW_ID_PREFIX + ck,\n level: store.level + 1,\n path: childRoute,\n key: child.key,\n aggregates: child.aggregates,\n data: child.data,\n } as ServerFooterRow<TData>,\n child.data,\n )\n }\n segStart = i + 1\n dispStart = total\n }\n }\n flushSegment(end)\n if (store.loadMore) {\n const count = store.cache.rowCount()\n const loaded = end\n if (count == null || loaded < count) {\n pushRow({\n kind: 'more',\n id: `sv-more:${store.key}`,\n level: store.level,\n path: store.route,\n remaining: count == null ? store.blockSize : count - loaded,\n loading: store.cache.getCacheState().some((b) => b.status === 'loading'),\n })\n }\n }\n }\n\n const root = stores.get(routeKey([]))\n if (root) {\n if (paging && !paging.paginateChildRows) {\n // A page of top-level rows. The root rows array is already sized to\n // the count (placeholders for what has not loaded), so the page\n // exists before its block does.\n const count = root.cache.rowCount() ?? root.cache.windowedRows().length\n pagerRowCount = count\n const start = Math.min(pageIndex * pageSize, Math.max(0, count - 1))\n walk(root, start, start + pageSize)\n } else {\n walk(root)\n }\n }\n\n /** Every piece as plain arrays. Lazy pieces read through `lazyLeafAt`. */\n const materialize = (): { display: ServerRowModelDisplayRow<TData>[]; grid: ServerRowModelGridRow<TData>[] } => {\n if (pieces.length === 1 && pieces[0]!.display) return { display: pieces[0]!.display, grid: pieces[0]!.grid! }\n const display: ServerRowModelDisplayRow<TData>[] = []\n const grid: ServerRowModelGridRow<TData>[] = []\n for (const p of pieces) {\n if (p.display) {\n for (let i = 0; i < p.length; i += 1) {\n display.push(p.display[i]!)\n grid.push(p.grid![i]!)\n }\n continue\n }\n for (let i = 0; i < p.length; i += 1) {\n const e = lazyLeafAt(p.store!, p.from! + i)\n display.push(e.d)\n grid.push(e.g)\n }\n }\n return { display, grid }\n }\n\n if (paging?.paginateChildRows) {\n // Child-row paging cuts the flattened body, so it works on plain\n // arrays; no level is lazy in this mode (see isLazyLeafLevel).\n const { display, grid } = materialize()\n // A page of the flattened tree. Cut the body and re-base the segments\n // that cross into the page; the grand total stays on every page.\n const bodyLength = display.length - bodyStart\n pagerRowCount = bodyLength\n const start = Math.min(pageIndex * pageSize, Math.max(0, bodyLength - 1))\n const stop = Math.min(bodyLength, start + pageSize)\n display.splice(bodyStart + stop)\n display.splice(bodyStart, start)\n grid.splice(bodyStart + stop)\n grid.splice(bodyStart, start)\n const cut: Segment<TData>[] = []\n for (const seg of segments) {\n const a = Math.max(seg.displayStart, bodyStart + start)\n const b = Math.min(seg.displayStart + seg.length, bodyStart + stop)\n if (b <= a) continue\n cut.push({\n store: seg.store,\n displayStart: a - start,\n storeStart: seg.storeStart + (a - seg.displayStart),\n length: b - a,\n })\n }\n segments = cut\n if (grandTotalRow === 'bottom' && grandTotal) {\n const d = grandTotalDisplay(grandTotal)\n display.push(d)\n grid.push(toGridRow(d, grandTotal))\n }\n return { display, grid }\n }\n\n if (grandTotalRow === 'bottom' && grandTotal) pushRow(grandTotalDisplay(grandTotal), grandTotal)\n\n if (!pieces.some((p) => p.store)) return materialize()\n // At least one lazy piece: hand out windowed arrays that find the piece\n // holding an index by binary search on the piece starts.\n const pieceAt = (index: number): Piece | undefined => {\n let lo = 0\n let hi = pieces.length - 1\n while (lo <= hi) {\n const mid = (lo + hi) >> 1\n const p = pieces[mid]!\n if (index < p.start) hi = mid - 1\n else if (index >= p.start + p.length) lo = mid + 1\n else return p\n }\n return undefined\n }\n const entryAt = (index: number): { d: ServerRowModelDisplayRow<TData>; g: ServerRowModelGridRow<TData> } | undefined => {\n const p = pieceAt(index)\n if (!p) return undefined\n const offset = index - p.start\n if (p.display) return { d: p.display[offset]!, g: p.grid![offset]! }\n return lazyLeafAt(p.store!, p.from! + offset)\n }\n return {\n display: createWindowedData(total, (i) => entryAt(i)?.d),\n grid: createWindowedData(total, (i) => entryAt(i)?.g),\n }\n }\n\n function pagination(): ServerRowModelPagination | null {\n if (!paging) return null\n return {\n pageIndex,\n pageSize,\n rowCount: pagerRowCount,\n pageCount: Math.max(1, Math.ceil(pagerRowCount / pageSize)),\n }\n }\n\n /**\n * A display row as the grid sees it: the row's own fields at the top\n * level plus the `__group` marker. Footers and the grand total also carry\n * the flags the grid keys its `sv-grid-group-footer-row` /\n * `sv-grid-grand-total-row` styling on, so they look like the client\n * model's totals rather than like ordinary rows.\n */\n function toGridRow(d: ServerRowModelDisplayRow<TData>, data?: TData): ServerRowModelGridRow<TData> {\n if (d.kind === 'placeholder') return d as unknown as ServerRowModelGridRow<TData>\n const row = { ...(data as object), __group: d } as ServerRowModelGridRow<TData> & {\n __groupFooter?: boolean\n __grandTotal?: boolean\n }\n if (d.kind === 'footer') row.__groupFooter = true\n if (d.kind === 'grandTotal') {\n row.__groupFooter = true\n row.__grandTotal = true\n }\n return row\n }\n\n function grandTotalDisplay(data: TData): ServerGrandTotalRow<TData> {\n const agg: Record<string, unknown> = {}\n for (const a of aggregations) agg[a.col] = (data as Record<string, unknown>)[a.col]\n return { kind: 'grandTotal', id: GRAND_TOTAL_ROW_ID, level: 0, aggregates: agg, data }\n }\n\n function pinnedGrandTotal(): ReadonlyArray<ServerRowModelGridRow<TData>> | undefined {\n if (!grandTotal) return undefined\n return [toGridRow(grandTotalDisplay(grandTotal), grandTotal)]\n }\n\n // ------------------------------------------------------------- state\n\n let current: ServerRowModelState<TData> = {\n displayRows: [],\n gridRows: [],\n groupBy: [...groupBy],\n aggregations: [...aggregations],\n rowCount: null,\n loading: true,\n saving: false,\n error: null,\n sortModel,\n filterModel,\n expandedGroups: [],\n openDetails: [],\n grandTotal: null,\n pivotBy: [...pivotBy],\n pivotMode,\n pivotResultFields: [],\n pagination: pagination(),\n }\n\n function buildState(): ServerRowModelState<TData> {\n const root = stores.get(routeKey([]))\n const { display, grid } = flatten()\n const rootLoaded = !!root && root.cache.getCacheState().some((b) => b.status === 'loaded')\n return {\n displayRows: display,\n gridRows: grid,\n groupBy: [...groupBy],\n aggregations: [...aggregations],\n rowCount: root?.cache.rowCount() ?? null,\n loading: !!root && !rootLoaded && root.cache.getCacheState().some((b) => b.status === 'loading'),\n saving: writesInFlight > 0,\n error: rootError,\n sortModel,\n filterModel,\n expandedGroups: [...expanded],\n openDetails: [...openDetails],\n grandTotal: grandTotal ?? null,\n pivotBy: [...pivotBy],\n pivotMode,\n pivotResultFields: [...pivotFields],\n pagination: pagination(),\n }\n }\n\n // `keepRowsWhileLoading`: after a sort, a filter or a regroup, the rows on\n // screen stay until the new answer's first block lands or the time runs\n // out. `holdUntil` is that deadline, 0 when nothing is held.\n let holdUntil = 0\n let holdTimer: ReturnType<typeof setTimeout> | null = null\n let held = false\n\n function holdRows(): void {\n const ms = options.keepRowsWhileLoading ?? 0\n if (ms > 0 && current.displayRows.length > 0) {\n holdUntil = Date.now() + ms\n freezeCurrent()\n }\n }\n\n /**\n * Held rows must not change under the user, but a lazy list reads the live\n * caches, which the sort or filter that started the hold is about to purge.\n * Copy the rows around the last viewport into a snapshot and serve the held\n * lists from it. Only the grid's subscription is told (so it re-reads);\n * `onChange` still fires once, when the hold ends.\n */\n function freezeCurrent(): void {\n if (!isWindowedData(current.gridRows)) return // plain arrays are a snapshot already\n const n = current.gridRows.length\n const MARGIN = 200\n const from = Math.max(0, lastViewport[0] - MARGIN)\n const to = Math.min(n - 1, lastViewport[1] + MARGIN)\n const display = new Map<number, ServerRowModelDisplayRow<TData>>()\n const grid = new Map<number, ServerRowModelGridRow<TData>>()\n for (let i = from; i <= to; i += 1) {\n display.set(i, current.displayRows[i]!)\n grid.set(i, current.gridRows[i]!)\n }\n current = {\n ...current,\n displayRows: createWindowedData(n, (i) => display.get(i) ?? LOADING_ROW),\n gridRows: createWindowedData(n, (i) => grid.get(i) ?? toGridRow(LOADING_ROW)),\n }\n for (const notify of subscribers) notify()\n }\n\n /** Whether the rows on screen should stay a little longer. */\n function holding(): boolean {\n if (!holdUntil) return false\n const root = stores.get(routeKey([]))\n // A failed block ends the hold too: its Retry is the answer to show.\n const rootAnswered = !!root && root.cache.getCacheState().some((b) => b.status !== 'loading')\n let pending = false\n for (const s of stores.values()) if (s.refreshPending) pending = true\n if (Date.now() >= holdUntil || rootError || (rootAnswered && !pending)) {\n holdUntil = 0\n return false\n }\n return true\n }\n\n function scheduleEmit(): void {\n if (disposed || emitScheduled) return\n emitScheduled = true\n queueMicrotask(() => {\n emitScheduled = false\n if (disposed) return\n if (holding()) {\n held = true\n holdTimer ??= setTimeout(() => {\n holdTimer = null\n scheduleEmit()\n }, Math.max(0, holdUntil - Date.now()))\n return\n }\n if (holdTimer) {\n clearTimeout(holdTimer)\n holdTimer = null\n }\n current = buildState()\n // While rows were held the grid kept reporting positions in the old\n // list, mapped through the old segments; map them through the new.\n if (held) {\n held = false\n applyViewport()\n }\n options.onChange?.(current)\n for (const notify of subscribers) notify()\n })\n }\n\n // ------------------------------------------------------- operations\n\n function applyViewport(): void {\n const [start, end] = lastViewport\n for (const seg of segments) {\n if (seg.store.loadMore) continue\n const segEnd = seg.displayStart + seg.length - 1\n if (segEnd < start || seg.displayStart > end) continue\n const from = Math.max(start, seg.displayStart) - seg.displayStart + seg.storeStart\n const to = Math.min(end, segEnd) - seg.displayStart + seg.storeStart\n seg.store.cache.setViewport(from, to)\n }\n }\n\n /** Ask a level for its first block, so it shows something before any scroll. */\n function primeStore(store: Store<TData>): void {\n if (store.loadMore) {\n store.cache.setViewport(0, store.blockSize - 1)\n return\n }\n const from = store.level === 0 && paging && !paging.paginateChildRows ? pageIndex * pageSize : 0\n store.cache.setViewport(from, from + Math.min(store.blockSize, skeletonRows) - 1)\n }\n\n function expandGroup(route: string[]): void {\n if (disposed) return\n // Under pivot the innermost group rows ARE the result; there is nothing\n // beneath them to fetch.\n if (pivotMode && !treeData && route.length >= groupBy.length) return\n const key = routeKey(route)\n if (expanded.has(key)) return\n expanded.add(key)\n const store = ensureStore(route)\n // A known child count sizes the scrollbar (and the skeletons) right away.\n const parent = parentRowOf(route)\n const known = parent !== undefined ? childCountOf?.(parent) : undefined\n if (known != null && store.cache.rowCount() == null) store.cache.setRowCount(known, true)\n primeStore(store)\n options.onGroupOpened?.(route)\n scheduleEmit()\n }\n\n function collapseGroup(route: string[]): void {\n const key = routeKey(route)\n if (!expanded.delete(key)) return\n if (options.purgeClosedGroups) dropSubtree(route)\n scheduleEmit()\n }\n\n /** Start over below `route` (or everywhere), keeping the expansion set. */\n function rebuild(route: string[] = []): void {\n if (route.length === 0) {\n // A full reset. Disposing every cache aborts every request, and the\n // generation bump discards any that slipped past the abort.\n generation += 1\n for (const s of stores.values()) s.cache.dispose()\n stores.clear()\n grandTotal = undefined\n grandTotalStale = false\n pivotFields = []\n pivotColumnsFromSource = null\n } else {\n dropSubtree(route)\n }\n const target = ensureStore(route)\n primeStore(target)\n // Expanded descendants come back too, each priming its own first block.\n for (const key of expanded) {\n const r = JSON.parse(key) as string[]\n if (r.length > route.length && route.every((seg, i) => r[i] === seg)) primeStore(ensureStore(r))\n }\n scheduleEmit()\n }\n\n /** Which stores a sort touches, under the selective rules. */\n function storesAffectedBySort(next: ServerSortModel): Store<TData>[] {\n const all = [...stores.values()]\n if (options.sortAllLevels || treeData) return all\n const aggCols = new Set(aggregations.map((a) => a.col))\n const levels = new Set<number>()\n let everything = false\n let leaves = false\n for (const s of next) {\n const gi = groupBy.indexOf(s.id)\n if (aggCols.has(s.id)) everything = true\n else if (gi >= 0) levels.add(gi)\n else leaves = true\n }\n // Clearing the sort has to put every level back to server order.\n if (next.length === 0) everything = true\n if (everything) return all\n return all.filter((s) => levels.has(s.level) || (leaves && isLeafLevel(s.level)))\n }\n\n function sortLocally(store: Store<TData>): boolean {\n const st = store.cache.getCacheState()\n const count = store.cache.rowCount()\n if (!store.cache.lastRowKnown() || count == null) return false\n const loaded = st.filter((b) => b.status === 'loaded').length\n if (loaded * store.blockSize < count) return false\n const rows = store.cache.rows().filter((r) => !rowPlaceholderState(r)) as Child<TData>[]\n if (rows.length !== count) return false\n const valueOf = (c: Child<TData>, col: string): unknown => (c.data as Record<string, unknown>)[col]\n rows.sort((a, b) => {\n for (const s of sortModel) {\n const cmp = compareValues(valueOf(a, s.id), valueOf(b, s.id))\n if (cmp !== 0) return s.desc ? -cmp : cmp\n }\n return 0\n })\n store.cache.applyRows(0, rows, count)\n return true\n }\n\n function setSort(next: ServerSortModel): void {\n sortModel = next\n holdRows()\n for (const store of storesAffectedBySort(next)) {\n if (options.clientSideSort && sortLocally(store)) continue\n store.refreshPending = true\n store.cache.refresh()\n }\n scheduleEmit()\n }\n\n function setFilter(next: ServerFilterModel | GridFilterState): void {\n const previous = filterModel\n holdRows()\n filterModel = Array.isArray(next.columns)\n ? { global: next.global, columns: toServerFilterColumns(next as GridFilterState) }\n : (next as ServerFilterModel)\n if (!options.onlyRefreshFilteredGroups) return rebuild()\n\n // Selective: the levels whose column changed. Everything else keeps its\n // stale counts, which is the documented trade.\n const changed = new Set<string>()\n const prevCols = previous.columns ?? {}\n const nextCols = filterModel.columns ?? {}\n for (const c of new Set([...Object.keys(prevCols), ...Object.keys(nextCols)])) {\n if (JSON.stringify(prevCols[c]) !== JSON.stringify(nextCols[c])) changed.add(c)\n }\n const globalChanged = (previous.global ?? '') !== (filterModel.global ?? '')\n const exprChanged = JSON.stringify(previous.expression) !== JSON.stringify(filterModel.expression)\n const aggCols = new Set(aggregations.map((a) => a.col))\n if (globalChanged || exprChanged || [...changed].some((c) => aggCols.has(c))) return rebuild()\n\n const levels = new Set<number>()\n let leaves = false\n for (const c of changed) {\n const gi = groupBy.indexOf(c)\n if (gi >= 0) levels.add(gi)\n else leaves = true\n }\n for (const store of stores.values()) {\n if (levels.has(store.level) || (leaves && isLeafLevel(store.level))) {\n store.refreshPending = true\n store.cache.refresh()\n }\n }\n scheduleEmit()\n }\n\n function levelState(store: Store<TData>): ServerLevelState {\n const blocks = store.cache.getCacheState()\n return {\n route: store.route,\n level: store.level,\n rowCount: store.cache.rowCount(),\n lastRowKnown: store.cache.lastRowKnown(),\n loading: blocks.some((b) => b.status === 'loading'),\n failedBlocks: blocks.filter((b) => b.status === 'failed').map((b) => b.blockIndex),\n blocks,\n }\n }\n\n // ------------------------------------------------------ transactions\n\n /** The id a transaction row goes by at a level: key at a group level, row id at a leaf level. */\n function transactionId(store: Store<TData>, row: TData | string): string {\n if (typeof row === 'string') return row\n if (getRowId) {\n const id = getRowId(row)\n if (id === GRAND_TOTAL_ROW_ID) return id\n }\n if (isLeafLevel(store.level) || treeData) {\n if (!getRowId) throw new Error('createServerRowModel: transactions need getRowId')\n return getRowId(row)\n }\n const field = groupBy[store.level]!\n const v = (row as Record<string, unknown>)[field]\n return v == null ? '' : String(v)\n }\n\n /** The id a CACHED child goes by, in the same terms. */\n function childId(child: Child<TData>): string {\n if (child.kind === 'group') return child.key\n // Leaf ids are `${storeKey}:${rowId}`; the row id is the tail.\n return getRowId ? getRowId(child.data) : child.id.slice(child.id.lastIndexOf(':') + 1)\n }\n\n function storeStatus(store: Store<TData>): ServerTransactionStatus {\n const blocks = store.cache.getCacheState()\n if (blocks.length === 0) return 'storeWaitingToLoad'\n if (blocks.some((b) => b.status === 'loaded')) return 'applied'\n if (blocks.some((b) => b.status === 'loading')) return 'storeLoading'\n return 'storeLoadingFailed'\n }\n\n function applyTransaction(tx: ServerTransaction<TData>): ServerTransactionResult {\n const result: ServerTransactionResult = { status: 'applied', add: [], update: [], remove: [] }\n if (disposed) return { ...result, status: 'storeNotFound' }\n if (options.isApplyTransaction && !options.isApplyTransaction(tx)) {\n return { ...result, status: 'cancelled' }\n }\n const route = tx.route ?? []\n const store = stores.get(routeKey(route))\n if (!store) return { ...result, status: 'storeNotFound' }\n const status = storeStatus(store)\n if (status !== 'applied') return { ...result, status }\n\n // The grand total answers to its fixed id, on the root route only.\n const isTotal = (row: TData | string): boolean =>\n route.length === 0 && typeof row !== 'string' && !!getRowId && getRowId(row) === GRAND_TOTAL_ROW_ID\n\n for (const row of tx.update ?? []) {\n if (isTotal(row)) {\n grandTotal = row\n result.update.push(GRAND_TOTAL_ROW_ID)\n continue\n }\n const id = transactionId(store, row)\n const index = store.cache.findIndex((c) => childId(c) === id)\n if (index < 0) continue\n const [child] = toChildren(route, index, [row])\n store.cache.patch(index, child!)\n result.update.push(id)\n }\n\n for (const row of tx.remove ?? []) {\n if (isTotal(row)) {\n grandTotal = null\n result.remove.push(GRAND_TOTAL_ROW_ID)\n continue\n }\n const id = transactionId(store, row)\n const index = store.cache.findIndex((c) => childId(c) === id)\n // Outside the cache means outside what we can show; when the count is\n // known the row is simply not here, and the count stands until the\n // caller says otherwise with `rowCount`.\n if (index < 0) continue\n const wasGroup = (store.cache.getRow(index) as Child<TData>).kind === 'group'\n if (store.cache.remove(index, 1) > 0) {\n result.remove.push(id)\n // A removed group takes its expansion and its cached children with it.\n if (wasGroup) {\n const childRoute = [...route, id]\n expanded.delete(routeKey(childRoute))\n dropSubtree(childRoute)\n }\n }\n }\n\n if (tx.add && tx.add.length) {\n const total = store.cache.rowCount()\n const at = tx.addIndex ?? (total ?? store.cache.windowedRows().length)\n const children = toChildren(route, at, tx.add)\n const placed = store.cache.insert(at, children)\n if (placed) for (const c of children) result.add.push(childId(c))\n // Adding the grand total means setting it.\n for (const row of tx.add) if (isTotal(row)) grandTotal = row\n }\n\n if (typeof tx.rowCount === 'number') store.cache.setRowCount(tx.rowCount, true)\n // The parent group row shows this level's count beside its key; adds\n // and removes move it by the net change. Aggregates stay as they were:\n // a refresh of the parent recomputes them, as documented.\n const delta = result.add.length - result.remove.length\n if (delta !== 0 && route.length > 0) adjustChildCount(route, delta)\n scheduleEmit()\n return result\n }\n\n function adjustChildCount(route: string[], delta: number): void {\n const parent = stores.get(routeKey(route.slice(0, -1)))\n if (!parent) return\n const key = route[route.length - 1]\n const index = parent.cache.findIndex((c) => c.kind === 'group' && c.key === key)\n if (index < 0) return\n const child = parent.cache.getRow(index) as Child<TData>\n if (child.kind !== 'group' || child.childCount == null) return\n parent.cache.patch(index, { ...child, childCount: Math.max(0, child.childCount + delta) })\n }\n\n const asyncQueue: Array<{\n tx: ServerTransaction<TData>\n callback?: (result: ServerTransactionResult) => void\n }> = []\n let asyncTimer: ReturnType<typeof setTimeout> | null = null\n\n function flushAsyncTransactions(): void {\n if (asyncTimer) clearTimeout(asyncTimer)\n asyncTimer = null\n if (asyncQueue.length === 0) return\n const batch = asyncQueue.splice(0)\n const results: ServerTransactionResult[] = []\n for (const item of batch) {\n const result = applyTransaction(item.tx)\n // A level still loading gets its transaction back in the queue for\n // the next flush; nothing else is retried.\n if (result.status === 'storeLoading' || result.status === 'storeWaitingToLoad') {\n asyncQueue.push(item)\n continue\n }\n results.push(result)\n item.callback?.(result)\n }\n if (results.length) options.onAsyncTransactionsFlushed?.(results)\n if (asyncQueue.length) scheduleAsyncFlush()\n }\n\n function scheduleAsyncFlush(): void {\n if (asyncTimer || disposed) return\n asyncTimer = setTimeout(() => {\n asyncTimer = null\n flushAsyncTransactions()\n }, options.asyncTransactionWaitMs ?? 50)\n }\n\n /** Run one write with `saving` raised around it; the flag is \"any write in flight\". */\n async function saving<T>(write: () => Promise<T>): Promise<T> {\n writesInFlight += 1\n scheduleEmit()\n try {\n return await write()\n } finally {\n writesInFlight -= 1\n // Rows are rebuilt from the cache on the next read, so an edit the\n // server refused (and the model never applied) is gone from the grid.\n lazyMemo = new WeakMap()\n scheduleEmit()\n }\n }\n\n /** The level and index holding a leaf row with this id, searching loaded rows only. */\n function locate(id: string): { store: Store<TData>; index: number } | null {\n for (const store of stores.values()) {\n const index = store.cache.findIndex((c) => childId(c) === id)\n if (index >= 0) return { store, index }\n }\n return null\n }\n\n function updateRowData(id: string, patch: Partial<TData>, opts?: { replace?: boolean }): boolean {\n const hit = locate(id)\n if (!hit) return false\n const current = hit.store.cache.getRow(hit.index) as Child<TData>\n const next = (opts?.replace ? patch : { ...current.data, ...patch }) as TData\n const [child] = toChildren(hit.store.route, hit.index, [next])\n hit.store.cache.patch(hit.index, child!)\n scheduleEmit()\n return true\n }\n\n // --------------------------------------------------------- selection\n\n const selectionModel: ServerSelectionModel | null = options.selection\n ? createServerSelectionModel({\n groupSelects: options.selection.groupSelects,\n // The grid re-derives the header checkbox and the row ticks from a\n // row-model notification, so a selection change is one.\n onChange: scheduleEmit,\n leafCount: groupLeafCount,\n })\n : null\n\n /**\n * Leaves under a loaded group row, from its `count` aggregate (the same\n * one `leafTotal` reads on the grand total); null without one, or when\n * the group row is not loaded.\n */\n function groupLeafCount(route: ReadonlyArray<string>): number | null {\n const counter = aggregations.find((a) => a.fn === 'count')\n if (!counter || route.length === 0) return null\n const parent = stores.get(routeKey(route.slice(0, -1)))\n if (!parent) return null\n const key = route[route.length - 1]\n const index = parent.cache.findIndex((c) => c.kind === 'group' && c.key === key)\n if (index < 0) return null\n const child = parent.cache.getRow(index) as Child<TData>\n if (child.kind !== 'group') return null\n const n = Number(child.aggregates[counter.col])\n return Number.isFinite(n) ? n : null\n }\n\n /** Where a grid row lives in selection terms: its parent route and its own id. */\n function locateForSelection(\n row: ServerRowModelGridRow<TData>,\n ): { route: ReadonlyArray<string>; id: string; isGroup: boolean } | null {\n const d = row.__group\n if (!d) return null\n if (d.kind === 'group') return { route: d.path.slice(0, -1), id: d.key, isGroup: true }\n if (d.kind === 'leaf') {\n return { route: d.route ?? [], id: getRowId ? getRowId(d.data) : d.id, isGroup: false }\n }\n return null\n }\n\n /**\n * How many leaves the whole result holds, for an honest select-all count:\n * the root count when nothing is grouped, else the `count` aggregation\n * on the grand total (the only place the server says it), else unknown.\n */\n function leafTotal(): number | null {\n if (treeData || groupBy.length === 0) return current.rowCount\n const counter = aggregations.find((a) => a.fn === 'count')\n if (!counter || !grandTotal) return null\n const n = Number((grandTotal as Record<string, unknown>)[counter.col])\n return Number.isFinite(n) ? n : null\n }\n\n const selectionAdapter = selectionModel\n ? {\n isSelected: (_rowId: string, row: ServerRowModelGridRow<TData>) => {\n const at = locateForSelection(row)\n return at ? selectionModel.isSelected(at.route, at.id) : false\n },\n headerState: () => selectionModel.headerState(),\n toggle: (_rowId: string, row: ServerRowModelGridRow<TData>, next: boolean) => {\n const at = locateForSelection(row)\n if (at) selectionModel.toggle(at.route, at.id, next, at.isGroup)\n },\n toggleAll: (next: boolean) => selectionModel.setAll(next),\n selectedCount: () => selectionModel.selectedCount(leafTotal()),\n bulkUpdate: (patch: Record<string, unknown>) => bulkUpdate(patch as Partial<TData>),\n }\n : undefined\n\n async function bulkUpdate(patch: Partial<TData>): Promise<number> {\n if (!selectionModel) throw new Error('createServerRowModel: bulkUpdate needs the `selection` option')\n if (!source.updateWhere) {\n throw new Error(\n 'createServerRowModel: the datasource does not implement updateWhere(), so a bulk edit ' +\n 'cannot reach rows the grid has not loaded',\n )\n }\n const rule = selectionModel.getState()\n // A nested rule is keyed level by level by the group columns; say which.\n const changed = await source.updateWhere(\n filterModel,\n patch,\n 'selectAllChildren' in rule ? { ...rule, groupBy: [...groupBy] } : rule,\n )\n if (disposed) return changed\n // Every level may have changed rows AND aggregates; reload them in place.\n for (const store of stores.values()) {\n store.refreshPending = true\n store.cache.refresh()\n }\n grandTotalStale = true\n scheduleEmit()\n return changed\n }\n\n // ------------------------------------------------------------ pivot\n\n /**\n * The columns that replace the grid's own while pivoting: the leading\n * columns the app named, then one header group per pivot key with a value\n * column per aggregation under it. Null outside pivot mode, or before the\n * first pivoted response has said what fields exist.\n */\n function pivotResultColumns(): ReadonlyArray<unknown> | null {\n if (!pivotMode) return null\n const leading = options.pivotLeadingColumns ?? []\n if (pivotColumnsFromSource) return [...leading, ...pivotColumnsFromSource]\n if (pivotFields.length === 0) return null\n return [\n ...leading,\n ...buildPivotResultColumns(pivotFields, aggregations, {\n separator: pivotSeparator,\n pivotResultColumn: options.pivotResultColumn,\n rowTotals: pivotRowTotals,\n }),\n ]\n }\n\n // ---------------------------------------------------- the controller\n\n // The id a leaf's detail is kept under: the app's row id, else the leaf's own.\n const leafDetailId = (g: { id: string; data: TData }) => (getRowId ? getRowId(g.data) : g.id.slice(g.id.lastIndexOf(':') + 1))\n const nav = {\n isGroup: (row: ServerRowModelGridRow<TData>) => row.__group?.kind === 'group',\n level: (row: ServerRowModelGridRow<TData>) =>\n row.__group && 'level' in row.__group ? row.__group.level : 0,\n expanded: (row: ServerRowModelGridRow<TData>) =>\n row.__group?.kind === 'group' ? row.__group.expanded : false,\n onToggle: (row: ServerRowModelGridRow<TData>) => {\n if (row.__group?.kind === 'group') model.toggleGroup(row.__group)\n else if (row.__group?.kind === 'more') model.loadMoreChildren(row.__group.path)\n },\n // A leaf's detail, by the id the app gave the row; a detail row toggles its master.\n toggleDetail: (row: ServerRowModelGridRow<TData>) => {\n const g = row.__group\n if (g?.kind === 'leaf') model.toggleDetail(leafDetailId(g))\n else if (g?.kind === 'detail') model.toggleDetail(g.masterId)\n },\n // Only a leaf has a detail to open; a group's expander is in the group column.\n hasDetail: (row: ServerRowModelGridRow<TData>) => row.__group?.kind === 'leaf',\n detailOpen: (row: ServerRowModelGridRow<TData>) => {\n const g = row.__group\n return g?.kind === 'leaf' ? model.isDetailOpen(leafDetailId(g)) : false\n },\n }\n\n const model: ServerRowModel<TData> = {\n refresh(opts) {\n if (disposed) return\n const route = opts?.route ?? []\n const store = stores.get(routeKey(route))\n if (opts?.purge || !store) return rebuild(route)\n store.refreshPending = true\n // The top level re-read in place brings its aggregates back fresh;\n // the grand total is one of them.\n if (route.length === 0) grandTotalStale = true\n store.cache.refresh()\n scheduleEmit()\n },\n retryLoads() {\n for (const store of stores.values()) store.cache.retryFailed()\n },\n setSort,\n setFilter,\n setGroupBy(next) {\n model.setLayout({ groupBy: next })\n },\n setAggregations(next) {\n model.setLayout({ aggregations: next })\n },\n setPivot(next) {\n model.setLayout(next)\n },\n setLayout(next) {\n if (disposed) return\n const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)\n const groupChanged = next.groupBy !== undefined && !same(next.groupBy, groupBy)\n const aggChanged = next.aggregations !== undefined && !same(next.aggregations, aggregations)\n const pivotChanged =\n (next.pivotBy !== undefined && !same(next.pivotBy, pivotBy)) ||\n (next.pivotMode !== undefined && next.pivotMode !== pivotMode)\n // The totals group is built from what is already loaded: no request.\n if (next.pivotRowTotals !== undefined && next.pivotRowTotals !== pivotRowTotals) {\n pivotRowTotals = next.pivotRowTotals\n if (!groupChanged && !aggChanged && !pivotChanged) {\n scheduleEmit()\n return\n }\n }\n if (!groupChanged && !aggChanged && !pivotChanged) return\n if (next.groupBy) groupBy = [...next.groupBy]\n if (next.aggregations) aggregations = [...next.aggregations]\n if (next.pivotBy) pivotBy = [...next.pivotBy]\n if (next.pivotMode !== undefined) pivotMode = next.pivotMode\n // New group columns make new rows, and pivoted group rows and plain\n // group rows are different rows: neither keeps its open state. A\n // change of aggregations alone keeps the tree open and refetches it.\n if (groupChanged || pivotChanged) {\n expanded.clear()\n seenGroups.clear()\n }\n holdRows()\n rebuild()\n },\n toggleGroup(row) {\n if (expanded.has(row.id)) collapseGroup(row.path)\n else expandGroup(row.path)\n },\n expandGroup,\n collapseGroup,\n toggleDetail(id, open) {\n const next = open ?? !openDetails.has(id)\n if (next === openDetails.has(id)) return\n if (next) openDetails.add(id)\n else openDetails.delete(id)\n scheduleEmit()\n },\n isDetailOpen(id) {\n return openDetails.has(id)\n },\n closeAllDetails() {\n if (!openDetails.size) return\n openDetails.clear()\n scheduleEmit()\n },\n expandAll(opts) {\n autoExpand = !!opts?.includeUnloaded\n for (const store of [...stores.values()]) {\n // A pure leaf level holds no groups to open; reading it would walk\n // every row it has.\n if (isLazyLeafLevel(store)) continue\n for (const child of store.cache.rows()) {\n if (rowPlaceholderState(child) || child.kind !== 'group') continue\n expandGroup([...store.route, child.key])\n }\n }\n },\n collapseAll() {\n autoExpand = false\n const open = [...expanded].map((k) => JSON.parse(k) as string[])\n expanded.clear()\n if (options.purgeClosedGroups) for (const r of open) dropSubtree(r)\n scheduleEmit()\n },\n isExpanded: (route) => expanded.has(routeKey(route)),\n applyRowData({ route = [], rows, rowCount, startRow = 0 }) {\n if (disposed) return\n const store = ensureStore(route)\n store.cache.applyRows(startRow, toChildren(route, startRow, rows), rowCount)\n scheduleEmit()\n },\n applyTransaction,\n applyTransactionAsync(tx, callback) {\n asyncQueue.push({ tx, callback })\n scheduleAsyncFlush()\n },\n flushAsyncTransactions,\n updateRowData,\n async createRow(input, route = [], addIndex) {\n if (!source.createRow) throw new Error('createServerRowModel: the datasource does not implement createRow()')\n const saved = await saving(() => source.createRow!(input))\n if (disposed) return saved\n applyTransaction({ route, add: [saved], ...(addIndex !== undefined ? { addIndex } : {}) })\n return saved\n },\n async updateRow(id, patch) {\n if (!source.updateRow) throw new Error('createServerRowModel: the datasource does not implement updateRow()')\n const before = options.optimistic ? locate(id) : null\n const previous = before ? ((before.store.cache.getRow(before.index) as Child<TData>).data as TData) : null\n // Show the patch now; the server answer replaces it, a rejection restores it.\n if (previous) updateRowData(id, patch)\n let saved: TData\n try {\n saved = await saving(() => source.updateRow!(id, patch))\n } catch (err) {\n if (previous && !disposed) updateRowData(id, previous, { replace: true })\n throw err\n }\n if (disposed) return saved\n const hit = locate(id)\n if (hit) applyTransaction({ route: hit.store.route, update: [saved] })\n return saved\n },\n async moveRow(id, toRoute, opts = {}) {\n const from = locate(id)\n if (!from) throw new Error(`createServerRowModel: moveRow: row ${id} is not loaded`)\n const child = from.store.cache.getRow(from.index) as Child<TData>\n let row = child.data\n if (opts.patch) {\n if (!source.updateRow) throw new Error('createServerRowModel: the datasource does not implement updateRow()')\n row = await saving(() => source.updateRow!(id, opts.patch!))\n if (disposed) return { row, status: 'cancelled' }\n }\n const fromRoute = [...from.store.route]\n // A moved group's children were cached under its old route.\n if (child.kind === 'group') dropSubtree([...fromRoute, child.key])\n applyTransaction({ route: fromRoute, remove: [id] })\n const res = applyTransaction({\n route: [...toRoute],\n add: [row],\n ...(opts.addIndex !== undefined ? { addIndex: opts.addIndex } : {}),\n })\n // A target level nothing has opened cannot take the row, but its group\n // row is on screen and the row did go there: the badge follows now\n // rather than at the next refresh.\n if (res.status === 'storeNotFound' && toRoute.length) adjustChildCount([...toRoute], 1)\n return { row, status: res.status }\n },\n async deleteRow(id) {\n if (!source.deleteRow) throw new Error('createServerRowModel: the datasource does not implement deleteRow()')\n const before = options.optimistic ? locate(id) : null\n const removed = before ? ((before.store.cache.getRow(before.index) as Child<TData>).data as TData) : null\n const route = before ? [...before.store.route] : []\n const index = before?.index ?? 0\n // Take the row out now; a rejection puts it back where it was.\n if (removed) applyTransaction({ route, remove: [id] })\n try {\n await saving(() => source.deleteRow!(id))\n } catch (err) {\n if (removed && !disposed) applyTransaction({ route, add: [removed], addIndex: index })\n throw err\n }\n if (disposed || removed) return\n const hit = locate(id)\n if (hit) applyTransaction({ route: hit.store.route, remove: [id] })\n },\n setViewport(startIndex, endIndex) {\n lastViewport = [Math.max(0, startIndex), Math.max(startIndex, endIndex)]\n // The first viewport starts the model. Its first load used to come from\n // the grid reporting its starting sort on mount (setSort -> rebuild);\n // the grid no longer reports a mount as a sort change, and a model that\n // nothing else touched (no sort, no filter, a layout equal to the one\n // it was built with) then never asked for a single block.\n if (!disposed && !stores.has(routeKey([]))) {\n rebuild()\n return\n }\n applyViewport()\n },\n setPage(next) {\n if (!paging || disposed) return\n const last = Math.max(0, Math.ceil(pagerRowCount / pageSize) - 1)\n const clamped = Math.max(0, Math.min(Math.floor(next), last))\n if (clamped === pageIndex) return\n pageIndex = clamped\n // The grid keeps reporting the same on-screen indices from page to\n // page, so the new page asks for its own blocks here.\n current = buildState()\n applyViewport()\n const root = stores.get(routeKey([]))\n if (root) primeStore(root)\n scheduleEmit()\n },\n setPageSize(next) {\n if (!paging || disposed) return\n const size = Math.max(1, Math.floor(next))\n if (size === pageSize) return\n const firstRow = pageIndex * pageSize\n pageSize = size\n pageIndex = Math.floor(firstRow / size)\n current = buildState()\n applyViewport()\n const root = stores.get(routeKey([]))\n if (root) primeStore(root)\n scheduleEmit()\n },\n loadMoreChildren(route) {\n const store = stores.get(routeKey(route))\n if (!store || disposed) return\n const rows = store.cache.rows()\n let loaded = 0\n while (loaded < rows.length && !rowPlaceholderState(rows[loaded])) loaded += 1\n store.cache.setViewport(loaded, loaded + store.blockSize - 1)\n scheduleEmit()\n },\n selectionModel,\n getSelectionState: () => selectionModel?.getState() ?? null,\n setSelectionState(state) {\n selectionModel?.setState(isCallbackSelectionState(state) ? fromCallbackSelectionState(state) : state)\n },\n bulkUpdate,\n getLevelState(route = []) {\n const store = stores.get(routeKey(route))\n return store ? levelState(store) : null\n },\n levelStates: () => [...stores.values()].map(levelState),\n getCacheState() {\n const out: Array<BlockState & { route: string[] }> = []\n for (const store of stores.values()) {\n for (const b of store.cache.getCacheState()) out.push({ ...b, route: store.route })\n }\n return out\n },\n // Fresh, not the last emitted snapshot: a caller reading state straight\n // after `collapseAll()` expects to see it collapsed, and the emit is a\n // microtask away. `getRows()` stays on the snapshot - it is the hot path.\n getState: () => (current = buildState()),\n dispose() {\n disposed = true\n generation += 1\n if (asyncTimer) clearTimeout(asyncTimer)\n asyncTimer = null\n if (holdTimer) clearTimeout(holdTimer)\n holdTimer = null\n asyncQueue.length = 0\n for (const s of stores.values()) s.cache.dispose()\n stores.clear()\n subscribers.clear()\n source.destroy?.()\n },\n get pinnedTopRows() {\n return grandTotalRow === 'pinnedTop' ? pinnedGrandTotal() : undefined\n },\n get pinnedBottomRows() {\n return grandTotalRow === 'pinnedBottom' ? pinnedGrandTotal() : undefined\n },\n get pivotResultColumns() {\n return pivotResultColumns()\n },\n // A getter: the grid re-reads it after every change notification.\n get pagination() {\n if (!paging) return undefined\n return {\n pageIndex,\n pageSize,\n rowCount: pagerRowCount,\n setPage: (i: number) => model.setPage(i),\n setPageSize: (n: number) => model.setPageSize(n),\n ...(paging.pageSizes ? { pageSizes: paging.pageSizes } : {}),\n ...(paging.autoPageSize ? { autoPageSize: true } : {}),\n }\n },\n\n // --- GridRowModel ---------------------------------------------------\n subscribe(onChange) {\n subscribers.add(onChange)\n return () => {\n subscribers.delete(onChange)\n }\n },\n getRows: () => current.gridRows,\n isLoading: () => current.loading,\n getRowId: (row, index) =>\n row.__group && 'id' in row.__group ? row.__group.id : `sv-ph:${index}`,\n rowPlaceholder: (row) => rowPlaceholderState(row),\n retryRow(_row, rowIndex) {\n // The block under the clicked row; every failed block only when the\n // index maps to no level (a stale index after a layout change).\n for (const seg of segments) {\n if (rowIndex < seg.displayStart || rowIndex >= seg.displayStart + seg.length) continue\n seg.store.cache.retryFailedAt(rowIndex - seg.displayStart + seg.storeStart)\n return\n }\n for (const store of stores.values()) store.cache.retryFailed()\n },\n group: nav,\n selection: selectionAdapter,\n filterValues: options.filterValues,\n }\n\n return model\n}\n```\n\n### `function serverRowModelRows`\n\nMap a state's display rows to grid rows. `state.gridRows` already holds\nthis; the function exists for parity with `serverGroupRows` and for code\nthat keeps its own display list.\n\n```ts\nexport function serverRowModelRows<TData>(\n state: ServerRowModelState<TData> | null | undefined,\n): ReadonlyArray<ServerRowModelGridRow<TData>> {\n return state?.gridRows ?? []\n}\n```\n\n### `function serverRowModelNav`\n\nThe `serverGroup` prop for a grid driven by hand rather than by `rowModel`.\n\n```ts\nexport function serverRowModelNav<TData>(ctl: ServerRowModel<TData>) {\n return ctl.group!\n}\n```\n\n### `function serverGroupText`\n\nThe group column's text for one grid row: a group's key (or its\n`leafField` under `treeData`, where a node's key is its id), `Total` for a\nfooter, `Grand total` for the grand total, the `leafField` value of a leaf,\nand nothing for the rows that carry no data (placeholders, skeletons, the\n\"load more\" row). `SvGroupCell` draws the expander, the count and the\nspinner; this is the value behind it, so give the group column\n`fieldFn: (row) => serverGroupText(row, leafField)` and copy, export, the\nclipboard and a `pinnedTop` / `pinnedBottom` grand total (which the grid\nformats from the accessor, not from the cell renderer) all read the same\ntext. `messages` is the map `SvGroupCell` takes, so a localized footer\nand grand total read the same in the cell and in a copy.\n\n```ts\nexport function serverGroupText<TData>(\n row: ServerRowModelGridRow<TData>,\n leafField?: keyof TData & string,\n messages?: Partial<ServerGroupMessages>,\n): string {\n const meta = row.__group\n if (!meta) return ''\n const m = resolveServerGroupMessages(messages)\n switch (meta.kind) {\n case 'group': {\n if (meta.field !== '' || !leafField) return meta.key\n const v = (row as Record<string, unknown>)[leafField]\n return v == null ? meta.key : String(v)\n }\n case 'footer':\n return fillMessage(m.total, { label: meta.key })\n case 'grandTotal':\n return m.grandTotal\n case 'leaf': {\n if (!leafField) return ''\n const v = (row as Record<string, unknown>)[leafField]\n return v == null ? '' : String(v)\n }\n default:\n return ''\n }\n}\n```\n"
7779
+ "markdown": "# `@svgrid/enterprise` · `server/server-row-model.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\server\\server-row-model.ts`.\n\n### `type ServerLevelParams`\n\nPer-level cache settings, from `levelParams`.\n\n```ts\nexport type ServerLevelParams = {\n /** Rows per request at this level. Default: the model's `blockSize`. */\n blockSize?: number\n /** Loaded blocks to keep at this level. Default: the model's `maxBlocksInCache`. */\n maxBlocksInCache?: number\n /**\n * `false` loads the whole level as soon as it opens (block by block, still\n * under the concurrency cap) instead of waiting for the viewport. A level\n * that is fully loaded can also be sorted in the browser - see\n * `clientSideSort`.\n */\n infinite?: boolean\n /**\n * Children arrive one block at a time behind a \"Load N more\" row instead\n * of by scroll: the level shows what it has loaded, then a `more` row\n * while the server holds more. `loadMoreChildren(route)` - or the row's\n * own toggle - fetches the next block. Wins over `infinite`.\n */\n loadMore?: boolean\n /**\n * Rows this level claims before its first block lands, as placeholders.\n * Default: the model's `skeletonRows`. Set it to the count you expect at\n * the root of flat data and `api.scrollToRow(900000)` works before\n * anything has loaded: the scrollbar is already the right length, the\n * rows there are placeholders, and the block under them is what loads.\n */\n initialRowCount?: number\n}\n```\n\n### `type ServerRowModelPaginationOptions`\n\nPaging the top level instead of scrolling it. See `ServerRowModelOptions.pagination`.\n\n```ts\nexport type ServerRowModelPaginationOptions = {\n /** Rows per page. Default 100. */\n pageSize?: number\n /** Choices for the footer's page-size selector. */\n pageSizes?: number[]\n /**\n * Fit the page to the grid: as many rows as its body shows without\n * scrolling, re-measured when the grid resizes. `pageSize` is then the\n * size until the first measurement.\n */\n autoPageSize?: boolean\n /**\n * Count every row of the flattened tree towards the page, children\n * included. Off, a page is `pageSize` top-level rows, each shown with\n * whatever is open beneath it.\n */\n paginateChildRows?: boolean\n}\n```\n\n### `type ServerRowModelPagination`\n\nWhere the pager stands.\n\n```ts\nexport type ServerRowModelPagination = {\n pageIndex: number\n pageSize: number\n /** Top-level rows, or flattened rows with `paginateChildRows`. */\n rowCount: number\n pageCount: number\n}\n```\n\n### `type ServerLevelState`\n\nWhere a route's rows stand, for diagnostics.\n\n```ts\nexport type ServerLevelState = {\n route: string[]\n level: number\n rowCount: number | null\n lastRowKnown: boolean\n loading: boolean\n failedBlocks: number[]\n blocks: BlockState[]\n}\n```\n\n### `type ServerRowModelOptions`\n\nEverything `createServerRowModel` is built from: grouping, tree, pivot, blocks per level, totals, paging, selection, transactions and events.\n\n```ts\nexport type ServerRowModelOptions<TData> = {\n /** Columns to group on, outer to inner. Leave empty for a flat list or a tree. */\n groupBy?: string[]\n /** Value columns to roll up per group. */\n aggregations?: ServerAggregation[]\n /**\n * Server-side pivot: the columns whose distinct values become columns.\n * Takes effect with `pivotMode`; see `setPivot`.\n */\n pivotBy?: string[]\n pivotMode?: boolean\n /**\n * In pivot mode, a `Total` header group after the pivot keys with the\n * row's plain aggregates (`amount` beside `2024_amount`, `2025_amount`).\n * The backend puts those fields on every group row and on the grand\n * total in pivot mode; the reference sources do. A string is the label.\n */\n pivotRowTotals?: boolean | string\n /** How a backend joins pivot keys and the value column into a field name. Default `_`. */\n pivotFieldSeparator?: string\n /** Post-process each generated pivot value column. */\n pivotResultColumn?: PivotResultColumnOptions['pivotResultColumn']\n /**\n * Columns to put BEFORE the generated pivot columns in pivot mode -\n * the group column with its expander, typically. The pivot columns\n * replace the grid's `columns` wholesale, so this is where the\n * app's own leading columns come back in.\n */\n pivotLeadingColumns?: ReadonlyArray<unknown>\n /**\n * Self-referential tree: each row is a node whose children load on expand.\n * Needs `getRowId` (the node id, which builds the `groupKeys` path) and\n * `hasChildren`.\n */\n treeData?: boolean\n /** Stable row id. Needed for tree data, selection and transactions. */\n getRowId?: (row: TData) => string\n /** Tree data: whether a node can be expanded. */\n hasChildren?: (row: TData) => boolean\n /**\n * How many rows a group holds, read off its response row. Shown beside the\n * key, and used to size the group's scrollbar before its first block lands.\n */\n childCount?: (row: TData) => number | undefined\n /** Open a group as soon as it arrives. Receives the route and the row. */\n isGroupOpenByDefault?: (route: string[], row: TData) => boolean\n /** Per-level cache settings. Called once per route when its store is created. */\n levelParams?: (level: number, route: string[]) => ServerLevelParams\n /** Rows per request, unless `levelParams` says otherwise. Default 100. */\n blockSize?: number\n /** Loaded blocks to keep per level, unless `levelParams` says otherwise. Unlimited by default. */\n maxBlocksInCache?: number\n /** Requests open at once, across every level. Default 2. */\n maxConcurrentRequests?: number\n /** Wait for the scroll to settle this long before fetching. Default 0. */\n blockLoadDebounceMs?: number\n /**\n * Placeholder rows shown for a level before its first block lands - so an\n * expand never opens onto nothing. Default 3.\n */\n skeletonRows?: number\n /**\n * Page the top level instead of scrolling it. Blocks stay independent of\n * pages: a page of 20 over blocks of 100 costs one request per five\n * pages. Omit for infinite scrolling.\n */\n pagination?: ServerRowModelPaginationOptions\n /** Emit a subtotal \"footer\" row after each expanded group's children. */\n groupFooters?: boolean\n /**\n * A grand-total row across the whole result. The root request then carries\n * `needsGrandTotal` and the source answers with `grandTotal`. `top` /\n * `bottom` put it in the scrolling list; the pinned variants hand it to the\n * grid's pinned rows so it stays in view.\n */\n grandTotalRow?: 'top' | 'bottom' | 'pinnedTop' | 'pinnedBottom'\n /**\n * Milliseconds to keep the rows on screen after a sort, a filter or a\n * regroup while the new answer loads. If its first block lands in that\n * time, the grid goes straight from the old rows to the new ones: no\n * frame of skeletons between them, and one update instead of two. A fast\n * source (a worker, a local database) never shows a skeleton; a slow one\n * shows them once the time is up. Default 0: skeletons at once.\n */\n keepRowsWhileLoading?: number\n /** Drop a group's cached children when it is collapsed. Default false. */\n purgeClosedGroups?: boolean\n /**\n * Hide a group row once it is open, so its children stand at its level.\n * The classic \"multi-column group\" look.\n */\n hideOpenParents?: boolean\n /**\n * Treat a group whose key is empty as unbalanced: always open, its group\n * row hidden, its rows shown among the siblings. Costs one extra request\n * per such group.\n */\n allowUnbalancedGroups?: boolean\n /**\n * Which levels a sort re-fetches. The default is selective: a column that\n * is neither grouped nor aggregated only re-orders leaves; a grouped column\n * re-fetches its own level; an aggregated column re-fetches everything.\n * `true` always re-fetches everything.\n */\n sortAllLevels?: boolean\n /**\n * Sort a fully loaded level in the browser instead of asking the server.\n * Plain type-aware comparison; a backend with collation rules of its own\n * should leave this off.\n */\n clientSideSort?: boolean\n /**\n * Re-fetch only the levels a filter touches instead of everything. Cheaper,\n * but the levels above keep their old counts and aggregates, so a group can\n * end up showing zero children. A filter on an aggregated column always\n * re-fetches everything.\n */\n onlyRefreshFilteredGroups?: boolean\n /**\n * Row selection as a RULE rather than a list of ids, so \"select all\" can\n * mean a million rows the grid never loaded. `self` treats a group row as\n * one row; `descendants` makes ticking a group select everything beneath\n * it. Off by default; the grid then keeps selection itself, over loaded\n * rows only. See `ctl.selection`, `getSelectionState`, `bulkUpdate`.\n */\n selection?: { groupSelects?: ServerSelectionGroupMode }\n /**\n * Apply `updateRow` and `deleteRow` to the loaded rows before the server\n * answers, and put them back if it rejects: the same contract as the\n * free controller's `optimistic`. A create waits for the server either\n * way, since the row has no id until then. Off by default, so a cell\n * shows a new value only once the server has it.\n */\n optimistic?: boolean\n /** Forwarded on every request as `ServerRequest.context`. Keep it serialisable. */\n context?: unknown\n /** Distinct values for a column's set filter, for `<SvGrid rowModel>` to use. */\n filterValues?: (columnId: string) => Promise<Array<string>>\n /** Log every block requested, loaded, failed and evicted, with its route. */\n debug?: boolean\n /**\n * Veto a transaction. Return false and it is reported `cancelled` and\n * nothing changes - the hook for \"a refresh is in flight, drop this\".\n */\n isApplyTransaction?: (transaction: ServerTransaction<TData>) => boolean\n /** How long `applyTransactionAsync` batches before flushing. Default 50 ms. */\n asyncTransactionWaitMs?: number\n onChange?: (state: ServerRowModelState<TData>) => void\n /** A batch of async transactions was applied, in order. */\n onAsyncTransactionsFlushed?: (results: ServerTransactionResult[]) => void\n /** A level finished re-fetching after `refresh()` (not after a purge). */\n onStoreRefreshed?: (route: string[]) => void\n /** A group was opened, by the user or by `isGroupOpenByDefault`. */\n onGroupOpened?: (route: string[]) => void\n /** A block failed to load. The row shows a Retry; this is for logging. */\n onLoadError?: (route: string[], error: unknown) => void\n}\n```\n\n### `type ServerRowModelDisplayRow`\n\nWhat this model puts on screen: every shared display row, plus placeholders.\n\n```ts\nexport type ServerRowModelDisplayRow<TData> = ServerDisplayRow<TData> | ServerPlaceholderRow\n```\n\n### `type ServerRowModelState`\n\nWhat the model emits on every change: the flattened display list, the grid rows, the counts and the current layout.\n\n```ts\nexport type ServerRowModelState<TData> = {\n /**\n * The flattened tree, one entry per row the grid shows: groups with their\n * expanded children spliced in, footers, the grand total, and a shared\n * placeholder object for every row not yet loaded.\n */\n displayRows: ReadonlyArray<ServerRowModelDisplayRow<TData>>\n /** `displayRows` mapped to grid rows - each row's data spread, plus `__group`. */\n gridRows: ReadonlyArray<ServerRowModelGridRow<TData>>\n groupBy: string[]\n aggregations: ServerAggregation[]\n /** Rows at the top level, or null until the root has answered. */\n rowCount: number | null\n /** True while the root has never loaded. */\n loading: boolean\n /** True while a `createRow`, `updateRow` or `deleteRow` is in flight. */\n saving: boolean\n /** The rejection from the last failed top-level fetch, else null. */\n error: unknown\n sortModel: ServerSortModel\n filterModel: ServerFilterModel\n /** Ids (JSON of the route) of the expanded groups. */\n expandedGroups: string[]\n /** Ids (by `getRowId`) of the leaves whose detail panel is open. */\n openDetails: string[]\n /** The grand-total row, when one is configured and has arrived. */\n grandTotal: TData | null\n pivotBy: string[]\n pivotMode: boolean\n /** The pivoted value fields the backend has reported so far, in pivot mode. */\n pivotResultFields: string[]\n /** The pager, or null when the top level scrolls. */\n pagination: ServerRowModelPagination | null\n}\n```\n\n### `type ServerRowModelGridRow`\n\nWhat the grid renders: the row's own fields at the top level (so a plain\n`field` column shows a subtotal on a group row and the value on a leaf)\nplus the display row under `__group`. Placeholders carry only the marker.\n\n```ts\nexport type ServerRowModelGridRow<TData> = (TData | Record<string, never>) & {\n __group: ServerRowModelDisplayRow<TData>\n}\n```\n\n### `type ServerTransaction`\n\nAdd, update and remove rows in one level without a request.\n\nRows are matched by `getRowId` at a leaf level, and by the group column's\nvalue at a group level (a group row IS its key). The grand total answers\nto the fixed id `sv-grand-total`.\n\n```ts\nexport type ServerTransaction<TData> = {\n /** The level to apply to. Omit for the top level. */\n route?: string[]\n add?: ReadonlyArray<TData>\n /** Where `add` goes. Default: the end of the level. */\n addIndex?: number\n update?: ReadonlyArray<TData>\n /** Rows to remove, or their ids. */\n remove?: ReadonlyArray<TData | string>\n /**\n * The level's row count afterwards, when you know it better than the\n * arithmetic does - a delete that also removed rows outside the cache,\n * say. Applied last.\n */\n rowCount?: number\n}\n```\n\n### `type ServerTransactionStatus`\n\nHow a transaction went. `applied`: every part that could be applied was.\n`storeNotFound`: no level exists for `route` (nothing has been expanded\nthere). `cancelled`: `isApplyTransaction` said no. `storeLoading`: the\nlevel's first block is still in flight. `storeWaitingToLoad`: the level\nexists but nothing has been requested from it yet. `storeLoadingFailed`:\nthe level's load failed; retry it before applying.\n\n```ts\nexport type ServerTransactionStatus =\n | 'applied'\n | 'storeNotFound'\n | 'cancelled'\n | 'storeLoading'\n | 'storeWaitingToLoad'\n | 'storeLoadingFailed'\n```\n\n### `type ServerTransactionResult`\n\nWhat `applyTransaction` returns: the status and the ids it placed, patched and removed.\n\n```ts\nexport type ServerTransactionResult = {\n status: ServerTransactionStatus\n /** Ids of the rows placed in the cache. */\n add: string[]\n /** Ids of the rows found and updated. */\n update: string[]\n /** Ids of the rows found and removed. */\n remove: string[]\n}\n```\n\n### `type RefreshOptions`\n\nWhat `refresh` takes: the level to re-read (`[]` is the root) and whether to drop its cache first.\n\n```ts\nexport type RefreshOptions = {\n /** The group whose children to reload. Omit for the top level. */\n route?: string[]\n /**\n * Drop the cache for that level and everything beneath it and start over.\n * Without it the loaded blocks re-fetch in place: the count, the scroll\n * position and every expanded descendant survive.\n */\n purge?: boolean\n}\n```\n\n### `type ServerRowModel`\n\nThe Server-Side Row Model: the controller surface plus the `GridRowModel` shape, so one object drives the grid through `rowModel`.\n\n```ts\nexport type ServerRowModel<TData> = GridRowModel<ServerRowModelGridRow<TData>> & {\n /** The group accessors the grid's treegrid keyboard and `SvGroupCell` use. Always present on this model. */\n group: NonNullable<GridRowModel<ServerRowModelGridRow<TData>>['group']>\n /** Load the top level, or reload a level. See {@link RefreshOptions}. */\n refresh(options?: RefreshOptions): void\n /** Re-fetch every block that failed, at every level. */\n retryLoads(): void\n /** Replace the sort and re-fetch the levels it affects. Takes either filter shape. */\n setSort(sortModel: ServerSortModel): void\n setFilter(filterModel: ServerFilterModel | GridFilterState): void\n /** Change the grouping. Collapses everything and reloads the top level. */\n setGroupBy(groupBy: string[]): void\n /** Change the aggregations. Reloads every level. */\n setAggregations(aggregations: ServerAggregation[]): void\n /**\n * Change the pivot columns and / or switch pivot mode. Reloads every\n * level. In pivot mode the innermost group level cannot be opened: its\n * rows are the pivoted aggregates, and there are no leaves under them.\n */\n setPivot(pivot: { pivotBy?: string[]; pivotMode?: boolean }): void\n /**\n * Change any of group-by, aggregations and pivot in one go, with ONE\n * reload - what a designer sends on Apply. A field left out keeps its\n * value; a layout equal to the current one does nothing at all.\n */\n setLayout(layout: {\n groupBy?: string[]\n aggregations?: ServerAggregation[]\n pivotBy?: string[]\n pivotMode?: boolean\n pivotRowTotals?: boolean | string\n }): void\n /** Go to a page (clamped to what exists). No-op without `pagination`. */\n setPage(pageIndex: number): void\n /** Change the page size; the current first row stays on screen. */\n setPageSize(pageSize: number): void\n /** Fetch the next block of a `loadMore` level (the \"Load N more\" row). */\n loadMoreChildren(route: string[]): void\n toggleGroup(row: ServerGroupRow<TData>): void\n expandGroup(route: string[]): void\n collapseGroup(route: string[]): void\n /**\n * Open every group. With `includeUnloaded`, groups that arrive later open\n * on arrival too, until the next `collapseAll()`.\n */\n expandAll(options?: { includeUnloaded?: boolean }): void\n collapseAll(): void\n isExpanded(route: string[]): boolean\n /**\n * Master-detail: open or close the detail panel under a leaf, by the id\n * `getRowId` gives it. The panel is a display row of kind `detail` right\n * under its leaf, carrying the leaf as `master`; mark it for the grid\n * with `isDetailRow: (row) => row.__group?.kind === 'detail'` and draw\n * it with `renderDetailRow` (give `detailRowHeight` under\n * virtualization). Closes with the group that holds the leaf, and goes\n * when the leaf is removed.\n */\n toggleDetail(id: string, open?: boolean): void\n isDetailOpen(id: string): boolean\n /** Close every open detail panel. */\n closeAllDetails(): void\n /**\n * Write rows straight into a level, bypassing the datasource: children\n * that came with their parent, a socket that pushed a whole level. Creates\n * the level's store if it does not exist. `startRow` must sit on a block\n * boundary for that level.\n */\n applyRowData(input: {\n route?: string[]\n rows: ReadonlyArray<TData>\n rowCount?: number\n startRow?: number\n }): void\n /** Apply a transaction now. See {@link ServerTransaction}. */\n applyTransaction(transaction: ServerTransaction<TData>): ServerTransactionResult\n /**\n * Queue a transaction and apply it with whatever else arrives within\n * `asyncTransactionWaitMs`, so a burst of updates re-renders once. A\n * transaction whose level is still loading waits for it. The callback\n * gets that transaction's result when the batch flushes.\n */\n applyTransactionAsync(\n transaction: ServerTransaction<TData>,\n callback?: (result: ServerTransactionResult) => void,\n ): void\n /** Apply every queued async transaction now. */\n flushAsyncTransactions(): void\n /**\n * Patch one loaded row in place, on whatever level holds it, without a\n * request and without changing its id. The path for a socket-driven\n * tick; `applyTransaction` is for adding and removing. `replace` swaps\n * the whole row instead of merging the patch. Returns whether it was found.\n */\n updateRowData(id: string, patch: Partial<TData>, options?: { replace?: boolean }): boolean\n /**\n * Write through the source, then update the cache with what it returned\n * (no refetch). Throws when the source lacks the method. Aggregates are\n * NOT recomputed - `refresh({ route })` the parent when a subtotal must\n * follow. A created row lands at `addIndex` within its level, else at the\n * end, which in a level of thousands is out of sight: pass `0` for the\n * top, or the index a deleted row had to put it back where it was.\n */\n createRow(input: Partial<TData>, route?: string[], addIndex?: number): Promise<TData>\n updateRow(id: string, patch: Partial<TData>): Promise<TData>\n deleteRow(id: string): Promise<void>\n /**\n * Move a loaded row to another level: a file dragged into a folder, an\n * order into another region. With `patch` the move is written through\n * `source.updateRow` first (the parent field, typically) and the saved\n * row is what lands; without it the cache alone moves. The row leaves\n * its level as a transaction and joins `toRoute` at `addIndex` (the end\n * by default). A group takes its open children with it in the sense\n * that their cached level is dropped: they are read again under the\n * new route. A target level nothing has opened reports `storeNotFound`\n * and holds the row once it opens; the parent counts follow either way.\n */\n moveRow(\n id: string,\n toRoute: string[],\n options?: { patch?: Partial<TData>; addIndex?: number },\n ): Promise<{ row: TData; status: ServerTransactionStatus }>\n /** Tell the model which display rows are on screen. `<SvGrid rowModel>` does this. */\n setViewport(startIndex: number, endIndex: number): void\n /** The selection rule, when `selection` was configured. */\n readonly selectionModel: ServerSelectionModel | null\n /** The rule as plain data, for saving or for sending to a bulk endpoint. */\n getSelectionState(): ServerSelectionState | ServerGroupSelectionNode | null\n /**\n * Restore a saved rule. The callback-style shape (`toggledNodes`) is\n * accepted as it is, with group ids read as group keys; pass it through\n * `fromCallbackSelectionState(state, mapping)` first when they differ.\n */\n setSelectionState(\n state: ServerSelectionState | ServerGroupSelectionNode | CallbackSelectionState | CallbackGroupSelectionState,\n ): void\n /**\n * Apply one patch to every selected row, loaded or not, through the\n * datasource's `updateWhere`, then reload every level so the rows and\n * their aggregates reflect it. Resolves with how many rows changed.\n * Throws when the source has no `updateWhere` - a bulk edit is refused\n * rather than silently applied to the loaded rows only.\n */\n bulkUpdate(patch: Partial<TData>): Promise<number>\n getLevelState(route?: string[]): ServerLevelState | null\n levelStates(): ServerLevelState[]\n /** Every block at every level, for logging and tests. */\n getCacheState(): Array<BlockState & { route: string[] }>\n getState(): ServerRowModelState<TData>\n /** Abort what is in flight, close the source, stop emitting. Call on unmount. */\n dispose(): void\n /** The grand-total row for `pinnedTop` / `pinnedBottom`, or nothing. */\n readonly pinnedTopRows: ReadonlyArray<ServerRowModelGridRow<TData>> | undefined\n readonly pinnedBottomRows: ReadonlyArray<ServerRowModelGridRow<TData>> | undefined\n}\n```\n\n### `const GRAND_TOTAL_ROW_ID`\n\nThe fixed id of the grand-total display row, so a transaction can address it.\n\n```ts\nexport const GRAND_TOTAL_ROW_ID = 'sv-grand-total' as const\n```\n\n### `const GROUP_TOTAL_ROW_ID_PREFIX`\n\nThe prefix of a group footer's id; the rest is the group route.\n\n```ts\nexport const GROUP_TOTAL_ROW_ID_PREFIX = 'sv-group-total:' as const\n```\n\n### `function createServerRowModel`\n\nBuild the Server-Side Row Model over a `ServerDataSource`: lazy grouping\nand tree data one level at a time, a block cache per level, aggregates,\nchild counts, grand totals, pivot, paging, transactions and a selection\nthat reaches rows the grid never loaded. Hand the result to\n`<SvGrid rowModel>`. Enterprise: nudges when no licence key is set.\n\n```ts\nexport function createServerRowModel<TData>(\n source: ServerDataSource<TData>,\n options: ServerRowModelOptions<TData>,\n): ServerRowModel<TData>\n```\n\n### `function serverRowModelRows`\n\nMap a state's display rows to grid rows. `state.gridRows` already holds\nthis; the function exists for parity with `serverGroupRows` and for code\nthat keeps its own display list.\n\n```ts\nexport function serverRowModelRows<TData>(\n state: ServerRowModelState<TData> | null | undefined,\n): ReadonlyArray<ServerRowModelGridRow<TData>>\n```\n\n### `function serverRowModelNav`\n\nThe `serverGroup` prop for a grid driven by hand rather than by `rowModel`.\n\n```ts\nexport function serverRowModelNav<TData>(ctl: ServerRowModel<TData>)\n```\n\n### `function serverGroupText`\n\nThe group column's text for one grid row: a group's key (or its\n`leafField` under `treeData`, where a node's key is its id), `Total` for a\nfooter, `Grand total` for the grand total, the `leafField` value of a leaf,\nand nothing for the rows that carry no data (placeholders, skeletons, the\n\"load more\" row). `SvGroupCell` draws the expander, the count and the\nspinner; this is the value behind it, so give the group column\n`fieldFn: (row) => serverGroupText(row, leafField)` and copy, export, the\nclipboard and a `pinnedTop` / `pinnedBottom` grand total (which the grid\nformats from the accessor, not from the cell renderer) all read the same\ntext. `messages` is the map `SvGroupCell` takes, so a localized footer\nand grand total read the same in the cell and in a copy.\n\n```ts\nexport function serverGroupText<TData>(\n row: ServerRowModelGridRow<TData>,\n leafField?: keyof TData & string,\n messages?: Partial<ServerGroupMessages>,\n): string\n```\n"
7709
7780
  },
7710
7781
  {
7711
7782
  "slug": "reference/auto/svgrid-enterprise-server-selection",
7712
7783
  "path": "docs/reference/auto/svgrid-enterprise-server-selection.md",
7713
7784
  "title": "@svgrid/enterprise · server/server-selection.ts",
7714
7785
  "section": "API reference",
7715
- "markdown": "# `@svgrid/enterprise` · `server/server-selection.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\server\\server-selection.ts`.\n\n### `type ServerSelectionGroupMode`\n\nHow ticking a group row behaves: itself, or everything beneath it.\n\n```ts\nexport type ServerSelectionGroupMode = 'self' | 'descendants' | 'filteredDescendants'\n```\n\n### `type ServerSelectionState`\n\nThe flat rule, for `groupSelects: 'self'`.\n\n```ts\nexport type ServerSelectionState = {\n selectAll: boolean\n /** Exceptions to `selectAll`: selected ids when it is false, deselected ones when true. */\n toggled: string[]\n}\n```\n\n### `type ServerGroupSelectionNode`\n\nOne node of the hierarchical rule, for `groupSelects: 'descendants'`.\n\n```ts\nexport type ServerGroupSelectionNode = {\n /** Whether everything under this node is selected, before exceptions. */\n selectAllChildren: boolean\n /** Exceptions, keyed by child id (a group key or a leaf id) under this node. */\n toggled: Record<string, ServerGroupSelectionNode>\n /**\n * True when this node is a group. A flipped group is an exception of\n * unknown size (its rows were never counted here); a flipped leaf is\n * exactly one row. Absent on the root and on leaves.\n */\n group?: boolean\n}\n```\n\n### `type ServerSelectionModelOptions`\n\nWhat `createServerSelectionModel` takes: the group mode and a change callback.\n\n```ts\nexport type ServerSelectionModelOptions = {\n /**\n * How ticking a group row behaves. `self` selects that one row;\n * `descendants` selects everything beneath it. `filteredDescendants` is\n * `descendants` under a filter, which on a server is the same rule - the\n * server applies the filter - so it is accepted as an alias.\n */\n groupSelects?: ServerSelectionGroupMode\n /** Called after any change. The row model re-renders from here. */\n onChange?: () => void\n /**\n * How many leaves sit under a group, by its route, or `null` when that is\n * not known. `selectedCount` needs it once a rule flips a whole group\n * (a plan ticked under an unticked root): without it the count of such a\n * rule is unknown. The row model answers from the group row's `count`\n * aggregate.\n */\n leafCount?: (route: ReadonlyArray<string>) => number | null\n}\n```\n\n### `type ServerSelectionModel`\n\nA selection kept as a rule - \"everything, except these\" - flat or per group, that the row model exposes to the grid.\n\n```ts\nexport type ServerSelectionModel = {\n readonly groupSelects: ServerSelectionGroupMode\n /** Whether the row `id` at `route` is selected. Leaves and groups alike. */\n isSelected(route: ReadonlyArray<string>, id: string): boolean\n /**\n * Set one row's selection. Under `descendants` a group takes its subtree\n * along, and `isGroup` says which kind of row this is - the model cannot\n * tell, and the difference decides whether a count is still exact.\n */\n toggle(route: ReadonlyArray<string>, id: string, next: boolean, isGroup?: boolean): void\n /** The header checkbox: select or clear everything. */\n setAll(next: boolean): void\n clear(): void\n /** `all`, `none`, or `some` - what the header checkbox should draw. */\n headerState(): 'none' | 'some' | 'all'\n /**\n * How many rows are selected, given the total. Exact for the flat rule.\n * Under `descendants` it is exact only while no group is an exception (a\n * group's size is not known here); then it is `null`, and a UI should say\n * \"some\" rather than invent a number.\n */\n selectedCount(rowCount: number | null): number | null\n /** True when the rule is \"everything\" with no exceptions - a bulk edit can go by filter alone. */\n isSelectAllWithoutExceptions(): boolean\n getState(): ServerSelectionState | ServerGroupSelectionNode\n setState(state: ServerSelectionState | ServerGroupSelectionNode): void\n}\n```\n\n### `function createServerSelectionModel`\n\nBuild a rule-based selection model. `createServerRowModel` makes one when\nits `selection` option is set; it is exported for a model of your own.\n\n```ts\nexport function createServerSelectionModel(\n options: ServerSelectionModelOptions = {},\n): ServerSelectionModel {\n const groupSelects = options.groupSelects ?? 'self'\n const hierarchical = groupSelects !== 'self'\n const notify = () => options.onChange?.()\n\n // ------------------------------------------------------------- flat\n let selectAll = false\n const toggled = new Set<string>()\n\n // ------------------------------------------------------ hierarchical\n type Node = { selectAllChildren: boolean; toggled: Map<string, Node>; group: boolean }\n let root: Node = { selectAllChildren: false, toggled: new Map(), group: true }\n\n /** Walk the rule tree along `route`, returning the deepest node reached and the state it implies. */\n function resolve(route: ReadonlyArray<string>): { node: Node; state: boolean; exact: boolean } {\n let node = root\n let state = root.selectAllChildren\n for (const key of route) {\n const next = node.toggled.get(key)\n if (!next) return { node, state, exact: false }\n node = next\n state = next.selectAllChildren\n }\n return { node, state, exact: true }\n }\n\n /** Walk-or-create the rule tree along `route`, so an exception can be recorded beneath it. */\n function ensurePath(route: ReadonlyArray<string>): Node {\n let node = root\n for (const key of route) {\n let next = node.toggled.get(key)\n if (!next) {\n // A group we descend into without an explicit rule inherits its\n // parent's state, and records it so the exception below has a base.\n next = { selectAllChildren: node.selectAllChildren, toggled: new Map(), group: true }\n node.toggled.set(key, next)\n }\n node = next\n }\n return node\n }\n\n /** Drop nodes that no longer differ from their parent, so state stays minimal. */\n function prune(node: Node): void {\n for (const [key, child] of [...node.toggled]) {\n prune(child)\n if (child.toggled.size === 0 && child.selectAllChildren === node.selectAllChildren) {\n node.toggled.delete(key)\n }\n }\n }\n\n const toPlain = (node: Node): ServerGroupSelectionNode => ({\n selectAllChildren: node.selectAllChildren,\n toggled: Object.fromEntries([...node.toggled].map(([k, v]) => [k, toPlain(v)])),\n ...(node.group ? { group: true } : {}),\n })\n const fromPlain = (plain: ServerGroupSelectionNode, group = true): Node => ({\n selectAllChildren: !!plain.selectAllChildren,\n toggled: new Map(\n Object.entries(plain.toggled ?? {}).map(([k, v]) => [k, fromPlain(v, !!v.group)]),\n ),\n group,\n })\n\n /**\n * The number of rows the exceptions under `node` amount to, or null when\n * one of them is a flipped GROUP - its size was never counted here. A\n * group whose own state matches its parent is a pass-through; only what\n * sits beneath it counts.\n */\n /**\n * Leaves selected under `node`, whose own subtree holds `size` leaves\n * (`null` when unknown). A selected node is its size minus the exceptions\n * among its toggled children; an unselected one is the sum of what its\n * toggled children select. A flipped group needs its size, which comes\n * from `leafCount`; without it the answer is unknown.\n */\n function selectedUnder(node: Node, route: ReadonlyArray<string>, size: number | null): number | null {\n if (node.selectAllChildren) {\n if (size == null) return null\n let minus = 0\n for (const [key, child] of node.toggled) {\n if (child.group) {\n const childRoute = [...route, key]\n const childSize = options.leafCount?.(childRoute) ?? null\n const selected = selectedUnder(child, childRoute, childSize)\n if (childSize == null || selected == null) return null\n minus += childSize - selected\n } else if (!child.selectAllChildren) {\n minus += 1\n }\n }\n return Math.max(0, size - minus)\n }\n let n = 0\n for (const [key, child] of node.toggled) {\n if (child.group) {\n const childRoute = [...route, key]\n const selected = selectedUnder(child, childRoute, options.leafCount?.(childRoute) ?? null)\n if (selected == null) return null\n n += selected\n } else if (child.selectAllChildren) {\n n += 1\n }\n }\n return n\n }\n\n return {\n groupSelects,\n\n isSelected(route, id) {\n if (!hierarchical) return selectAll !== toggled.has(id)\n const { node, state } = resolve(route)\n const own = node.toggled.get(id)\n return own ? own.selectAllChildren : state\n },\n\n toggle(route, id, next, isGroup = false) {\n if (!hierarchical) {\n // The row differs from the rule when `next` disagrees with selectAll.\n if (next !== selectAll) toggled.add(id)\n else toggled.delete(id)\n notify()\n return\n }\n const parent = ensurePath(route)\n // A toggled row - group or leaf - becomes a node with no exceptions of\n // its own: ticking a group throws away whatever was recorded beneath it.\n if (next === parent.selectAllChildren) parent.toggled.delete(id)\n else parent.toggled.set(id, { selectAllChildren: next, toggled: new Map(), group: isGroup })\n prune(root)\n notify()\n },\n\n setAll(next) {\n if (!hierarchical) {\n selectAll = next\n toggled.clear()\n } else {\n root = { selectAllChildren: next, toggled: new Map(), group: true }\n }\n notify()\n },\n\n clear() {\n this.setAll(false)\n },\n\n headerState() {\n if (!hierarchical) {\n if (selectAll) return toggled.size === 0 ? 'all' : 'some'\n return toggled.size === 0 ? 'none' : 'some'\n }\n if (root.selectAllChildren) return root.toggled.size === 0 ? 'all' : 'some'\n return root.toggled.size === 0 ? 'none' : 'some'\n },\n\n selectedCount(rowCount) {\n if (!hierarchical) {\n if (!selectAll) return toggled.size\n return rowCount == null ? null : Math.max(0, rowCount - toggled.size)\n }\n return selectedUnder(root, [], rowCount)\n },\n\n isSelectAllWithoutExceptions() {\n return hierarchical ? root.selectAllChildren && root.toggled.size === 0 : selectAll && toggled.size === 0\n },\n\n getState() {\n if (!hierarchical) return { selectAll, toggled: [...toggled] }\n return toPlain(root)\n },\n\n setState(state) {\n if (!hierarchical) {\n const flat = state as ServerSelectionState\n selectAll = !!flat.selectAll\n toggled.clear()\n for (const id of flat.toggled ?? []) toggled.add(id)\n } else {\n root = fromPlain(state as ServerGroupSelectionNode)\n }\n notify()\n },\n }\n}\n```\n"
7786
+ "markdown": "# `@svgrid/enterprise` · `server/server-selection.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\server\\server-selection.ts`.\n\n### `type ServerSelectionGroupMode`\n\nHow ticking a group row behaves: itself, or everything beneath it.\n\n```ts\nexport type ServerSelectionGroupMode = 'self' | 'descendants' | 'filteredDescendants'\n```\n\n### `type ServerSelectionState`\n\nThe flat rule, for `groupSelects: 'self'`.\n\n```ts\nexport type ServerSelectionState = {\n selectAll: boolean\n /** Exceptions to `selectAll`: selected ids when it is false, deselected ones when true. */\n toggled: string[]\n}\n```\n\n### `type ServerGroupSelectionNode`\n\nOne node of the hierarchical rule, for `groupSelects: 'descendants'`.\n\n```ts\nexport type ServerGroupSelectionNode = {\n /** Whether everything under this node is selected, before exceptions. */\n selectAllChildren: boolean\n /** Exceptions, keyed by child id (a group key or a leaf id) under this node. */\n toggled: Record<string, ServerGroupSelectionNode>\n /**\n * True when this node is a group. A flipped group is an exception of\n * unknown size (its rows were never counted here); a flipped leaf is\n * exactly one row. Absent on the root and on leaves.\n */\n group?: boolean\n}\n```\n\n### `type ServerSelectionModelOptions`\n\nWhat `createServerSelectionModel` takes: the group mode and a change callback.\n\n```ts\nexport type ServerSelectionModelOptions = {\n /**\n * How ticking a group row behaves. `self` selects that one row;\n * `descendants` selects everything beneath it. `filteredDescendants` is\n * `descendants` under a filter, which on a server is the same rule - the\n * server applies the filter - so it is accepted as an alias.\n */\n groupSelects?: ServerSelectionGroupMode\n /** Called after any change. The row model re-renders from here. */\n onChange?: () => void\n /**\n * How many leaves sit under a group, by its route, or `null` when that is\n * not known. `selectedCount` needs it once a rule flips a whole group\n * (a plan ticked under an unticked root): without it the count of such a\n * rule is unknown. The row model answers from the group row's `count`\n * aggregate.\n */\n leafCount?: (route: ReadonlyArray<string>) => number | null\n}\n```\n\n### `type ServerSelectionModel`\n\nA selection kept as a rule - \"everything, except these\" - flat or per group, that the row model exposes to the grid.\n\n```ts\nexport type ServerSelectionModel = {\n readonly groupSelects: ServerSelectionGroupMode\n /** Whether the row `id` at `route` is selected. Leaves and groups alike. */\n isSelected(route: ReadonlyArray<string>, id: string): boolean\n /**\n * Set one row's selection. Under `descendants` a group takes its subtree\n * along, and `isGroup` says which kind of row this is - the model cannot\n * tell, and the difference decides whether a count is still exact.\n */\n toggle(route: ReadonlyArray<string>, id: string, next: boolean, isGroup?: boolean): void\n /** The header checkbox: select or clear everything. */\n setAll(next: boolean): void\n clear(): void\n /** `all`, `none`, or `some` - what the header checkbox should draw. */\n headerState(): 'none' | 'some' | 'all'\n /**\n * How many rows are selected, given the total. Exact for the flat rule.\n * Under `descendants` it is exact only while no group is an exception (a\n * group's size is not known here); then it is `null`, and a UI should say\n * \"some\" rather than invent a number.\n */\n selectedCount(rowCount: number | null): number | null\n /** True when the rule is \"everything\" with no exceptions - a bulk edit can go by filter alone. */\n isSelectAllWithoutExceptions(): boolean\n getState(): ServerSelectionState | ServerGroupSelectionNode\n setState(state: ServerSelectionState | ServerGroupSelectionNode): void\n}\n```\n\n### `function createServerSelectionModel`\n\nBuild a rule-based selection model. `createServerRowModel` makes one when\nits `selection` option is set; it is exported for a model of your own.\n\n```ts\nexport function createServerSelectionModel(\n options: ServerSelectionModelOptions = {},\n): ServerSelectionModel\n```\n"
7716
7787
  },
7717
7788
  {
7718
7789
  "slug": "reference/auto/svgrid-enterprise-svgrid-adapter",
7719
7790
  "path": "docs/reference/auto/svgrid-enterprise-svgrid-adapter.md",
7720
7791
  "title": "@svgrid/enterprise · server/svgrid-adapter.ts",
7721
7792
  "section": "API reference",
7722
- "markdown": "# `@svgrid/enterprise` · `server/svgrid-adapter.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\server\\svgrid-adapter.ts`.\n\n### `type CallbackServerRequest`\n\nThe request a callback-style datasource receives; the subset the adapter reads.\n\n```ts\nexport type CallbackServerRequest = {\n startRow?: number\n endRow?: number\n rowGroupCols: Array<{ id: string; displayName?: string; field?: string; aggFunc?: string | null }>\n groupKeys: string[]\n valueCols: Array<{ id: string; displayName?: string; field?: string; aggFunc?: string | null }>\n pivotCols: Array<{ id: string; displayName?: string; field?: string }>\n pivotMode: boolean\n sortModel: Array<{ colId: string; sort: 'asc' | 'desc' }>\n filterModel: Record<string, CallbackColumnFilter> | null\n}\n```\n\n### `type CallbackColumnFilter`\n\nOne column of the callback-style filter model (text, number or set).\n\n```ts\nexport type CallbackColumnFilter = {\n filterType?: string\n type?: string\n filter?: unknown\n filterTo?: unknown\n values?: string[]\n}\n```\n\n### `type CallbackGetRowsParams`\n\nWhat a callback-style datasource's `getRows` receives, and how it answers.\n\n```ts\nexport type CallbackGetRowsParams<TData = unknown> = {\n request: CallbackServerRequest\n success: (result: { rowData: TData[]; rowCount?: number; pivotResultFields?: string[] }) => void\n fail: () => void\n context?: unknown\n parentNode?: { data?: TData } | null\n}\n```\n\n### `type CallbackDatasource`\n\nA datasource in the callback shape: `getRows(params)` answering through `params.success` / `params.fail`.\n\n```ts\nexport type CallbackDatasource<TData = unknown> = {\n getRows(params: CallbackGetRowsParams<TData>): void\n destroy?(): void\n}\n```\n\n### `function fromCallbackFilterModel`\n\nThe callback-style per-column filter model -> `ServerFilterModel`.\n\n```ts\nexport function fromCallbackFilterModel(model: Record<string, CallbackColumnFilter> | null | undefined): ServerFilterModel {\n const columns: NonNullable<ServerFilterModel['columns']> = {}\n for (const [id, f] of Object.entries(model ?? {})) {\n if (!f) continue\n if (f.filterType === 'set' && Array.isArray(f.values)) {\n columns[id] = { operator: 'in', value: '', selectedValues: f.values.map(asString) }\n continue\n }\n const operator = CALLBACK_TO_GRID_OPERATOR[f.type ?? ''] ?? f.type ?? 'equals'\n columns[id] = {\n operator,\n value: asString(f.filter),\n ...(f.filterTo != null ? { valueTo: asString(f.filterTo) } : {}),\n }\n }\n return Object.keys(columns).length ? { columns } : {}\n}\n```\n\n### `function toCallbackFilterModel`\n\n`ServerFilterModel` -> the callback-style per-column filter model. The global search has no form there and is dropped.\n\n```ts\nexport function toCallbackFilterModel(model: ServerFilterModel): Record<string, CallbackColumnFilter> {\n const out: Record<string, CallbackColumnFilter> = {}\n for (const [id, f] of Object.entries(model.columns ?? {})) {\n if (f.selectedValues) {\n out[id] = { filterType: 'set', values: f.selectedValues }\n continue\n }\n out[id] = {\n filterType: 'text',\n type: GRID_TO_CALLBACK_OPERATOR[f.operator] ?? f.operator,\n filter: f.value,\n ...(f.valueTo != null ? { filterTo: f.valueTo } : {}),\n }\n }\n return out\n}\n```\n\n### `function toCallbackRequest`\n\n`ServerRequest` -> the callback-style request shape.\n\n```ts\nexport function toCallbackRequest(req: ServerRequest): CallbackServerRequest {\n return {\n startRow: req.startRow,\n endRow: req.endRow,\n rowGroupCols: (req.groupBy ?? []).map((id) => ({ id, field: id, displayName: id })),\n groupKeys: [...(req.groupKeys ?? [])],\n valueCols: (req.aggregations ?? []).map((a) => ({ id: a.col, field: a.col, displayName: a.col, aggFunc: a.fn })),\n pivotCols: (req.pivotBy ?? []).map((id) => ({ id, field: id, displayName: id })),\n pivotMode: !!req.pivotMode,\n sortModel: req.sortModel.map((s) => ({ colId: s.id, sort: s.desc ? 'desc' : 'asc' })),\n filterModel: toCallbackFilterModel(req.filterModel),\n }\n}\n```\n\n### `function fromCallbackRequest`\n\nThe callback-style request shape -> `ServerRequest`.\n\n```ts\nexport function fromCallbackRequest(req: CallbackServerRequest, extra: Partial<ServerRequest> = {}): ServerRequest {\n const startRow = req.startRow ?? 0\n const endRow = req.endRow ?? startRow + 100\n const pageSize = Math.max(1, endRow - startRow)\n const sortModel: ServerSortModel = req.sortModel.map((s) => ({ id: s.colId, desc: s.sort === 'desc' }))\n const out: ServerRequest = {\n startRow,\n endRow,\n pageIndex: Math.floor(startRow / pageSize),\n pageSize,\n sortModel,\n filterModel: fromCallbackFilterModel(req.filterModel),\n ...extra,\n }\n if (req.rowGroupCols.length) {\n out.groupBy = req.rowGroupCols.map((c) => c.id)\n out.groupKeys = [...req.groupKeys]\n }\n if (req.valueCols.length) {\n out.aggregations = req.valueCols.map((c) => ({\n col: c.id,\n fn: (c.aggFunc ?? 'sum') as 'sum' | 'avg' | 'min' | 'max' | 'count',\n }))\n }\n if (req.pivotMode && req.pivotCols.length) {\n out.pivotBy = req.pivotCols.map((c) => c.id)\n out.pivotMode = true\n }\n return out\n}\n```\n\n### `function adaptCallbackDatasource`\n\nWrap a callback-style datasource so `createServerRowModel` (or\n`createServerDataSource`) can drive it.\n\n```ts\nconst ctl = createServerRowModel(adaptCallbackDatasource(myDatasource), { groupBy: ['country'] })\n```\n\n```ts\nexport function adaptCallbackDatasource<TData>(ds: CallbackDatasource<TData>): ServerDataSource<TData> {\n return {\n getRows(req) {\n return new Promise<ServerResult<TData>>((resolve, reject) => {\n let settled = false\n ds.getRows({\n request: toCallbackRequest(req),\n context: req.context,\n parentNode: req.parentRow === undefined ? null : { data: req.parentRow as TData },\n success: ({ rowData, rowCount, pivotResultFields }) => {\n if (settled) return\n settled = true\n const result: ServerResult<TData> = {\n rows: rowData,\n rowCount: rowCount == null || rowCount < 0 ? -1 : rowCount,\n }\n if (pivotResultFields) result.pivotResultFields = pivotResultFields\n resolve(result)\n },\n fail: () => {\n if (settled) return\n settled = true\n reject(new Error('The datasource reported a failed load'))\n },\n })\n })\n },\n ...(ds.destroy ? { destroy: () => ds.destroy!() } : {}),\n }\n}\n```\n\n### `function toCallbackDatasource`\n\nThe other direction: a `ServerDataSource` as a callback-style datasource,\nso one backend can serve two grids side by side.\n\n```ts\nexport function toCallbackDatasource<TData>(source: ServerDataSource<TData>): CallbackDatasource<TData> {\n return {\n getRows(params) {\n const extra: Partial<ServerRequest> = {}\n if (params.context !== undefined) extra.context = params.context\n if (params.parentNode?.data !== undefined) extra.parentRow = params.parentNode.data as never\n source.getRows(fromCallbackRequest(params.request, extra)).then(\n (res) => {\n params.success({\n rowData: [...res.rows],\n rowCount: res.rowCount < 0 ? undefined : res.rowCount,\n ...(res.pivotResultFields ? { pivotResultFields: res.pivotResultFields } : {}),\n })\n },\n () => params.fail(),\n )\n },\n ...(source.destroy ? { destroy: () => source.destroy!() } : {}),\n }\n}\n```\n\n### `type CallbackSelectionState`\n\nThe flat selection rule in the callback-style shape.\n\n```ts\nexport type CallbackSelectionState = {\n selectAll: boolean\n /** Exceptions to `selectAll`, as row ids. */\n toggledNodes: string[]\n}\n```\n\n### `type CallbackGroupSelectionState`\n\nOne node of the callback-style hierarchical rule. The root carries no\n`nodeId`; a child is a group row or a leaf, told apart by whether it has\nexceptions of its own (see `SelectionStateMapping.isGroup`).\n\n```ts\nexport type CallbackGroupSelectionState = {\n nodeId?: string\n selectAllChildren?: boolean\n toggledNodes?: CallbackGroupSelectionState[]\n}\n```\n\n### `type SelectionStateMapping`\n\nHow group rows are named across the two shapes. This model keys a group\nby its route segment (`['EMEA', 'DE']` is the DE group under EMEA); the\ncallback shape keys it by a row node id that the app chose. When the two\nare the same string - the default - nothing needs to be passed.\n\n```ts\nexport type SelectionStateMapping = {\n /** The node id of the group at `route`. Default: the last key of the route. */\n groupId?: (route: string[]) => string\n /** The group key for a node id under `parentRoute`. Default: the id itself. */\n groupKey?: (nodeId: string, parentRoute: string[]) => string\n /**\n * Whether the node `nodeId` under `parentRoute` is a group row. Default:\n * it is when it carries exceptions of its own, a leaf otherwise. A flipped\n * group read as a leaf still selects the same rows; only `selectedCount`\n * is off, since a group exception has no size of its own.\n */\n isGroup?: (nodeId: string, parentRoute: string[]) => boolean\n}\n```\n\n### `function isCallbackSelectionState`\n\nWhether a selection state is in the callback-style shape (either level).\n\n```ts\nexport function isCallbackSelectionState(\n state: unknown,\n): state is CallbackSelectionState | CallbackGroupSelectionState {\n return typeof state === 'object' && state !== null && 'toggledNodes' in state\n}\n```\n\n### `function toCallbackSelectionState`\n\nThe selection rule -> the callback-style shape, flat or per group.\n\n```ts\nexport function toCallbackSelectionState(\n state: ServerSelectionState | ServerGroupSelectionNode,\n mapping: SelectionStateMapping = {},\n): CallbackSelectionState | CallbackGroupSelectionState {\n if ('selectAll' in state) return { selectAll: !!state.selectAll, toggledNodes: [...(state.toggled ?? [])] }\n const walk = (node: ServerGroupSelectionNode, route: string[]): CallbackGroupSelectionState => {\n const out: CallbackGroupSelectionState = {}\n if (route.length) {\n out.nodeId = node.group ? (mapping.groupId?.(route) ?? route[route.length - 1]!) : route[route.length - 1]!\n }\n out.selectAllChildren = !!node.selectAllChildren\n out.toggledNodes = Object.entries(node.toggled ?? {}).map(([key, child]) => walk(child, [...route, key]))\n return out\n }\n return walk(state, [])\n}\n```\n\n### `function fromCallbackSelectionState`\n\nThe callback-style shape -> the selection rule this model keeps.\n\n```ts\nexport function fromCallbackSelectionState(\n state: CallbackSelectionState | CallbackGroupSelectionState,\n mapping: SelectionStateMapping = {},\n): ServerSelectionState | ServerGroupSelectionNode {\n if ('selectAll' in state) {\n const flat = state as CallbackSelectionState\n return { selectAll: !!flat.selectAll, toggled: (flat.toggledNodes ?? []).map(String) }\n }\n const walk = (node: CallbackGroupSelectionState, route: string[]): ServerGroupSelectionNode => {\n const toggled: Record<string, ServerGroupSelectionNode> = {}\n for (const child of node.toggledNodes ?? []) {\n if (child.nodeId == null) continue\n const id = String(child.nodeId)\n const group = mapping.isGroup?.(id, route) ?? (child.toggledNodes?.length ?? 0) > 0\n const key = group ? (mapping.groupKey?.(id, route) ?? id) : id\n const plain = walk(child, [...route, key])\n toggled[key] = group ? { ...plain, group: true } : plain\n }\n return { selectAllChildren: !!node.selectAllChildren, toggled }\n }\n return walk(state, [])\n}\n```\n"
7793
+ "markdown": "# `@svgrid/enterprise` · `server/svgrid-adapter.ts`\n\nAuto-generated. Source: `packages\\enterprise\\src\\server\\svgrid-adapter.ts`.\n\n### `type CallbackServerRequest`\n\nThe request a callback-style datasource receives; the subset the adapter reads.\n\n```ts\nexport type CallbackServerRequest = {\n startRow?: number\n endRow?: number\n rowGroupCols: Array<{ id: string; displayName?: string; field?: string; aggFunc?: string | null }>\n groupKeys: string[]\n valueCols: Array<{ id: string; displayName?: string; field?: string; aggFunc?: string | null }>\n pivotCols: Array<{ id: string; displayName?: string; field?: string }>\n pivotMode: boolean\n sortModel: Array<{ colId: string; sort: 'asc' | 'desc' }>\n filterModel: Record<string, CallbackColumnFilter> | null\n}\n```\n\n### `type CallbackColumnFilter`\n\nOne column of the callback-style filter model (text, number or set).\n\n```ts\nexport type CallbackColumnFilter = {\n filterType?: string\n type?: string\n filter?: unknown\n filterTo?: unknown\n values?: string[]\n}\n```\n\n### `type CallbackGetRowsParams`\n\nWhat a callback-style datasource's `getRows` receives, and how it answers.\n\n```ts\nexport type CallbackGetRowsParams<TData = unknown> = {\n request: CallbackServerRequest\n success: (result: { rowData: TData[]; rowCount?: number; pivotResultFields?: string[] }) => void\n fail: () => void\n context?: unknown\n parentNode?: { data?: TData } | null\n}\n```\n\n### `type CallbackDatasource`\n\nA datasource in the callback shape: `getRows(params)` answering through `params.success` / `params.fail`.\n\n```ts\nexport type CallbackDatasource<TData = unknown> = {\n getRows(params: CallbackGetRowsParams<TData>): void\n destroy?(): void\n}\n```\n\n### `function fromCallbackFilterModel`\n\nThe callback-style per-column filter model -> `ServerFilterModel`.\n\n```ts\nexport function fromCallbackFilterModel(model: Record<string, CallbackColumnFilter> | null | undefined): ServerFilterModel\n```\n\n### `function toCallbackFilterModel`\n\n`ServerFilterModel` -> the callback-style per-column filter model. The global search has no form there and is dropped.\n\n```ts\nexport function toCallbackFilterModel(model: ServerFilterModel): Record<string, CallbackColumnFilter>\n```\n\n### `function toCallbackRequest`\n\n`ServerRequest` -> the callback-style request shape.\n\n```ts\nexport function toCallbackRequest(req: ServerRequest): CallbackServerRequest\n```\n\n### `function fromCallbackRequest`\n\nThe callback-style request shape -> `ServerRequest`.\n\n```ts\nexport function fromCallbackRequest(req: CallbackServerRequest, extra: Partial<ServerRequest> = {}): ServerRequest\n```\n\n### `function adaptCallbackDatasource`\n\nWrap a callback-style datasource so `createServerRowModel` (or\n`createServerDataSource`) can drive it.\n\n```ts\nconst ctl = createServerRowModel(adaptCallbackDatasource(myDatasource), { groupBy: ['country'] })\n```\n\n```ts\nexport function adaptCallbackDatasource<TData>(ds: CallbackDatasource<TData>): ServerDataSource<TData>\n```\n\n### `function toCallbackDatasource`\n\nThe other direction: a `ServerDataSource` as a callback-style datasource,\nso one backend can serve two grids side by side.\n\n```ts\nexport function toCallbackDatasource<TData>(source: ServerDataSource<TData>): CallbackDatasource<TData>\n```\n\n### `type CallbackSelectionState`\n\nThe flat selection rule in the callback-style shape.\n\n```ts\nexport type CallbackSelectionState = {\n selectAll: boolean\n /** Exceptions to `selectAll`, as row ids. */\n toggledNodes: string[]\n}\n```\n\n### `type CallbackGroupSelectionState`\n\nOne node of the callback-style hierarchical rule. The root carries no\n`nodeId`; a child is a group row or a leaf, told apart by whether it has\nexceptions of its own (see `SelectionStateMapping.isGroup`).\n\n```ts\nexport type CallbackGroupSelectionState = {\n nodeId?: string\n selectAllChildren?: boolean\n toggledNodes?: CallbackGroupSelectionState[]\n}\n```\n\n### `type SelectionStateMapping`\n\nHow group rows are named across the two shapes. This model keys a group\nby its route segment (`['EMEA', 'DE']` is the DE group under EMEA); the\ncallback shape keys it by a row node id that the app chose. When the two\nare the same string - the default - nothing needs to be passed.\n\n```ts\nexport type SelectionStateMapping = {\n /** The node id of the group at `route`. Default: the last key of the route. */\n groupId?: (route: string[]) => string\n /** The group key for a node id under `parentRoute`. Default: the id itself. */\n groupKey?: (nodeId: string, parentRoute: string[]) => string\n /**\n * Whether the node `nodeId` under `parentRoute` is a group row. Default:\n * it is when it carries exceptions of its own, a leaf otherwise. A flipped\n * group read as a leaf still selects the same rows; only `selectedCount`\n * is off, since a group exception has no size of its own.\n */\n isGroup?: (nodeId: string, parentRoute: string[]) => boolean\n}\n```\n\n### `function isCallbackSelectionState`\n\nWhether a selection state is in the callback-style shape (either level).\n\n```ts\nexport function isCallbackSelectionState(\n state: unknown,\n): state is CallbackSelectionState | CallbackGroupSelectionState\n```\n\n### `function toCallbackSelectionState`\n\nThe selection rule -> the callback-style shape, flat or per group.\n\n```ts\nexport function toCallbackSelectionState(\n state: ServerSelectionState | ServerGroupSelectionNode,\n mapping: SelectionStateMapping = {},\n): CallbackSelectionState | CallbackGroupSelectionState\n```\n\n### `function fromCallbackSelectionState`\n\nThe callback-style shape -> the selection rule this model keeps.\n\n```ts\nexport function fromCallbackSelectionState(\n state: CallbackSelectionState | CallbackGroupSelectionState,\n mapping: SelectionStateMapping = {},\n): ServerSelectionState | ServerGroupSelectionNode\n```\n"
7723
7794
  },
7724
7795
  {
7725
7796
  "slug": "reference/auto/svgrid-grid-SvGridChart.types",
@@ -7733,182 +7804,182 @@ export const docs = [
7733
7804
  "path": "docs/reference/auto/svgrid-grid-advanced-filter.svelte.md",
7734
7805
  "title": "@svgrid/grid · advanced-filter.svelte.ts",
7735
7806
  "section": "API reference",
7736
- "markdown": "# `@svgrid/grid` · `advanced-filter.svelte.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\advanced-filter.svelte.ts`.\n\n### `type AdvancedFilterCompileContext`\n\nWhat the engine needs in order to compile an expression into a predicate.\n\n```ts\nexport type AdvancedFilterCompileContext<TRow> = {\n /**\n * Resolve a column id to its cell value for a row. The grid passes the same\n * accessor the column-menu filter stage uses, so a `cmp` on a `fieldFn` or\n * value-getter column resolves identically in both.\n */\n getValue: (row: TRow, columnId: string) => unknown\n /** Locale for text folding, matching the column filters. */\n locale?: string | ReadonlyArray<string>\n /**\n * The rows entering this stage. Aggregates (`SUM(amount) > 1000`) are folded\n * over exactly these, once, so they see the rows the user is currently\n * looking at rather than the raw dataset.\n */\n rows: ReadonlyArray<TRow>\n}\n```\n\n### `type CompiledRowPredicate`\n\nA compiled expression: cheap to call once per row.\n\n```ts\nexport type CompiledRowPredicate<TRow> = (row: TRow) => boolean\n```\n\n### `type AdvancedFilterEngine`\n\nCompile an expression to a row predicate.\n\nReturns `null` when the expression cannot be compiled (an unknown node kind,\nan unresolvable column). Must never throw: the grid treats both `null` and a\nthrown error as \"do not filter\", because a half-applied filter silently\nshowing the wrong rows is worse than an unapplied one.\n\n```ts\nexport type AdvancedFilterEngine = <TRow>(\n expr: GridPredicateExpr,\n ctx: AdvancedFilterCompileContext<TRow>,\n) => CompiledRowPredicate<TRow> | null\n```\n\n### `function registerAdvancedFilterEngine`\n\nRegister the engine. Enterprise calls this from `enableAdvancedFilter()`.\n\n```ts\nexport function registerAdvancedFilterEngine(fn: AdvancedFilterEngine | null): void {\n engine = fn\n}\n```\n\n### `function getAdvancedFilterEngine`\n\nThe registered engine, or null when enterprise is not installed.\n\n```ts\nexport function getAdvancedFilterEngine(): AdvancedFilterEngine | null {\n return engine\n}\n```\n\n### `function hasAdvancedFilterEngine`\n\nWhether an advanced-filter engine has been registered.\n\n```ts\nexport function hasAdvancedFilterEngine(): boolean {\n return engine != null\n}\n```\n"
7807
+ "markdown": "# `@svgrid/grid` · `advanced-filter.svelte.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\advanced-filter.svelte.ts`.\n\n### `type AdvancedFilterCompileContext`\n\nWhat the engine needs in order to compile an expression into a predicate.\n\n```ts\nexport type AdvancedFilterCompileContext<TRow> = {\n /**\n * Resolve a column id to its cell value for a row. The grid passes the same\n * accessor the column-menu filter stage uses, so a `cmp` on a `fieldFn` or\n * value-getter column resolves identically in both.\n */\n getValue: (row: TRow, columnId: string) => unknown\n /** Locale for text folding, matching the column filters. */\n locale?: string | ReadonlyArray<string>\n /**\n * The rows entering this stage. Aggregates (`SUM(amount) > 1000`) are folded\n * over exactly these, once, so they see the rows the user is currently\n * looking at rather than the raw dataset.\n */\n rows: ReadonlyArray<TRow>\n}\n```\n\n### `type CompiledRowPredicate`\n\nA compiled expression: cheap to call once per row.\n\n```ts\nexport type CompiledRowPredicate<TRow> = (row: TRow) => boolean\n```\n\n### `type AdvancedFilterEngine`\n\nCompile an expression to a row predicate.\n\nReturns `null` when the expression cannot be compiled (an unknown node kind,\nan unresolvable column). Must never throw: the grid treats both `null` and a\nthrown error as \"do not filter\", because a half-applied filter silently\nshowing the wrong rows is worse than an unapplied one.\n\n```ts\nexport type AdvancedFilterEngine = <TRow>(\n expr: GridPredicateExpr,\n ctx: AdvancedFilterCompileContext<TRow>,\n) => CompiledRowPredicate<TRow> | null\n```\n\n### `function registerAdvancedFilterEngine`\n\nRegister the engine. Enterprise calls this from `enableAdvancedFilter()`.\n\n```ts\nexport function registerAdvancedFilterEngine(fn: AdvancedFilterEngine | null): void\n```\n\n### `function getAdvancedFilterEngine`\n\nThe registered engine, or null when enterprise is not installed.\n\n```ts\nexport function getAdvancedFilterEngine(): AdvancedFilterEngine | null\n```\n\n### `function hasAdvancedFilterEngine`\n\nWhether an advanced-filter engine has been registered.\n\n```ts\nexport function hasAdvancedFilterEngine(): boolean\n```\n"
7737
7808
  },
7738
7809
  {
7739
7810
  "slug": "reference/auto/svgrid-grid-ai",
7740
7811
  "path": "docs/reference/auto/svgrid-grid-ai.md",
7741
7812
  "title": "@svgrid/grid · ai.ts",
7742
7813
  "section": "API reference",
7743
- "markdown": "# `@svgrid/grid` · `ai.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\ai.ts`.\n\n### `type AIProvider`\n\nShape every consumer-provided model adapter must implement. Keeping this\ntiny (one async call, two response formats) lets the same adapter drive\nOpenAI's `chat.completions`, Anthropic's `messages`, a self-hosted\nllama.cpp endpoint, or a server-side proxy. The grid only cares that the\nprovider eventually returns a string we can parse.\n\n```ts\nexport type AIProvider = (request: AIRequest) => Promise<string>\n```\n\n### `type AIRequest`\n\nOne call out to the model, as the grid builds it. Providers receive this.\n\n```ts\nexport type AIRequest = {\n /** Full prompt the grid built for the model. Already includes column\n * schema and any sampled rows where applicable. */\n prompt: string\n /** When 'json', the provider should ask the model to return strict\n * JSON only - no prose. We parse the response with JSON.parse and\n * throw a typed error on failure. */\n responseFormat?: 'text' | 'json'\n /** Honored if the underlying transport supports cancellation. */\n signal?: AbortSignal\n /** Free-form tag for telemetry / logging. One of: 'filter',\n * 'smart-fill', 'summarize', 'classify'. */\n task: AITask\n /** Soft hint to the provider about how many tokens we expect back.\n * Useful for routing small jobs to a cheaper model. */\n maxOutputTokens?: number\n}\n```\n\n### `type AITask`\n\nWhich helper produced a request - carried on {@link AIRequest} for routing and telemetry.\n\n```ts\nexport type AITask = 'filter' | 'smart-fill' | 'summarize' | 'classify' | 'export' | 'anomaly' | 'chart' | 'explain-chart'\n```\n\n### `function setAIProvider`\n\nRegister the model adapter every AI call will route through. Call once\nat app boot. Passing `null` clears the provider and AI calls revert to\nthrowing \"no provider\" errors.\n\n```ts\nexport function setAIProvider(p: AIProvider | null): void {\n provider = p\n}\n```\n\n### `function getAIProvider`\n\nThe provider registered with `setAIProvider`, or null when none is.\n\n```ts\nexport function getAIProvider(): AIProvider | null {\n return provider\n}\n```\n\n### `function hasAIProvider`\n\nWhether an AI provider is registered. Gate AI affordances on this so the UI stays honest.\n\n```ts\nexport function hasAIProvider(): boolean {\n return provider != null\n}\n```\n\n### `type AIRowSource`\n\nWhat the read-only helpers need from a grid: its rows. A full `SvGridApi`\nsatisfies it, and so does `{ getData: () => rows }`, which lets a chat or a\nreport summarize data that is not on screen in a grid. `aiFilter` with\n`apply: true` and `aiExport` still need the grid itself.\n\n```ts\nexport type AIRowSource<\n TFeatures extends TableFeatures = TableFeatures,\n TData extends RowData = RowData,\n> = Pick<SvGridApi<TFeatures, TData>, 'getData'>\n```\n\n### `type AIFilterClause`\n\nOne condition in a filter plan: a column, a comparison, and the value to match.\n\n```ts\nexport type AIFilterClause = {\n field: string\n operator: 'contains' | 'equals' | 'startsWith' | 'greaterThan' | 'lessThan' | 'isBlank'\n value?: string\n}\n```\n\n### `type AISortClause`\n\nOne ordering clause in a filter plan.\n\n```ts\nexport type AISortClause = { field: string; desc: boolean }\n```\n\n### `type AIFilterResult`\n\nA natural-language query turned into filters and sorting, plus the model's reasoning.\n\n```ts\nexport type AIFilterResult = {\n filters: AIFilterClause[]\n sort: AISortClause[]\n /** Plain-English explanation of how the model interpreted the query.\n * Surface this in the UI so the user can confirm or undo. */\n rationale: string\n}\n```\n\n### `type AIFilterOptions`\n\nOptions for `aiFilter` - preview the plan, or apply it straight to the grid.\n\n```ts\nexport type AIFilterOptions = {\n /**\n * When true, the helper not only RETURNS the plan but also applies it\n * to the grid via `api.setFilter` / `api.setSort`. Defaults to false\n * so callers can show a preview before committing.\n */\n apply?: boolean\n signal?: AbortSignal\n}\n```\n\n### `type AISmartFillExample`\n\nOne worked example teaching smart-fill what to produce for a row.\n\n```ts\nexport type AISmartFillExample = { input: Record<string, unknown>; output: unknown }\n```\n\n### `type AISmartFillResult`\n\nProposed values for the blank cells of one column, each with a confidence score.\n\n```ts\nexport type AISmartFillResult<TValue = unknown> = {\n field: string\n predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>\n rationale: string\n}\n```\n\n### `type AISmartFillOptions`\n\nOptions for `aiSmartFill` - which column to fill, which rows, and the examples to learn from.\n\n```ts\nexport type AISmartFillOptions = {\n /** Target column - the one whose values we want filled. */\n field: string\n /** Index of rows the model should propose values for. If omitted, every\n * row whose current `field` value is `null`, `undefined` or `''` is\n * selected automatically. */\n targetRowIndices?: number[]\n /**\n * Worked examples the user has already filled in. Required - the\n * model needs at least one to know the pattern, two or more to lock\n * the schema. We don't pull these from the grid automatically because\n * \"edited\" vs \"untouched\" isn't a state SvGrid exposes today.\n */\n examples: AISmartFillExample[]\n signal?: AbortSignal\n}\n```\n\n### `type AISummarizeTarget`\n\nWhat to summarise: one row, the selection, a group, or the whole set.\n\n```ts\nexport type AISummarizeTarget =\n | { kind: 'row'; rowIndex: number }\n | { kind: 'all' }\n | { kind: 'selection'; rowIndices: number[] }\n | { kind: 'group'; field: string; value: unknown }\n```\n\n### `type AISummary`\n\nA generated summary: prose, bullets, and the columns the model leaned on.\n\n```ts\nexport type AISummary = {\n text: string\n bullets: string[]\n /** Field names the model thinks are the most load-bearing for the\n * story it just told. UI can highlight those columns. */\n highlightedFields: string[]\n}\n```\n\n### `type AISummarizeOptions`\n\nOptions for `aiSummarize` - the target, and optionally the question to answer.\n\n```ts\nexport type AISummarizeOptions = {\n target: AISummarizeTarget\n /** Optional question the user is trying to answer. Helps the model\n * bias the summary toward the relevant columns. */\n question?: string\n signal?: AbortSignal\n}\n```\n\n### `type AIClassifyOptions`\n\nOptions for `aiClassify` - the column to label and the categories to choose from.\n\n```ts\nexport type AIClassifyOptions = {\n /** Column whose free-text we're classifying. */\n inputField: string\n /** Target column the model should write to. */\n outputField: string\n /** Allowed values. The model is constrained to pick one. */\n classes: string[]\n /** Optional one-line description of each class (acts as a labeling rubric). */\n classDescriptions?: Record<string, string>\n /** Rows to classify. Defaults to all. */\n targetRowIndices?: number[]\n signal?: AbortSignal\n}\n```\n\n### `type AIClassifyResult`\n\nProposed category labels per row, with the model's reasoning.\n\n```ts\nexport type AIClassifyResult = {\n inputField: string\n outputField: string\n predictions: Array<{ rowIndex: number; value: string; confidence: number }>\n}\n```\n\n### `type AIExportPlan`\n\nAn export the model derived from a request: format, columns, and scope.\n\n```ts\nexport type AIExportPlan = {\n format: ExportFormat\n filters: AIFilterClause[]\n sort: AISortClause[]\n groupBy: string[]\n /** Plain-English explanation of how the model read the request. */\n rationale: string\n}\n```\n\n### `type AIExportOptions`\n\nOptions for `aiExport` - preview the plan, or run the export it describes.\n\n```ts\nexport type AIExportOptions = {\n /**\n * Also apply the filter / sort / grouping to the grid (mutating the view) so\n * it mirrors the export. Default FALSE - the export is self-contained (it\n * computes its own rows), so the grid is left untouched unless you opt in.\n */\n apply?: boolean\n /** Actually download the file. Default true; set false to preview the plan. */\n run?: boolean\n /** Base filename (no extension). Default 'export'. */\n filename?: string\n signal?: AbortSignal\n}\n```\n\n### `type AIAnomaly`\n\nOne flagged value, with why it stands out and how strongly.\n\n```ts\nexport type AIAnomaly = {\n /** Index into the SCANNED rows (target order), when the model pins one row. */\n rowIndex?: number\n field?: string\n value?: unknown\n reason: string\n severity: 'low' | 'medium' | 'high'\n}\n```\n\n### `type AIAnomalyResult`\n\nEverything an anomaly scan flagged across the rows it looked at.\n\n```ts\nexport type AIAnomalyResult = {\n anomalies: AIAnomaly[]\n summary: string\n}\n```\n\n### `type AIAnomalyOptions`\n\nOptions for `aiFindAnomalies` - which rows and columns to scan.\n\n```ts\nexport type AIAnomalyOptions = {\n /** Which rows to scan. Defaults to the whole dataset. */\n target?: AISummarizeTarget\n /** Optional focus, e.g. \"look at pricing and margins\". */\n question?: string\n signal?: AbortSignal\n}\n```\n\n### `type AIChartType`\n\nChart shapes the model may choose from when planning a visualisation.\n\nThese are exactly the types the built-in panel can build from a dimension, a\nmeasure and an optional split - which is all a chart plan carries. Scatter\nis deliberately absent, because a plan cannot express its SECOND measure.\nA candlestick can be asked for: the panel finds the open / high / low /\nclose / volume columns by name, so the plan only needs a date dimension.\n\n```ts\nexport type AIChartType =\n | 'bar' | 'line' | 'area' | 'pie'\n | 'treemap' | 'funnel' | 'waterfall' | 'radar'\n | 'heatmap' | 'boxplot' | 'gauge' | 'calendar' | 'sankey'\n | 'histogram' | 'lollipop' | 'pareto' | 'sunburst' | 'radial-bar' | 'radial-column' | 'nightingale' | 'bullet' | 'chord' | 'stream'\n | 'candlestick'\n```\n\n### `type AIChartIndicator`\n\nThe indicators a chart plan may ask for on a candlestick.\n\n```ts\nexport type AIChartIndicator = 'volume' | 'rsi' | 'macd' | 'stochastic' | 'atr' | 'obv' | 'sma' | 'ema' | 'bb' | 'vwap'\n```\n\n### `type AIChartPlan`\n\nA chart the model proposed: its type, and the fields to plot.\n\n```ts\nexport type AIChartPlan = {\n type: AIChartType\n /** Group-by (category-axis) column field, or null. */\n dimension: string | null\n /** Split-by column field: one series per distinct value, or null. */\n series: string | null\n /** Measure (value-axis) column field, or null. */\n measure: string | null\n reduce: AIChartReduce\n stacked: boolean\n logScale: boolean\n timeAxis: boolean\n valueFormat: 'number' | 'currency' | 'percent'\n /** Calendar unit to group a date dimension by, or null for exact values. */\n bucket: 'day' | 'week' | 'month' | 'quarter' | 'year' | null\n /** Candlestick only: indicator panes and overlays to add. */\n indicators?: AIChartIndicator[]\n rationale: string\n /** With `apply`: what `validateChartSpec` flagged as an error on the spec\n * the panel built from the plan, empty when it drew cleanly. */\n diagnostics?: ChartDiagnostic[]\n}\n```\n\n### `type AIChartReduce`\n\nThe reducers a chart plan may name: the panel's full list.\n\n```ts\nexport type AIChartReduce =\n | 'sum' | 'avg' | 'count' | 'min' | 'max' | 'median' | 'p90' | 'first' | 'last' | 'countDistinct'\n```\n\n### `type AIChartOptions`\n\nOptions for `aiChart` - preview the plan, or render it into the grid.\n\n```ts\nexport type AIChartOptions = {\n /** Apply the plan to the grid's chart panel (open + configure). Default false. */\n apply?: boolean\n signal?: AbortSignal\n}\n```\n\n### `type AIChartExplanation`\n\nWhat `aiExplainChart` returns: the grounded summary and the model's insights.\n\n```ts\nexport type AIChartExplanation = {\n /** The plain-language reading of the chart (`chartSummary`), as the model saw it. */\n summary: string\n /** Two to three observations the model added: comparisons, outliers, what to look at next. */\n insights: string[]\n}\n```\n\n### `type AIExplainChartOptions`\n\nOptions for `aiExplainChart`.\n\n```ts\nexport type AIExplainChartOptions = {\n /** The spec to explain. Default: the grid panel's active chart. */\n spec?: ChartSpec\n signal?: AbortSignal\n}\n```\n\n### `function enableAiCharting`\n\nWire the grid's chart-panel AI button to the model: registers a handler (via\n`api.setChartAiHandler`) that runs `aiChart` and returns the plan for the\npanel to apply + explain. Call once after `onApiReady`. `installEnterprise`\ncalls this for you.\n\n```ts\nexport function enableAiCharting<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(api: SvGridApi<TFeatures, TData>): void {\n const hook = api as unknown as {\n setChartAiHandler?: (\n fn: ((prompt: string) => Promise<Record<string, unknown> | null>) | null,\n ) => void\n }\n hook.setChartAiHandler?.(async (prompt: string) => {\n const plan = await aiChart(api, prompt)\n return {\n type: plan.type,\n dimension: plan.dimension,\n series: plan.series,\n measure: plan.measure,\n reduce: plan.reduce,\n stacked: plan.stacked,\n logScale: plan.logScale,\n timeAxis: plan.timeAxis,\n valueFormat: plan.valueFormat,\n bucket: plan.bucket,\n rationale: plan.rationale,\n }\n })\n // And the Explain button beside it.\n const explain = api as unknown as { setChartExplainHandler?: (fn: (() => Promise<AIChartExplanation | null>) | null) => void }\n explain.setChartExplainHandler?.(() => aiExplainChart(api))\n}\n```\n\n### `function disableAiCharting`\n\nRemove the natural-language chart handler, hiding the AI button in the chart\npanel. The inverse of `enableAiCharting`; safe to call when none was set.\n\n```ts\nexport function disableAiCharting<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(api: SvGridApi<TFeatures, TData>): void {\n const hook = api as unknown as { setChartAiHandler?: (fn: null) => void; setChartExplainHandler?: (fn: null) => void }\n hook.setChartAiHandler?.(null)\n hook.setChartExplainHandler?.(null)\n}\n```\n\n### `const mockAIProvider`\n\nA deterministic provider that returns canned, schema-shaped responses\nfor each task. Wire it in via `setAIProvider(mockAIProvider)` to make\nthe AI demo work end-to-end without a real model key. Not for production.\n\n```ts\nexport const mockAIProvider: AIProvider = async (req) => {\n // Tiny artificial delay so the UI's \"thinking\" state is visible.\n await new Promise((r) => setTimeout(r, 350 + Math.random() * 400))\n\n if (req.task === 'filter') {\n const q = extractUserQuery(req.prompt)\n return JSON.stringify(buildMockFilter(req.prompt, q))\n }\n if (req.task === 'smart-fill') {\n return JSON.stringify(buildMockSmartFill(req.prompt))\n }\n if (req.task === 'summarize') {\n return JSON.stringify(buildMockSummary(req.prompt))\n }\n if (req.task === 'classify') {\n return JSON.stringify(buildMockClassify(req.prompt))\n }\n if (req.task === 'export') {\n return JSON.stringify(buildMockExport(req.prompt))\n }\n if (req.task === 'anomaly') {\n return JSON.stringify(buildMockAnomaly(req.prompt))\n }\n if (req.task === 'chart') {\n return JSON.stringify(buildMockChart(req.prompt))\n }\n if (req.task === 'explain-chart') {\n // Two canned observations round the reading the prompt was grounded on.\n const reading = /Reading of the chart: ([^\\n]+)/.exec(req.prompt)?.[1] ?? ''\n const rises = /rises/.test(reading)\n return JSON.stringify({\n insights: [\n rises ? 'The growth is front-loaded: the early categories carry most of the change.' : 'The movement is gradual with no single category driving it.',\n 'Compare the peak against the same category a period earlier before reading it as a trend.',\n ],\n })\n }\n return '{}'\n}\n```\n"
7814
+ "markdown": "# `@svgrid/grid` · `ai.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\ai.ts`.\n\n### `type AIProvider`\n\nShape every consumer-provided model adapter must implement. Keeping this\ntiny (one async call, two response formats) lets the same adapter drive\nOpenAI's `chat.completions`, Anthropic's `messages`, a self-hosted\nllama.cpp endpoint, or a server-side proxy. The grid only cares that the\nprovider eventually returns a string we can parse.\n\n```ts\nexport type AIProvider = (request: AIRequest) => Promise<string>\n```\n\n### `type AIRequest`\n\nOne call out to the model, as the grid builds it. Providers receive this.\n\n```ts\nexport type AIRequest = {\n /** Full prompt the grid built for the model. Already includes column\n * schema and any sampled rows where applicable. */\n prompt: string\n /** When 'json', the provider should ask the model to return strict\n * JSON only - no prose. We parse the response with JSON.parse and\n * throw a typed error on failure. */\n responseFormat?: 'text' | 'json'\n /** Honored if the underlying transport supports cancellation. */\n signal?: AbortSignal\n /** Free-form tag for telemetry / logging. One of: 'filter',\n * 'smart-fill', 'summarize', 'classify'. */\n task: AITask\n /** Soft hint to the provider about how many tokens we expect back.\n * Useful for routing small jobs to a cheaper model. */\n maxOutputTokens?: number\n}\n```\n\n### `type AITask`\n\nWhich helper produced a request - carried on {@link AIRequest} for routing and telemetry.\n\n```ts\nexport type AITask = 'filter' | 'smart-fill' | 'summarize' | 'classify' | 'export' | 'anomaly' | 'chart' | 'explain-chart'\n```\n\n### `function setAIProvider`\n\nRegister the model adapter every AI call will route through. Call once\nat app boot. Passing `null` clears the provider and AI calls revert to\nthrowing \"no provider\" errors.\n\n```ts\nexport function setAIProvider(p: AIProvider | null): void\n```\n\n### `function getAIProvider`\n\nThe provider registered with `setAIProvider`, or null when none is.\n\n```ts\nexport function getAIProvider(): AIProvider | null\n```\n\n### `function hasAIProvider`\n\nWhether an AI provider is registered. Gate AI affordances on this so the UI stays honest.\n\n```ts\nexport function hasAIProvider(): boolean\n```\n\n### `type AIRowSource`\n\nWhat the read-only helpers need from a grid: its rows. A full `SvGridApi`\nsatisfies it, and so does `{ getData: () => rows }`, which lets a chat or a\nreport summarize data that is not on screen in a grid. `aiFilter` with\n`apply: true` and `aiExport` still need the grid itself.\n\n```ts\nexport type AIRowSource<\n TFeatures extends TableFeatures = TableFeatures,\n TData extends RowData = RowData,\n> = Pick<SvGridApi<TFeatures, TData>, 'getData'>\n```\n\n### `type AIFilterClause`\n\nOne condition in a filter plan: a column, a comparison, and the value to match.\n\n```ts\nexport type AIFilterClause = {\n field: string\n operator: 'contains' | 'equals' | 'startsWith' | 'greaterThan' | 'lessThan' | 'isBlank'\n value?: string\n}\n```\n\n### `type AISortClause`\n\nOne ordering clause in a filter plan.\n\n```ts\nexport type AISortClause = { field: string; desc: boolean }\n```\n\n### `type AIFilterResult`\n\nA natural-language query turned into filters and sorting, plus the model's reasoning.\n\n```ts\nexport type AIFilterResult = {\n filters: AIFilterClause[]\n sort: AISortClause[]\n /** Plain-English explanation of how the model interpreted the query.\n * Surface this in the UI so the user can confirm or undo. */\n rationale: string\n}\n```\n\n### `type AIFilterOptions`\n\nOptions for `aiFilter` - preview the plan, or apply it straight to the grid.\n\n```ts\nexport type AIFilterOptions = {\n /**\n * When true, the helper not only RETURNS the plan but also applies it\n * to the grid via `api.setFilter` / `api.setSort`. Defaults to false\n * so callers can show a preview before committing.\n */\n apply?: boolean\n signal?: AbortSignal\n}\n```\n\n### `function aiFilter`\n\nTranslate a natural-language query into a filter+sort plan against\nthe current grid's columns. The grid passes the column schema (names,\ntypes, sample values) to the model so it can pick the right field\nnames without hallucinating.\n\n```ts\nexport async function aiFilter<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n api: AIRowSource<TFeatures, TData>,\n query: string,\n opts: AIFilterOptions = {},\n): Promise<AIFilterResult>\n```\n\n### `type AISmartFillExample`\n\nOne worked example teaching smart-fill what to produce for a row.\n\n```ts\nexport type AISmartFillExample = { input: Record<string, unknown>; output: unknown }\n```\n\n### `type AISmartFillResult`\n\nProposed values for the blank cells of one column, each with a confidence score.\n\n```ts\nexport type AISmartFillResult<TValue = unknown> = {\n field: string\n predictions: Array<{ rowIndex: number; value: TValue; confidence: number }>\n rationale: string\n}\n```\n\n### `type AISmartFillOptions`\n\nOptions for `aiSmartFill` - which column to fill, which rows, and the examples to learn from.\n\n```ts\nexport type AISmartFillOptions = {\n /** Target column - the one whose values we want filled. */\n field: string\n /** Index of rows the model should propose values for. If omitted, every\n * row whose current `field` value is `null`, `undefined` or `''` is\n * selected automatically. */\n targetRowIndices?: number[]\n /**\n * Worked examples the user has already filled in. Required - the\n * model needs at least one to know the pattern, two or more to lock\n * the schema. We don't pull these from the grid automatically because\n * \"edited\" vs \"untouched\" isn't a state SvGrid exposes today.\n */\n examples: AISmartFillExample[]\n signal?: AbortSignal\n}\n```\n\n### `function aiSmartFill`\n\nGiven a column and a few user-provided examples, propose values for the\nuntouched rows. Returns predictions only - the caller chooses whether to\ncommit them via `api.setCellValue`. This is the right shape for an\naccept-per-cell UX with confidence-coloured highlights.\n\n```ts\nexport async function aiSmartFill<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TValue = unknown,\n>(\n api: AIRowSource<TFeatures, TData>,\n opts: AISmartFillOptions,\n): Promise<AISmartFillResult<TValue>>\n```\n\n### `type AISummarizeTarget`\n\nWhat to summarise: one row, the selection, a group, or the whole set.\n\n```ts\nexport type AISummarizeTarget =\n | { kind: 'row'; rowIndex: number }\n | { kind: 'all' }\n | { kind: 'selection'; rowIndices: number[] }\n | { kind: 'group'; field: string; value: unknown }\n```\n\n### `type AISummary`\n\nA generated summary: prose, bullets, and the columns the model leaned on.\n\n```ts\nexport type AISummary = {\n text: string\n bullets: string[]\n /** Field names the model thinks are the most load-bearing for the\n * story it just told. UI can highlight those columns. */\n highlightedFields: string[]\n}\n```\n\n### `type AISummarizeOptions`\n\nOptions for `aiSummarize` - the target, and optionally the question to answer.\n\n```ts\nexport type AISummarizeOptions = {\n target: AISummarizeTarget\n /** Optional question the user is trying to answer. Helps the model\n * bias the summary toward the relevant columns. */\n question?: string\n signal?: AbortSignal\n}\n```\n\n### `function aiSummarize`\n\nAsk the model to summarise a slice of the grid. Caps the row sample at\na model-friendly size; for huge selections it samples uniformly so the\nsummary stays representative without blowing the context window.\n\n```ts\nexport async function aiSummarize<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n api: AIRowSource<TFeatures, TData>,\n opts: AISummarizeOptions,\n): Promise<AISummary>\n```\n\n### `type AIClassifyOptions`\n\nOptions for `aiClassify` - the column to label and the categories to choose from.\n\n```ts\nexport type AIClassifyOptions = {\n /** Column whose free-text we're classifying. */\n inputField: string\n /** Target column the model should write to. */\n outputField: string\n /** Allowed values. The model is constrained to pick one. */\n classes: string[]\n /** Optional one-line description of each class (acts as a labeling rubric). */\n classDescriptions?: Record<string, string>\n /** Rows to classify. Defaults to all. */\n targetRowIndices?: number[]\n signal?: AbortSignal\n}\n```\n\n### `type AIClassifyResult`\n\nProposed category labels per row, with the model's reasoning.\n\n```ts\nexport type AIClassifyResult = {\n inputField: string\n outputField: string\n predictions: Array<{ rowIndex: number; value: string; confidence: number }>\n}\n```\n\n### `function aiClassify`\n\nBucket free-text cells into one of a known set of classes. The model\nis constrained to pick from `opts.classes`; predictions outside the set\nare dropped so the caller can rely on the output being clean enum\nvalues it can write straight back into the grid.\n\n```ts\nexport async function aiClassify<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n api: AIRowSource<TFeatures, TData>,\n opts: AIClassifyOptions,\n): Promise<AIClassifyResult>\n```\n\n### `type AIExportPlan`\n\nAn export the model derived from a request: format, columns, and scope.\n\n```ts\nexport type AIExportPlan = {\n format: ExportFormat\n filters: AIFilterClause[]\n sort: AISortClause[]\n groupBy: string[]\n /** Plain-English explanation of how the model read the request. */\n rationale: string\n}\n```\n\n### `type AIExportOptions`\n\nOptions for `aiExport` - preview the plan, or run the export it describes.\n\n```ts\nexport type AIExportOptions = {\n /**\n * Also apply the filter / sort / grouping to the grid (mutating the view) so\n * it mirrors the export. Default FALSE - the export is self-contained (it\n * computes its own rows), so the grid is left untouched unless you opt in.\n */\n apply?: boolean\n /** Actually download the file. Default true; set false to preview the plan. */\n run?: boolean\n /** Base filename (no extension). Default 'export'. */\n filename?: string\n signal?: AbortSignal\n}\n```\n\n### `function aiExport`\n\nTurn a natural-language request (\"export EU orders from Q2 as a grouped PDF\")\ninto an export: the model returns a `{ format, filters, sort, groupBy }` plan\nagainst the grid's columns; we apply the filter/sort to the grid and hand the\nresult to the registered export engine (@svgrid/enterprise). Returns the plan\nso the UI can show what it did (or preview it first with `run: false`).\n\n```ts\nexport async function aiExport<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n api: SvGridApi<TFeatures, TData>,\n query: string,\n opts: AIExportOptions = {},\n): Promise<AIExportPlan>\n```\n\n### `type AIAnomaly`\n\nOne flagged value, with why it stands out and how strongly.\n\n```ts\nexport type AIAnomaly = {\n /** Index into the SCANNED rows (target order), when the model pins one row. */\n rowIndex?: number\n field?: string\n value?: unknown\n reason: string\n severity: 'low' | 'medium' | 'high'\n}\n```\n\n### `type AIAnomalyResult`\n\nEverything an anomaly scan flagged across the rows it looked at.\n\n```ts\nexport type AIAnomalyResult = {\n anomalies: AIAnomaly[]\n summary: string\n}\n```\n\n### `type AIAnomalyOptions`\n\nOptions for `aiFindAnomalies` - which rows and columns to scan.\n\n```ts\nexport type AIAnomalyOptions = {\n /** Which rows to scan. Defaults to the whole dataset. */\n target?: AISummarizeTarget\n /** Optional focus, e.g. \"look at pricing and margins\". */\n question?: string\n signal?: AbortSignal\n}\n```\n\n### `function aiFindAnomalies`\n\nScan a slice of the grid (all / selection / group) for anomalies - outliers,\nsuspicious values, inconsistencies - and return a structured list plus a\none-line summary. Pairs naturally with an export: \"find the odd ones, then\nexport just those\".\n\n```ts\nexport async function aiFindAnomalies<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n api: AIRowSource<TFeatures, TData>,\n opts: AIAnomalyOptions = {},\n): Promise<AIAnomalyResult>\n```\n\n### `type AIChartType`\n\nChart shapes the model may choose from when planning a visualisation.\n\nThese are exactly the types the built-in panel can build from a dimension, a\nmeasure and an optional split - which is all a chart plan carries. Scatter\nis deliberately absent, because a plan cannot express its SECOND measure.\nA candlestick can be asked for: the panel finds the open / high / low /\nclose / volume columns by name, so the plan only needs a date dimension.\n\n```ts\nexport type AIChartType =\n | 'bar' | 'line' | 'area' | 'pie'\n | 'treemap' | 'funnel' | 'waterfall' | 'radar'\n | 'heatmap' | 'boxplot' | 'gauge' | 'calendar' | 'sankey'\n | 'histogram' | 'lollipop' | 'pareto' | 'sunburst' | 'radial-bar' | 'radial-column' | 'nightingale' | 'bullet' | 'chord' | 'stream'\n | 'candlestick'\n```\n\n### `type AIChartIndicator`\n\nThe indicators a chart plan may ask for on a candlestick.\n\n```ts\nexport type AIChartIndicator = 'volume' | 'rsi' | 'macd' | 'stochastic' | 'atr' | 'obv' | 'sma' | 'ema' | 'bb' | 'vwap'\n```\n\n### `type AIChartPlan`\n\nA chart the model proposed: its type, and the fields to plot.\n\n```ts\nexport type AIChartPlan = {\n type: AIChartType\n /** Group-by (category-axis) column field, or null. */\n dimension: string | null\n /** Split-by column field: one series per distinct value, or null. */\n series: string | null\n /** Measure (value-axis) column field, or null. */\n measure: string | null\n reduce: AIChartReduce\n stacked: boolean\n logScale: boolean\n timeAxis: boolean\n valueFormat: 'number' | 'currency' | 'percent'\n /** Calendar unit to group a date dimension by, or null for exact values. */\n bucket: 'day' | 'week' | 'month' | 'quarter' | 'year' | null\n /** Candlestick only: indicator panes and overlays to add. */\n indicators?: AIChartIndicator[]\n rationale: string\n /** With `apply`: what `validateChartSpec` flagged as an error on the spec\n * the panel built from the plan, empty when it drew cleanly. */\n diagnostics?: ChartDiagnostic[]\n}\n```\n\n### `type AIChartReduce`\n\nThe reducers a chart plan may name: the panel's full list.\n\n```ts\nexport type AIChartReduce =\n | 'sum' | 'avg' | 'count' | 'min' | 'max' | 'median' | 'p90' | 'first' | 'last' | 'countDistinct'\n```\n\n### `type AIChartOptions`\n\nOptions for `aiChart` - preview the plan, or render it into the grid.\n\n```ts\nexport type AIChartOptions = {\n /** Apply the plan to the grid's chart panel (open + configure). Default false. */\n apply?: boolean\n signal?: AbortSignal\n}\n```\n\n### `function aiChart`\n\nTranslate a natural-language request into a chart plan for the grid's built-in\n`charting` panel. Validates every field against the real schema, then (with\n`apply: true`) pushes it into the panel through `api.configureChart`.\n\n```ts\nexport async function aiChart<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n api: SvGridApi<TFeatures, TData>,\n query: string,\n opts: AIChartOptions = {},\n): Promise<AIChartPlan>\n```\n\n### `type AIChartExplanation`\n\nWhat `aiExplainChart` returns: the grounded summary and the model's insights.\n\n```ts\nexport type AIChartExplanation = {\n /** The plain-language reading of the chart (`chartSummary`), as the model saw it. */\n summary: string\n /** Two to three observations the model added: comparisons, outliers, what to look at next. */\n insights: string[]\n}\n```\n\n### `type AIExplainChartOptions`\n\nOptions for `aiExplainChart`.\n\n```ts\nexport type AIExplainChartOptions = {\n /** The spec to explain. Default: the grid panel's active chart. */\n spec?: ChartSpec\n signal?: AbortSignal\n}\n```\n\n### `function aiExplainChart`\n\nExplain a chart in plain words. The prompt is grounded on `chartSummary`\n(the same sentence a screen reader hears) plus a compact table of the\nfirst 50 categories, so the model comments on numbers it was given rather\nthan on an image. Returns the summary and up to three insights.\n\n```ts\nexport async function aiExplainChart<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(api: SvGridApi<TFeatures, TData>, opts: AIExplainChartOptions = {}): Promise<AIChartExplanation>\n```\n\n### `function enableAiCharting`\n\nWire the grid's chart-panel AI button to the model: registers a handler (via\n`api.setChartAiHandler`) that runs `aiChart` and returns the plan for the\npanel to apply + explain. Call once after `onApiReady`. `installEnterprise`\ncalls this for you.\n\n```ts\nexport function enableAiCharting<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(api: SvGridApi<TFeatures, TData>): void\n```\n\n### `function disableAiCharting`\n\nRemove the natural-language chart handler, hiding the AI button in the chart\npanel. The inverse of `enableAiCharting`; safe to call when none was set.\n\n```ts\nexport function disableAiCharting<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(api: SvGridApi<TFeatures, TData>): void\n```\n\n### `const mockAIProvider`\n\nA deterministic provider that returns canned, schema-shaped responses\nfor each task. Wire it in via `setAIProvider(mockAIProvider)` to make\nthe AI demo work end-to-end without a real model key. Not for production.\n\n```ts\nexport const mockAIProvider: AIProvider = async (req) => ...\n```\n"
7744
7815
  },
7745
7816
  {
7746
7817
  "slug": "reference/auto/svgrid-grid-builtin-editors",
7747
7818
  "path": "docs/reference/auto/svgrid-grid-builtin-editors.md",
7748
7819
  "title": "@svgrid/grid · builtin-editors.ts",
7749
7820
  "section": "API reference",
7750
- "markdown": "# `@svgrid/grid` · `builtin-editors.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\builtin-editors.ts`.\n\n### `function registerBuiltinEditors`\n\nRegister the config-free UI-kit editors (`otp`, `duration`, `richtext`) as\ngrid cell editors. Idempotent. Returns the list of type names it registered.\n\n```ts\nexport function registerBuiltinEditors(): string[] {\n registerCellEditor('otp', {\n component: SvOtpInput,\n autoOpen: false,\n props: (ctx) => ({\n value: (ctx.value ?? '') as string,\n autofocus: true,\n onChange: (v: string) => ctx.onChange(v),\n // The code is complete -> commit + stop editing.\n onComplete: (v: string) => ctx.onCommit(v),\n }),\n })\n registerCellEditor('duration', {\n component: SvDurationInput,\n props: (ctx) => ({\n value: (ctx.value ?? null) as number | null,\n autofocus: true,\n onChange: (v: number | null) => ctx.onChange(v),\n onCommit: (v: number | null) => ctx.onCommit(v),\n onCancel: () => ctx.onCancel(),\n }),\n })\n // Rich text carries a toolbar, so give the column a taller row (or edit it\n // from a detail panel) - it does not fit a default single-line row.\n //\n // Both the value handed to the editor and the value coming back are\n // sanitized. The stored string is the one SvRichCell later paints, so\n // cleaning it on the way in means a pasted payload never reaches row data.\n registerCellEditor('richtext', {\n component: SvRichText,\n props: (ctx) => ({\n value: sanitizeHtml((ctx.value ?? '') as string),\n autofocus: true,\n onChange: (html: string) => ctx.onChange(sanitizeHtml(html)),\n }),\n })\n return ['otp', 'duration', 'richtext']\n}\n```\n"
7821
+ "markdown": "# `@svgrid/grid` · `builtin-editors.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\builtin-editors.ts`.\n\n### `function registerBuiltinEditors`\n\nRegister the config-free UI-kit editors (`otp`, `duration`, `richtext`) as\ngrid cell editors. Idempotent. Returns the list of type names it registered.\n\n```ts\nexport function registerBuiltinEditors(): string[]\n```\n"
7751
7822
  },
7752
7823
  {
7753
7824
  "slug": "reference/auto/svgrid-grid-cell-formatting",
7754
7825
  "path": "docs/reference/auto/svgrid-grid-cell-formatting.md",
7755
7826
  "title": "@svgrid/grid · cell-formatting.ts",
7756
7827
  "section": "API reference",
7757
- "markdown": "# `@svgrid/grid` · `cell-formatting.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\cell-formatting.ts`.\n\n### `function resolveDatePattern`\n\nMap shortcut date patterns to Intl options (merged with caller `options`).\n\n```ts\nexport function resolveDatePattern(\n pattern: string | undefined,\n kind: 'date' | 'datetime',\n): Intl.DateTimeFormatOptions | undefined {\n if (!pattern) return undefined\n\n const p = pattern.trim()\n\n switch (p) {\n /** Short numeric local date (no weekday). */\n case 'd':\n return kind === 'datetime'\n ? {\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n }\n : { year: 'numeric', month: 'numeric', day: 'numeric' }\n /** Long spelled-out date (+ time if datetime). */\n case 'D':\n return kind === 'datetime'\n ? {\n weekday: 'long',\n year: 'numeric',\n month: 'long',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n }\n : { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }\n /** ISO-friendly yyyy-mm-dd (with time when datetime). */\n case 'y-m-d':\n return kind === 'datetime'\n ? {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n hour12: false,\n }\n : { year: 'numeric', month: '2-digit', day: '2-digit' }\n case 'medium':\n return { dateStyle: 'medium', timeStyle: kind === 'datetime' ? 'short' : undefined }\n case 'short':\n return { dateStyle: 'short', timeStyle: kind === 'datetime' ? 'short' : undefined }\n case 'long':\n return { dateStyle: 'long', timeStyle: kind === 'datetime' ? 'short' : undefined }\n default:\n return undefined\n }\n}\n```\n\n### `function getNumberFormatter`\n\nA cached `Intl.NumberFormat` for the locale and options given. Cached because\nconstructing one is among the most expensive calls in the platform, and both\ncallers do it per rendered value: once per cell while scrolling a number\ncolumn, and once per axis tick, data label and tooltip while drawing a chart.\n\n```ts\nexport function getNumberFormatter(\n locales: string | readonly string[] | undefined,\n options: Intl.NumberFormatOptions,\n): Intl.NumberFormat {\n // Stable key - for normal column configs the options object is reused\n // (declared in module scope), so this stringifies a small static shape.\n const key =\n (Array.isArray(locales) ? locales.join(',') : locales ?? '') +\n '|' +\n (options.style ?? '') +\n '|' +\n (options.currency ?? '') +\n '|' +\n (options.minimumFractionDigits ?? '') +\n '|' +\n (options.maximumFractionDigits ?? '') +\n '|' +\n (options.useGrouping ?? '') +\n '|' +\n (options.currencyDisplay ?? '') +\n '|' +\n (options.notation ?? '') +\n // Every option that changes the output belongs in the key. `signDisplay`\n // was missing, so a percent column asking for \"+3.27\" got the formatter\n // a currency column with the same digits had already cached, and no sign.\n '|' +\n (options.signDisplay ?? '') +\n '|' +\n (options.minimumIntegerDigits ?? '') +\n '|' +\n (options.compactDisplay ?? '') +\n '|' +\n (options.unit ?? '') +\n '|' +\n (options.unitDisplay ?? '') +\n '|' +\n (options.minimumSignificantDigits ?? '') +\n '|' +\n (options.maximumSignificantDigits ?? '')\n let fmt = numberFormatterCache.get(key)\n if (!fmt) {\n fmt = new Intl.NumberFormat(locales as string | string[] | undefined, options)\n numberFormatterCache.set(key, fmt)\n }\n return fmt\n}\n```\n\n### `function parseDateValue`\n\nA cell value as a Date, or null when it is not one. Accepts a Date, epoch ms,\nor a parseable string.\n\nA bare calendar date ('2026-06-27') is read as LOCAL midnight of that day.\n`new Date('2026-06-27')` reads it as UTC midnight, which every zone west of\nUTC formats as the 26th. The day in the string is the day the user meant.\n\n```ts\nexport function parseDateValue(value: unknown): Date | null {\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) return null\n const d = new Date(value)\n return Number.isNaN(d.getTime()) ? null : d\n }\n if (typeof value !== 'string') return null\n const s = value.trim()\n if (s === '') return null\n const ymd = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(s)\n if (ymd) {\n const [y, m, day] = [Number(ymd[1]), Number(ymd[2]) - 1, Number(ymd[3])]\n const d = new Date(0)\n d.setFullYear(y, m, day)\n d.setHours(0, 0, 0, 0)\n // Reject a rollover ('2026-02-30' is not March 2nd), as `new Date` does.\n return d.getMonth() === m && d.getDate() === day ? d : null\n }\n const d = new Date(s)\n return Number.isNaN(d.getTime()) ? null : d\n}\n```\n\n### `function getDateFormatter`\n\nA cached `Intl.DateTimeFormat` for the locale and options given. Cached because\n constructing one per cell is the dominant cost when formatting a date column.\n\n```ts\nexport function getDateFormatter(\n locales: string | readonly string[] | undefined,\n options: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormat {\n const key =\n (Array.isArray(locales) ? locales.join(',') : locales ?? '') +\n '|' +\n (options.dateStyle ?? '') +\n '|' +\n (options.timeStyle ?? '') +\n '|' +\n (options.year ?? '') +\n '|' +\n (options.month ?? '') +\n '|' +\n (options.day ?? '') +\n '|' +\n (options.hour ?? '') +\n '|' +\n (options.minute ?? '') +\n '|' +\n (options.second ?? '') +\n '|' +\n (options.weekday ?? '') +\n '|' +\n (options.hour12 ?? '')\n let fmt = dateFormatterCache.get(key)\n if (!fmt) {\n fmt = new Intl.DateTimeFormat(locales as string | string[] | undefined, options)\n dateFormatterCache.set(key, fmt)\n }\n return fmt\n}\n```\n\n### `function formatNumericWithConfig`\n\nFormat a numeric value for number / currency / percent column formats.\n\n```ts\nexport function formatNumericWithConfig(value: unknown, config: NumericFormatInput): string {\n // An empty cell stays empty. Number(null) and Number('') are 0, so a cleared\n // value in a currency column used to render as \"$0\", a number nobody entered.\n if (value == null || (typeof value === 'string' && value.trim() === '')) return ''\n const n = typeof value === 'number' ? value : Number(value)\n if (!Number.isFinite(n)) return String(value ?? '')\n\n const locales = config.locales\n\n if (config.type === 'currency') {\n return getNumberFormatter(locales, {\n style: 'currency',\n currency: config.currency ?? 'USD',\n ...config.options,\n }).format(n)\n }\n\n if (config.type === 'percent') {\n const frac = config.valueIsPercentPoints === true ? n / 100 : n\n return getNumberFormatter(locales, {\n style: 'percent',\n minimumFractionDigits: 0,\n maximumFractionDigits: 2,\n ...config.options,\n }).format(frac)\n }\n\n return getNumberFormatter(locales, config.options ?? {}).format(n)\n}\n```\n"
7828
+ "markdown": "# `@svgrid/grid` · `cell-formatting.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\cell-formatting.ts`.\n\n### `function resolveDatePattern`\n\nMap shortcut date patterns to Intl options (merged with caller `options`).\n\n```ts\nexport function resolveDatePattern(\n pattern: string | undefined,\n kind: 'date' | 'datetime',\n): Intl.DateTimeFormatOptions | undefined\n```\n\n### `function getNumberFormatter`\n\nA cached `Intl.NumberFormat` for the locale and options given. Cached because\nconstructing one is among the most expensive calls in the platform, and both\ncallers do it per rendered value: once per cell while scrolling a number\ncolumn, and once per axis tick, data label and tooltip while drawing a chart.\n\n```ts\nexport function getNumberFormatter(\n locales: string | readonly string[] | undefined,\n options: Intl.NumberFormatOptions,\n): Intl.NumberFormat\n```\n\n### `function parseDateValue`\n\nA cell value as a Date, or null when it is not one. Accepts a Date, epoch ms,\nor a parseable string.\n\nA bare calendar date ('2026-06-27') is read as LOCAL midnight of that day.\n`new Date('2026-06-27')` reads it as UTC midnight, which every zone west of\nUTC formats as the 26th. The day in the string is the day the user meant.\n\n```ts\nexport function parseDateValue(value: unknown): Date | null\n```\n\n### `function getDateFormatter`\n\nA cached `Intl.DateTimeFormat` for the locale and options given. Cached because\n constructing one per cell is the dominant cost when formatting a date column.\n\n```ts\nexport function getDateFormatter(\n locales: string | readonly string[] | undefined,\n options: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormat\n```\n\n### `function formatNumericWithConfig`\n\nFormat a numeric value for number / currency / percent column formats.\n\n```ts\nexport function formatNumericWithConfig(value: unknown, config: NumericFormatInput): string\n```\n"
7758
7829
  },
7759
7830
  {
7760
7831
  "slug": "reference/auto/svgrid-grid-chart-axes",
7761
7832
  "path": "docs/reference/auto/svgrid-grid-chart-axes.md",
7762
7833
  "title": "@svgrid/grid · chart-axes.ts",
7763
7834
  "section": "API reference",
7764
- "markdown": "# `@svgrid/grid` · `chart-axes.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-axes.ts`.\n\n### `function chartScales`\n\nTurn a laid-out chart's axes into functions, so a caller can draw its own\nmarks in the same coordinates the built-in ones use.\n\nThis is the custom-series seam. Rather than a registry of mark types, the\nchart hands over its geometry and its scales and lets the caller render\nwhatever SVG it likes into the plot - which is the Svelte-shaped answer, and\nmeans a custom mark is ordinary markup rather than a plugin.\n\nDeriving the scale from `geo.axes` matters: the domain a chart drew against\nis the NICE-ROUNDED one, stretched to include zero for bar charts and any\nreference lines. Recomputing it from the data outside would land custom marks\na few pixels off the built-in ones, in a way that looks like a rendering bug.\n\nReturns `null` for a chart with no cartesian axes (pie, gauge, treemap,\nsankey, calendar, radar, funnel), where plot coordinates mean nothing.\n\n```ts\nexport function chartScales(geo: ChartGeometry): ChartScales | null {\n const a = geo.axes\n if (!a) return null\n const { x: px, y: py, w: pw, h: ph } = geo.plot\n type Dom = { min: number; max: number; log: boolean; reversed?: boolean }\n const yFor = (dom: Dom) => (value: number) => {\n let t = project(value, dom.min, dom.max, dom.log)\n if (t === null) return Number.NaN\n if (dom.reversed) t = 1 - t\n return py + ph - t * ph\n }\n const left = yFor(a.y)\n const right = a.y2 ? yFor(a.y2) : left\n const invFor = (dom: Dom) => (y: number) => {\n let t = ph === 0 ? 0 : (py + ph - y) / ph\n if (dom.reversed) t = 1 - t\n if (!dom.log) return dom.min + t * (dom.max - dom.min)\n const lo = Math.log10(dom.min)\n return 10 ** (lo + t * (Math.log10(dom.max) - lo))\n }\n // A continuous x axis (time / number) places by value; a category axis by\n // index. `xOf(i)` on a continuous axis goes through the stored per-category\n // values, so a custom mark at \"category 3\" lands where the built-in one did\n // even when the categories are unevenly spaced in time.\n const cx = a.x\n const span = cx ? cx.max - cx.min || 1 : 1\n const logSpan = cx?.log ? Math.log10(cx.max) - Math.log10(cx.min) || 1 : 1\n const xOfNum = (v: number) => {\n if (!cx || !Number.isFinite(v)) return Number.NaN\n if (cx.log && v <= 0) return Number.NaN\n let t = cx.log ? (Math.log10(v) - Math.log10(cx.min)) / logSpan : (v - cx.min) / span\n if (cx.reversed) t = 1 - t\n return px + t * pw\n }\n const xOfIndex = (i: number) => {\n if (cx?.values) {\n const v = cx.values[Math.round(i)]\n if (v != null && Number.isFinite(v)) return xOfNum(v)\n }\n const t = px + a.slot * i + a.slot / 2\n return a.xReversed ? px + pw - (t - px) : t\n }\n const xOfValue = (value: number | string | Date): number => {\n if (cx) {\n if (value instanceof Date) return xOfNum(value.getTime())\n if (typeof value === 'number') return xOfNum(value)\n const n = cx.type === 'time' ? Date.parse(value) : Number(value)\n if (Number.isFinite(n)) return xOfNum(n)\n // A label that did not parse can still be one of the categories.\n const i = geo.xTicks.findIndex((t) => t.label === value)\n return i >= 0 ? geo.xTicks[i]!.x : Number.NaN\n }\n if (typeof value === 'number') return xOfIndex(value)\n const label = value instanceof Date ? value.toISOString() : value\n const i = a.labels ? a.labels.indexOf(label) : -1\n return i >= 0 ? xOfIndex(i) : Number.NaN\n }\n const xInvertValue = (x: number): number => {\n let t = pw === 0 ? 0 : (x - px) / pw\n if (cx ? cx.reversed : a.xReversed) t = 1 - t\n if (cx?.log) return Math.pow(10, Math.log10(cx.min) + t * logSpan)\n if (cx) return cx.min + t * span\n return Math.max(0, Math.min(a.count - 1, t * a.count - 0.5))\n }\n return {\n xOf: xOfIndex,\n yOf: (value, axis) => (axis === 'right' ? right(value) : left(value)),\n xInvert: (x) => {\n if (cx?.values) {\n // Nearest category by value, which is what a hover on a time axis means.\n const v = xInvertValue(x)\n let best = 0\n let bestD = Infinity\n cx.values.forEach((cv, i) => {\n const d = Math.abs(cv - v)\n if (d < bestD) { bestD = d; best = i }\n })\n return best\n }\n const raw = Math.floor((x - px) / (a.slot || 1))\n const i = a.xReversed ? a.count - 1 - raw : raw\n return Math.max(0, Math.min(a.count - 1, i))\n },\n yInvert: (y, axis) => (axis === 'right' && a.y2 ? invFor(a.y2)(y) : invFor(a.y)(y)),\n xOfValue,\n xInvertValue,\n }\n}\n```\n"
7835
+ "markdown": "# `@svgrid/grid` · `chart-axes.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-axes.ts`.\n\n### `function chartScales`\n\nTurn a laid-out chart's axes into functions, so a caller can draw its own\nmarks in the same coordinates the built-in ones use.\n\nThis is the custom-series seam. Rather than a registry of mark types, the\nchart hands over its geometry and its scales and lets the caller render\nwhatever SVG it likes into the plot - which is the Svelte-shaped answer, and\nmeans a custom mark is ordinary markup rather than a plugin.\n\nDeriving the scale from `geo.axes` matters: the domain a chart drew against\nis the NICE-ROUNDED one, stretched to include zero for bar charts and any\nreference lines. Recomputing it from the data outside would land custom marks\na few pixels off the built-in ones, in a way that looks like a rendering bug.\n\nReturns `null` for a chart with no cartesian axes (pie, gauge, treemap,\nsankey, calendar, radar, funnel), where plot coordinates mean nothing.\n\n```ts\nexport function chartScales(geo: ChartGeometry): ChartScales | null\n```\n"
7765
7836
  },
7766
7837
  {
7767
7838
  "slug": "reference/auto/svgrid-grid-chart-cartesian",
7768
7839
  "path": "docs/reference/auto/svgrid-grid-chart-cartesian.md",
7769
7840
  "title": "@svgrid/grid · chart-cartesian.ts",
7770
7841
  "section": "API reference",
7771
- "markdown": "# `@svgrid/grid` · `chart-cartesian.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-cartesian.ts`.\n\n### `function buildLinePath`\n\nBuild an SVG path from a list of (x,y) pairs, optionally smoothed via\nmonotone cubic interpolation (preserves local extrema - no overshoots).\nBreaks the path at `defined === false` gaps unless `connectNulls` is set,\nand draws steps instead of straight segments when `step` is set.\n\n```ts\nexport function buildLinePath(\n pts: Array<{ x: number; y: number; defined: boolean }>,\n smooth: boolean,\n opts: { connectNulls?: boolean; step?: Step } = {},\n): string {\n const runs = definedRuns(pts, !!opts.connectNulls)\n return runs.map((run) => runPath(run, smooth, opts.step)).filter(Boolean).join(' ')\n}\n```\n\n### `function streamBaseline`\n\nThe baseline a stacked area sits on per category. `'zero'` is the axis;\n`'silhouette'` centres the total on zero; `'wiggle'` picks the baseline\nthat minimises the weighted change of slope across the layers (Byron and\nWattenberg's stream graph), which is what makes a stream read as flowing\nrather than as a stack. Gaps count as 0 so the stack stays continuous.\n\n```ts\nexport function streamBaseline(layers: ReadonlyArray<ReadonlyArray<number>>, offset: 'zero' | 'wiggle' | 'silhouette'): number[] {\n const n = layers.length\n const m = layers[0]?.length ?? 0\n const base = new Array<number>(m).fill(0)\n if (!n || !m || offset === 'zero') return base\n const v = (i: number, j: number) => {\n const x = layers[i]![j]\n return Number.isFinite(x) ? (x as number) : 0\n }\n if (offset === 'silhouette') {\n for (let j = 0; j < m; j += 1) {\n let total = 0\n for (let i = 0; i < n; i += 1) total += v(i, j)\n base[j] = -total / 2\n }\n return base\n }\n let y = 0\n for (let j = 1; j < m; j += 1) {\n let s1 = 0\n let s2 = 0\n for (let i = 0; i < n; i += 1) {\n const sij0 = v(i, j)\n const sij1 = v(i, j - 1)\n let s3 = (sij0 - sij1) / 2\n for (let k = 0; k < i; k += 1) s3 += v(k, j) - v(k, j - 1)\n s1 += sij0\n s2 += s3 * sij0\n }\n base[j - 1] = y\n if (s1) y -= s2 / s1\n }\n base[m - 1] = y\n return base\n}\n```\n\n### `function markerPath`\n\nThe SVG path for a point marker of `shape` centred on (cx, cy) with\nhalf-size `size`. `'circle'` and `'none'` return `''`: circles draw as\n`<circle>` (which keeps every existing selector working), and `'none'` draws\nnothing. Exposed so a legend swatch or a custom mark can match the series.\n\n```ts\nexport function markerPath(shape: ChartMarkerShape, cx: number, cy: number, size: number): string {\n const s = Math.max(0.5, size)\n switch (shape) {\n case 'square':\n return `M${round(cx - s)},${round(cy - s)} h${round(2 * s)} v${round(2 * s)} h${round(-2 * s)} Z`\n case 'diamond':\n return `M${round(cx)},${round(cy - s * 1.3)} L${round(cx + s * 1.3)},${round(cy)} L${round(cx)},${round(cy + s * 1.3)} L${round(cx - s * 1.3)},${round(cy)} Z`\n case 'triangle':\n return `M${round(cx)},${round(cy - s * 1.2)} L${round(cx + s * 1.2)},${round(cy + s)} L${round(cx - s * 1.2)},${round(cy + s)} Z`\n case 'cross':\n return `M${round(cx - s)},${round(cy - s)} L${round(cx + s)},${round(cy + s)} M${round(cx - s)},${round(cy + s)} L${round(cx + s)},${round(cy - s)}`\n default:\n return ''\n }\n}\n```\n\n### `type ChartDataLabel`\n\nOne positioned data label. `onBar` means it sits on a mark and should be\n painted in the contrast colour.\n\n```ts\nexport type ChartDataLabel = {\n x: number\n y: number\n text: string\n anchor: 'start' | 'middle' | 'end'\n onBar: boolean\n series: string\n /** Rotation in degrees about (x, y), from `dataLabels.rotation`. */\n angle?: number\n /** A leader from the mark to a label that was pushed away from it. */\n leader?: { x1: number; y1: number; x2: number; y2: number }\n}\n```\n\n### `function layoutDataLabels`\n\nPlace the data labels for a laid-out cartesian chart: one per bar and one\nper defined line point, positioned by `placement`, formatted by `formatter`\n(or `fmt`), and thinned so no label overlaps an earlier one when\n`hideOverlap` is on (the default).\n\nPure, so the renderer derives it and a test can assert on it. Pie slices\nlabel themselves (a percentage at the centroid) and are not handled here.\n\n```ts\nexport function layoutDataLabels(\n geo: ChartGeometry,\n cfg: ChartDataLabelConfig,\n fmt: (v: number, series?: string) => string,\n opts: { stacked?: boolean; dense?: boolean; share?: boolean } = {},\n): ChartDataLabel[] {\n if (cfg.show === false) return []\n const out: ChartDataLabel[] = []\n // On a 100% chart the axis reads shares whatever `valueFormat` says, and a\n // label on the bar reads the same: \"18%\", not the \"$18\" (or, with a percent\n // format, the \"1800%\") the raw value gave. A formatter still gets the raw\n // value; the tooltip keeps it too.\n const totals = opts.share ? new Map<string, number>() : null\n if (totals) {\n for (const b of geo.bars) {\n const key = b.index === undefined ? b.label : String(b.index)\n totals.set(key, (totals.get(key) ?? 0) + Math.abs(b.value))\n }\n }\n const shareOf = (b: ChartBar) => {\n const total = totals!.get(b.index === undefined ? b.label : String(b.index)) || 0\n return total ? `${Math.round((Math.abs(b.value) / total) * 100)}%` : ''\n }\n const text = (v: number, category: string, series: string, bar?: ChartBar) =>\n cfg.formatter ? cfg.formatter(v, { category, series }) : totals && bar ? shareOf(bar) : fmt(v, series)\n const horizontal = geo.orientation === 'horizontal'\n const placement = cfg.placement ?? (opts.stacked ? 'inside' : horizontal ? 'outside' : 'top')\n const inside = placement === 'inside' || placement === 'center'\n for (const b of geo.bars) {\n const t = text(b.value, b.label, b.series, b)\n if (!t) continue\n if (horizontal) {\n if (inside) {\n if (b.w <= 18 || b.h < 8) continue\n out.push({ x: b.x + b.w / 2, y: b.y + b.h / 2 + 3, text: t, anchor: 'middle', onBar: true, series: b.series })\n } else {\n if (b.h < 8) continue\n const pos = b.value >= 0\n out.push({ x: pos ? b.x + b.w + 3 : b.x - 3, y: b.y + b.h / 2 + 3, text: t, anchor: pos ? 'start' : 'end', onBar: false, series: b.series })\n }\n } else if (inside) {\n if (b.h <= 13 || b.w < 14) continue\n out.push({ x: b.x + b.w / 2, y: b.y + b.h / 2 + 3, text: t, anchor: 'middle', onBar: true, series: b.series })\n } else {\n if (b.w < 6) continue\n const pos = b.value >= 0\n out.push({ x: b.x + b.w / 2, y: pos ? b.y - 3 : b.y + b.h + 11, text: t, anchor: 'middle', onBar: false, series: b.series })\n }\n }\n if (!opts.dense) {\n for (const line of geo.lines) {\n for (const p of line.points) {\n if (!p.defined) continue\n const t = text(p.value, p.label, line.label)\n if (!t) continue\n out.push({ x: p.x, y: inside ? p.y + 3 : p.y - 7, text: t, anchor: 'middle', onBar: false, series: line.label })\n }\n }\n }\n const angle = cfg.rotation ?? 0\n if (angle) for (const l of out) l.angle = angle\n if (cfg.hideOverlap === false && !cfg.connector) return out\n // Greedy thinning in draw order: a label is kept only when its estimated\n // box (10px type, ~5.6px a glyph) misses every box already kept. A rotated\n // label past 45 degrees stands more than it lies, so its box is turned.\n // With `connector`, a label that collides is pushed away from its mark in\n // 12px steps (up, or right on a horizontal chart) and keeps a leader back\n // to where it started; after four steps it gives up and is dropped.\n const kept: Array<{ x0: number; y0: number; x1: number; y1: number }> = []\n const steep = Math.abs(angle) >= 45\n const boxOf = (l: ChartDataLabel) => {\n const len = l.text.length * 5.6 + 2\n const w = steep ? 10 : len\n const h = steep ? len : 11\n const x0 = l.anchor === 'middle' ? l.x - w / 2 : l.anchor === 'end' ? l.x - w : l.x\n const y0 = steep ? l.y - h : l.y - 10\n return { x0, y0, x1: x0 + w, y1: y0 + h }\n }\n const hits = (b: { x0: number; y0: number; x1: number; y1: number }) =>\n kept.some((k) => b.x0 < k.x1 && b.x1 > k.x0 && b.y0 < k.y1 && b.y1 > k.y0)\n const STEP = 12\n const MAX_STEPS = 4\n const pushed: ChartDataLabel[] = []\n for (const l of out) {\n let box = boxOf(l)\n if (!hits(box)) { kept.push(box); pushed.push(l); continue }\n if (!cfg.connector || l.onBar) continue\n const from = { x: l.x, y: l.y }\n let moved: ChartDataLabel | null = null\n for (let step = 1; step <= MAX_STEPS; step += 1) {\n const cand: ChartDataLabel = horizontal\n ? { ...l, x: l.x + STEP * step }\n : { ...l, y: l.y - STEP * step }\n box = boxOf(cand)\n if (!hits(box)) { moved = cand; break }\n }\n if (!moved) continue\n // The leader runs from the mark's edge (where the label started) to the\n // near edge of the moved label.\n moved.leader = horizontal\n ? { x1: from.x, y1: from.y - 3, x2: moved.x - 2, y2: moved.y - 3 }\n : { x1: from.x, y1: from.y + 1, x2: moved.x, y2: moved.y + 2 }\n kept.push(box)\n pushed.push(moved)\n }\n return pushed\n}\n```\n"
7842
+ "markdown": "# `@svgrid/grid` · `chart-cartesian.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-cartesian.ts`.\n\n### `function buildLinePath`\n\nBuild an SVG path from a list of (x,y) pairs, optionally smoothed via\nmonotone cubic interpolation (preserves local extrema - no overshoots).\nBreaks the path at `defined === false` gaps unless `connectNulls` is set,\nand draws steps instead of straight segments when `step` is set.\n\n```ts\nexport function buildLinePath(\n pts: Array<{ x: number; y: number; defined: boolean }>,\n smooth: boolean,\n opts: { connectNulls?: boolean; step?: Step } = {},\n): string\n```\n\n### `function streamBaseline`\n\nThe baseline a stacked area sits on per category. `'zero'` is the axis;\n`'silhouette'` centres the total on zero; `'wiggle'` picks the baseline\nthat minimises the weighted change of slope across the layers (Byron and\nWattenberg's stream graph), which is what makes a stream read as flowing\nrather than as a stack. Gaps count as 0 so the stack stays continuous.\n\n```ts\nexport function streamBaseline(layers: ReadonlyArray<ReadonlyArray<number>>, offset: 'zero' | 'wiggle' | 'silhouette'): number[]\n```\n\n### `function markerPath`\n\nThe SVG path for a point marker of `shape` centred on (cx, cy) with\nhalf-size `size`. `'circle'` and `'none'` return `''`: circles draw as\n`<circle>` (which keeps every existing selector working), and `'none'` draws\nnothing. Exposed so a legend swatch or a custom mark can match the series.\n\n```ts\nexport function markerPath(shape: ChartMarkerShape, cx: number, cy: number, size: number): string\n```\n\n### `type ChartDataLabel`\n\nOne positioned data label. `onBar` means it sits on a mark and should be\n painted in the contrast colour.\n\n```ts\nexport type ChartDataLabel = {\n x: number\n y: number\n text: string\n anchor: 'start' | 'middle' | 'end'\n onBar: boolean\n series: string\n /** Rotation in degrees about (x, y), from `dataLabels.rotation`. */\n angle?: number\n /** A leader from the mark to a label that was pushed away from it. */\n leader?: { x1: number; y1: number; x2: number; y2: number }\n}\n```\n\n### `function layoutDataLabels`\n\nPlace the data labels for a laid-out cartesian chart: one per bar and one\nper defined line point, positioned by `placement`, formatted by `formatter`\n(or `fmt`), and thinned so no label overlaps an earlier one when\n`hideOverlap` is on (the default).\n\nPure, so the renderer derives it and a test can assert on it. Pie slices\nlabel themselves (a percentage at the centroid) and are not handled here.\n\n```ts\nexport function layoutDataLabels(\n geo: ChartGeometry,\n cfg: ChartDataLabelConfig,\n fmt: (v: number, series?: string) => string,\n opts: { stacked?: boolean; dense?: boolean; share?: boolean } = {},\n): ChartDataLabel[]\n```\n"
7772
7843
  },
7773
7844
  {
7774
7845
  "slug": "reference/auto/svgrid-grid-chart-decimate",
7775
7846
  "path": "docs/reference/auto/svgrid-grid-chart-decimate.md",
7776
7847
  "title": "@svgrid/grid · chart-decimate.ts",
7777
7848
  "section": "API reference",
7778
- "markdown": "# `@svgrid/grid` · `chart-decimate.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-decimate.ts`.\n\n### `const PER_CATEGORY_SERIES_KEYS`\n\nEvery array on a {@link ChartSeries} indexed by category. Anything that\nnarrows a spec to a subset of categories (the zoom window, decimation) picks\neach of these with the same indices; a key missing here is a mark drawn\nagainst the wrong category, which is why the list is one constant rather\nthan a convention. `values` is included for completeness.\n\n```ts\nexport const PER_CATEGORY_SERIES_KEYS = [\n 'values',\n 'rowIds',\n 'upperValues',\n 'lowerValues',\n 'ohlc',\n 'boxes',\n 'errors',\n 'markers',\n 'colors',\n 'lowValues',\n 'targets',\n 'volumes',\n] as const satisfies ReadonlyArray<keyof ChartSeries>\n```\n\n### `const PER_CATEGORY_SPEC_KEYS`\n\nSpec-level arrays indexed by category (see {@link PER_CATEGORY_SERIES_KEYS}).\n\n```ts\nexport const PER_CATEGORY_SPEC_KEYS = ['waterfallTotals'] as const satisfies ReadonlyArray<keyof ChartSpec>\n```\n\n### `function pickCategories`\n\nNarrow a spec to the categories at `indices` (ascending), keeping every\ncategory-parallel array in step. The zoom window and decimation both go\nthrough here, so there is exactly one list of arrays to keep in step.\n\n```ts\nexport function pickCategories(spec: ChartSpec, indices: ReadonlyArray<number>): ChartSpec {\n const pick = <T,>(arr: T[] | undefined): T[] | undefined => {\n if (!arr) return undefined\n const out: T[] = new Array(indices.length)\n for (let k = 0; k < indices.length; k += 1) out[k] = arr[indices[k]!]!\n return out\n }\n const series = spec.series.map((s) => {\n const next: ChartSeries = { ...s, values: pick(s.values) ?? [] }\n for (const key of PER_CATEGORY_SERIES_KEYS) {\n if (key === 'values') continue\n const arr = s[key] as unknown[] | undefined\n if (arr) (next as unknown as Record<string, unknown>)[key] = pick(arr)\n }\n return next\n })\n const out: ChartSpec = { ...spec, categories: pick(spec.categories) ?? [], series }\n for (const key of PER_CATEGORY_SPEC_KEYS) {\n const arr = spec[key] as unknown[] | undefined\n if (arr) (out as unknown as Record<string, unknown>)[key] = pick(arr)\n }\n return out\n}\n```\n\n### `function lttb`\n\nLargest-Triangle-Three-Buckets: the indices of the `target` points that best\npreserve the visual shape of `values` plotted against their index. The\nfirst and last points are always kept. Non-finite values are skipped as\ncandidates, so a gap cannot be \"chosen\" as a representative point.\n\n```ts\nexport function lttb(values: ReadonlyArray<number>, target: number, xs?: ReadonlyArray<number>): number[] {\n const n = values.length\n // The x of point j: its index unless the caller positions points by value\n // (a numeric or log axis), where the triangles must use the real spacing.\n const xAt = (j: number) => (xs && Number.isFinite(xs[j]) ? xs[j]! : j)\n if (target >= n || n <= 2) return values.map((_, i) => i)\n if (target < 3) return [0, n - 1]\n const out: number[] = [0]\n const every = (n - 2) / (target - 2)\n let a = 0\n for (let i = 0; i < target - 2; i += 1) {\n // The next bucket's centroid is the far corner of every candidate triangle.\n const nextStart = Math.floor((i + 1) * every) + 1\n const nextEnd = Math.min(Math.floor((i + 2) * every) + 1, n)\n let avgX = 0\n let avgY = 0\n let cnt = 0\n for (let j = nextStart; j < nextEnd; j += 1) {\n const v = values[j]!\n if (!Number.isFinite(v)) continue\n avgX += xAt(j)\n avgY += v\n cnt += 1\n }\n if (cnt) { avgX /= cnt; avgY /= cnt } else { avgX = (xAt(nextStart) + xAt(Math.min(nextEnd, n - 1))) / 2; avgY = values[a]! }\n const start = Math.floor(i * every) + 1\n const end = Math.min(Math.floor((i + 1) * every) + 1, n)\n const ax = xAt(a)\n const ay = Number.isFinite(values[a]!) ? values[a]! : 0\n let best = -1\n let bestArea = -1\n for (let j = start; j < end; j += 1) {\n const v = values[j]!\n if (!Number.isFinite(v)) continue\n const area = Math.abs((ax - avgX) * (v - ay) - (ax - xAt(j)) * (avgY - ay))\n if (area > bestArea) { bestArea = area; best = j }\n }\n if (best < 0) best = start\n out.push(best)\n a = best\n }\n out.push(n - 1)\n return out\n}\n```\n\n### `function minMaxIndices`\n\nThe indices of the minimum and maximum in each of `buckets` equal slices of\n`values`, plus the first and last point. Keeps every spike, which is what\nmonitoring data wants and what LTTB will sometimes smooth over.\n\n```ts\nexport function minMaxIndices(values: ReadonlyArray<number>, buckets: number): number[] {\n const n = values.length\n if (buckets >= n || n <= 2) return values.map((_, i) => i)\n const keep = new Set<number>([0, n - 1])\n const size = n / Math.max(1, buckets)\n for (let b = 0; b < buckets; b += 1) {\n const start = Math.floor(b * size)\n const end = Math.min(n, Math.floor((b + 1) * size))\n let lo = -1\n let hi = -1\n for (let j = start; j < end; j += 1) {\n const v = values[j]!\n if (!Number.isFinite(v)) continue\n if (lo < 0 || v < values[lo]!) lo = j\n if (hi < 0 || v > values[hi]!) hi = j\n }\n if (lo >= 0) keep.add(lo)\n if (hi >= 0) keep.add(hi)\n }\n return [...keep].sort((x, y) => x - y)\n}\n```\n\n### `function decimateSpec`\n\nThin a spec's line / area series to about one point per pixel of plot\nwidth. Nothing happens below the threshold, for a spec that says\n`decimate: false`, or when any series draws bars, candles or boxes (those\nmarks ARE the data; thinning them would hide categories). Every series is\ndecimated separately and the union of the kept indices is used, so a spike\nthat only one series has still survives.\n\n```ts\nexport function decimateSpec(spec: ChartSpec, plotW: number, cfg: ChartDecimateConfig | undefined = spec.decimate): ChartSpec {\n const opt = resolveDecimate(cfg, plotW)\n if (!opt) return spec\n const n = spec.categories.length\n if (n <= opt.threshold || !spec.series.length) return spec\n const lineLike = (t: string | undefined) => t === 'line' || t === 'area'\n if (!lineLike(spec.type) && !spec.series.every((s) => lineLike(s.type))) return spec\n if (spec.series.some((s) => (s.type && !lineLike(s.type)) || s.ohlc || s.boxes)) return spec\n // On a numeric axis the points sit where their values are, so the\n // triangles are measured in those positions (log10 of them on a log axis).\n const numeric = (spec.xAxis?.type ?? spec.xType) === 'number'\n const isLog = numeric && spec.xAxis?.scale === 'log'\n const xs = numeric\n ? spec.categories.map((c) => { const v = Number(c); return isLog ? (v > 0 ? Math.log10(v) : Number.NaN) : v })\n : undefined\n const keep = new Set<number>()\n for (const s of spec.series) {\n const idx = opt.method === 'minmax' ? minMaxIndices(s.values, Math.floor(opt.target / 2)) : lttb(s.values, opt.target, xs)\n for (const i of idx) keep.add(i)\n }\n const indices = [...keep].sort((a, b) => a - b)\n if (indices.length >= n) return spec\n return pickCategories(spec, indices)\n}\n```\n"
7849
+ "markdown": "# `@svgrid/grid` · `chart-decimate.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-decimate.ts`.\n\n### `const PER_CATEGORY_SERIES_KEYS`\n\nEvery array on a {@link ChartSeries} indexed by category. Anything that\nnarrows a spec to a subset of categories (the zoom window, decimation) picks\neach of these with the same indices; a key missing here is a mark drawn\nagainst the wrong category, which is why the list is one constant rather\nthan a convention. `values` is included for completeness.\n\n```ts\nexport const PER_CATEGORY_SERIES_KEYS = [\n 'values',\n 'rowIds',\n 'upperValues',\n 'lowerValues',\n 'ohlc',\n 'boxes',\n 'errors',\n 'markers',\n 'colors',\n 'lowValues',\n 'targets',\n 'volumes',\n] as const satisfies ReadonlyArray<keyof ChartSeries>\n```\n\n### `const PER_CATEGORY_SPEC_KEYS`\n\nSpec-level arrays indexed by category (see {@link PER_CATEGORY_SERIES_KEYS}).\n\n```ts\nexport const PER_CATEGORY_SPEC_KEYS = ['waterfallTotals'] as const satisfies ReadonlyArray<keyof ChartSpec>\n```\n\n### `function pickCategories`\n\nNarrow a spec to the categories at `indices` (ascending), keeping every\ncategory-parallel array in step. The zoom window and decimation both go\nthrough here, so there is exactly one list of arrays to keep in step.\n\n```ts\nexport function pickCategories(spec: ChartSpec, indices: ReadonlyArray<number>): ChartSpec\n```\n\n### `function lttb`\n\nLargest-Triangle-Three-Buckets: the indices of the `target` points that best\npreserve the visual shape of `values` plotted against their index. The\nfirst and last points are always kept. Non-finite values are skipped as\ncandidates, so a gap cannot be \"chosen\" as a representative point.\n\n```ts\nexport function lttb(values: ReadonlyArray<number>, target: number, xs?: ReadonlyArray<number>): number[]\n```\n\n### `function minMaxIndices`\n\nThe indices of the minimum and maximum in each of `buckets` equal slices of\n`values`, plus the first and last point. Keeps every spike, which is what\nmonitoring data wants and what LTTB will sometimes smooth over.\n\n```ts\nexport function minMaxIndices(values: ReadonlyArray<number>, buckets: number): number[]\n```\n\n### `function decimateSpec`\n\nThin a spec's line / area series to about one point per pixel of plot\nwidth. Nothing happens below the threshold, for a spec that says\n`decimate: false`, or when any series draws bars, candles or boxes (those\nmarks ARE the data; thinning them would hide categories). Every series is\ndecimated separately and the union of the kept indices is used, so a spike\nthat only one series has still survives.\n\n```ts\nexport function decimateSpec(spec: ChartSpec, plotW: number, cfg: ChartDecimateConfig | undefined = spec.decimate): ChartSpec\n```\n"
7779
7850
  },
7780
7851
  {
7781
7852
  "slug": "reference/auto/svgrid-grid-chart-export-pdf",
7782
7853
  "path": "docs/reference/auto/svgrid-grid-chart-export-pdf.md",
7783
7854
  "title": "@svgrid/grid · chart-export-pdf.ts",
7784
7855
  "section": "API reference",
7785
- "markdown": "# `@svgrid/grid` · `chart-export-pdf.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-export-pdf.ts`.\n\n### `type ChartPdfOptions`\n\nOptions for the PDF: page, orientation, the text around the chart.\n\n```ts\nexport type ChartPdfOptions = ChartExportOptions & {\n /** Paper size. Default A4. */\n page?: 'A4' | 'Letter'\n /** Default: whichever fits the chart's aspect ratio better. */\n orientation?: 'portrait' | 'landscape'\n title?: string\n subtitle?: string\n caption?: string\n /** JPEG quality, 0..1. Default 0.92. */\n quality?: number\n}\n```\n\n### `function buildChartPdf`\n\nAssemble a one-page PDF from a JPEG and the text around it. Exported for\ntests and for callers that already have a JPEG; `chartToPdfBlob` is the\none that starts from a chart element.\n\n```ts\nexport function buildChartPdf(\n jpeg: { bytes: Uint8Array; width: number; height: number },\n opts: Pick<ChartPdfOptions, 'page' | 'orientation' | 'title' | 'subtitle' | 'caption'> = {},\n): Uint8Array {\n const [pw0, ph0] = PAGES[opts.page ?? 'A4']\n const landscape = opts.orientation ? opts.orientation === 'landscape' : jpeg.width / jpeg.height > pw0 / ph0\n const pw = landscape ? ph0 : pw0\n const ph = landscape ? pw0 : ph0\n const margin = 40\n const title = (opts.title ?? '').trim()\n const subtitle = (opts.subtitle ?? '').trim()\n const caption = (opts.caption ?? '').trim()\n\n // Text block at the top, image below it, caption at the foot.\n let y = ph - margin\n const content: string[] = []\n const line = (text: string, size: number, gray: number) => {\n y -= size + 4\n content.push(`BT /F1 ${size} Tf ${gray} g ${margin} ${y.toFixed(2)} Td ${pdfText(text)} Tj ET`)\n }\n if (title) line(title, 16, 0)\n if (subtitle) line(subtitle, 11, 0.4)\n if (title || subtitle) y -= 8\n const footer = caption ? 20 : 0\n const availW = pw - margin * 2\n const availH = y - margin - footer\n const scale = Math.min(availW / jpeg.width, availH / jpeg.height)\n const iw = jpeg.width * scale\n const ih = jpeg.height * scale\n const ix = margin + (availW - iw) / 2\n const iy = y - ih\n content.push(`q ${iw.toFixed(2)} 0 0 ${ih.toFixed(2)} ${ix.toFixed(2)} ${iy.toFixed(2)} cm /Im1 Do Q`)\n if (caption) {\n const size = 9\n const text = textWidth(caption, size) > availW ? caption.slice(0, Math.floor(availW / (size * 0.5)) - 3) + '...' : caption\n content.push(`BT /F1 ${size} Tf 0.4 g ${margin} ${(margin - 4).toFixed(2)} Td ${pdfText(text)} Tj ET`)\n }\n const stream = content.join('\\n')\n\n const objects: Array<Uint8Array | string> = []\n const offsets: number[] = []\n let length = 0\n const push = (part: Uint8Array | string) => {\n objects.push(part)\n length += typeof part === 'string' ? part.length : part.length\n }\n push('%PDF-1.4\\n%âãÏÓ\\n')\n const obj = (n: number, body: string, bin?: Uint8Array) => {\n offsets[n] = length\n push(`${n} 0 obj\\n${body}\\n`)\n if (bin) {\n push('stream\\n')\n push(bin)\n push('\\nendstream\\n')\n }\n push('endobj\\n')\n }\n obj(1, '<< /Type /Catalog /Pages 2 0 R >>')\n obj(2, '<< /Type /Pages /Kids [3 0 R] /Count 1 >>')\n obj(3, `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${pw.toFixed(2)} ${ph.toFixed(2)}] /Resources << /XObject << /Im1 4 0 R >> /Font << /F1 5 0 R >> >> /Contents 6 0 R >>`)\n obj(4, `<< /Type /XObject /Subtype /Image /Width ${jpeg.width} /Height ${jpeg.height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${jpeg.bytes.length} >>`, jpeg.bytes)\n obj(5, '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>')\n obj(6, `<< /Length ${stream.length} >>`, latin1(stream))\n const xref = length\n push(`xref\\n0 7\\n0000000000 65535 f \\n`)\n for (let n = 1; n <= 6; n += 1) push(`${String(offsets[n]).padStart(10, '0')} 00000 n \\n`)\n push(`trailer\\n<< /Size 7 /Root 1 0 R >>\\nstartxref\\n${xref}\\n%%EOF\\n`)\n\n const out = new Uint8Array(new ArrayBuffer(length))\n let at = 0\n for (const part of objects) {\n const bytes = typeof part === 'string' ? latin1(part) : part\n out.set(bytes, at)\n at += bytes.length\n }\n return out\n}\n```\n\n### `function printChart`\n\nPrint the chart: a new window with the standalone SVG (and the title\nabove it), sized to the page, that opens the print dialog once it has\ndrawn. Returns false when the window was blocked.\n\n```ts\nexport function printChart(source: SVGSVGElement | HTMLElement, options: ChartExportOptions & { title?: string } = {}): boolean {\n const svg = chartToSvgString(source, options)\n const win = window.open('', '_blank', 'width=900,height=700')\n if (!win) return false\n const esc = (s: string) => s.replace(/[&<>]/g, (m) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[m]!)\n win.document.write(\n `<!doctype html><html><head><meta charset=\"utf-8\"><title>${esc(options.title ?? 'Chart')}</title>` +\n `<style>body{margin:24px;font-family:system-ui,sans-serif}h1{font-size:16px;margin:0 0 12px}svg{max-width:100%;height:auto}@page{margin:12mm}</style></head><body>` +\n (options.title ? `<h1>${esc(options.title)}</h1>` : '') +\n svg +\n `</body></html>`,\n )\n win.document.close()\n const go = () => { win.focus(); win.print() }\n if (win.document.readyState === 'complete') setTimeout(go, 50)\n else win.addEventListener('load', () => setTimeout(go, 50))\n return true\n}\n```\n"
7856
+ "markdown": "# `@svgrid/grid` · `chart-export-pdf.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-export-pdf.ts`.\n\n### `type ChartPdfOptions`\n\nOptions for the PDF: page, orientation, the text around the chart.\n\n```ts\nexport type ChartPdfOptions = ChartExportOptions & {\n /** Paper size. Default A4. */\n page?: 'A4' | 'Letter'\n /** Default: whichever fits the chart's aspect ratio better. */\n orientation?: 'portrait' | 'landscape'\n title?: string\n subtitle?: string\n caption?: string\n /** JPEG quality, 0..1. Default 0.92. */\n quality?: number\n}\n```\n\n### `function buildChartPdf`\n\nAssemble a one-page PDF from a JPEG and the text around it. Exported for\ntests and for callers that already have a JPEG; `chartToPdfBlob` is the\none that starts from a chart element.\n\n```ts\nexport function buildChartPdf(\n jpeg: { bytes: Uint8Array; width: number; height: number },\n opts: Pick<ChartPdfOptions, 'page' | 'orientation' | 'title' | 'subtitle' | 'caption'> = {},\n): Uint8Array\n```\n\n### `function chartToPdfBlob`\n\nThe chart as a one-page PDF `Blob`.\n\n```ts\nexport async function chartToPdfBlob(source: SVGSVGElement | HTMLElement, options: ChartPdfOptions = {}): Promise<Blob>\n```\n\n### `function downloadChartPdf`\n\nDownload the chart as a `.pdf` file.\n\n```ts\nexport async function downloadChartPdf(source: SVGSVGElement | HTMLElement, filename = 'chart.pdf', options: ChartPdfOptions = {}): Promise<void>\n```\n\n### `function printChart`\n\nPrint the chart: a new window with the standalone SVG (and the title\nabove it), sized to the page, that opens the print dialog once it has\ndrawn. Returns false when the window was blocked.\n\n```ts\nexport function printChart(source: SVGSVGElement | HTMLElement, options: ChartExportOptions & { title?: string } = {}): boolean\n```\n"
7786
7857
  },
7787
7858
  {
7788
7859
  "slug": "reference/auto/svgrid-grid-chart-export",
7789
7860
  "path": "docs/reference/auto/svgrid-grid-chart-export.md",
7790
7861
  "title": "@svgrid/grid · chart-export.ts",
7791
7862
  "section": "API reference",
7792
- "markdown": "# `@svgrid/grid` · `chart-export.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-export.ts`.\n\n### `type ChartExportOptions`\n\nOptions for exporting a chart: the filename, and the background to paint behind it.\n\n```ts\nexport type ChartExportOptions = {\n /** Background color of the exported image. Default: the grid background. */\n background?: string\n /** PNG pixel scale (1 = viewBox size). Default 2 (retina). */\n scale?: number\n}\n```\n\n### `function chartToSvgString`\n\nSerialize the chart SVG to a standalone, self-styled SVG string.\n\n```ts\nexport function chartToSvgString(\n source: SVGSVGElement | HTMLElement,\n options: ChartExportOptions = {},\n): string {\n const svg = resolveSvg(source)\n if (!svg) throw new Error('chartToSvgString: no <svg> found')\n\n const fg = cssVar(svg, '--sg-fg', '#0f172a')\n const muted = cssVar(svg, '--sg-muted', '#64748b')\n const border = cssVar(svg, '--sg-border', '#e2e8f0')\n const bg = options.background ?? cssVar(svg, '--sg-bg', '#ffffff')\n\n const vb = svg.viewBox.baseVal\n const w = vb && vb.width ? vb.width : svg.clientWidth || 520\n const h = vb && vb.height ? vb.height : svg.clientHeight || 300\n\n const clone = svg.cloneNode(true) as SVGSVGElement\n clone.setAttribute('width', String(w))\n clone.setAttribute('height', String(h))\n clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')\n\n // Inline computed paint/text styles so the export is what's on screen -\n // dynamic SVG presentation attributes (a line's `stroke={color}`) and scoped\n // component CSS don't survive a raw clone + XMLSerializer. Walk the live tree\n // and its clone (1:1 here, before we prune hit layers) and copy the resolved\n // style, so line paths etc. export with their real stroke instead of nothing.\n const PAINT_PROPS = [\n 'fill', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-opacity',\n 'stroke-dasharray', 'stroke-linecap', 'stroke-linejoin', 'opacity',\n 'font-size', 'font-family', 'font-weight', 'text-anchor',\n ]\n const liveNodes = svg.querySelectorAll('*')\n const cloneNodes = clone.querySelectorAll('*')\n for (let i = 0; i < liveNodes.length; i += 1) {\n const el = cloneNodes[i] as (SVGElement & { style: CSSStyleDeclaration }) | undefined\n if (!el || !el.style) continue\n const cs = getComputedStyle(liveNodes[i]!)\n for (const prop of PAINT_PROPS) {\n const v = cs.getPropertyValue(prop)\n if (v && v !== 'normal') el.style.setProperty(prop, v)\n }\n }\n\n // Drop interaction-only hit layers.\n clone.querySelectorAll('.sv-grid-chart-hit').forEach((n) => n.remove())\n\n const style = document.createElementNS('http://www.w3.org/2000/svg', 'style')\n style.textContent = `\n .sv-grid-chart-axis { fill: ${muted}; font-size: 10px; font-family: sans-serif; }\n .sv-grid-chart-gridline { stroke: ${border}; stroke-width: 1; opacity: 0.6; }\n .sv-grid-chart-gridline.is-zero { stroke: ${muted}; opacity: 0.9; }\n .sv-grid-chart-datalabel { fill: ${fg}; font-size: 9.5px; font-weight: 600; font-family: sans-serif; }\n .sv-grid-chart-datalabel.on-bar { fill: #fff; }\n .sv-grid-chart-donut-total { fill: ${fg}; font-size: 16px; font-weight: 800; font-family: sans-serif; }\n .sv-grid-chart-donut-label { fill: ${muted}; font-size: 10px; font-family: sans-serif; }\n `\n clone.insertBefore(style, clone.firstChild)\n\n const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')\n rect.setAttribute('x', '0')\n rect.setAttribute('y', '0')\n rect.setAttribute('width', String(w))\n rect.setAttribute('height', String(h))\n rect.setAttribute('fill', bg)\n clone.insertBefore(rect, style.nextSibling)\n\n return new XMLSerializer().serializeToString(clone)\n}\n```\n\n### `function downloadChartSvg`\n\nDownload the chart as an `.svg` file.\n\n```ts\nexport function downloadChartSvg(\n source: SVGSVGElement | HTMLElement,\n filename = 'chart.svg',\n options: ChartExportOptions = {},\n): void {\n const svg = chartToSvgString(source, options)\n const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }))\n triggerDownload(url, filename)\n setTimeout(() => URL.revokeObjectURL(url), 1000)\n}\n```\n\n### `function chartToPngBlob`\n\nRasterize the chart to a PNG `Blob`.\n\n```ts\nexport function chartToPngBlob(\n source: SVGSVGElement | HTMLElement,\n options: ChartExportOptions = {},\n): Promise<Blob> {\n const svgStr = chartToSvgString(source, options)\n const scale = options.scale ?? 2\n const svgEl = resolveSvg(source)!\n const vb = svgEl.viewBox.baseVal\n const w = (vb && vb.width ? vb.width : svgEl.clientWidth || 520) * scale\n const h = (vb && vb.height ? vb.height : svgEl.clientHeight || 300) * scale\n\n return new Promise((resolve, reject) => {\n const url = URL.createObjectURL(new Blob([svgStr], { type: 'image/svg+xml' }))\n const img = new Image()\n img.onload = () => {\n const canvas = document.createElement('canvas')\n canvas.width = Math.round(w)\n canvas.height = Math.round(h)\n const ctx = canvas.getContext('2d')\n if (!ctx) {\n URL.revokeObjectURL(url)\n reject(new Error('canvas 2d context unavailable'))\n return\n }\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height)\n URL.revokeObjectURL(url)\n canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('toBlob failed'))), 'image/png')\n }\n img.onerror = () => {\n URL.revokeObjectURL(url)\n reject(new Error('failed to rasterize chart SVG'))\n }\n img.src = url\n })\n}\n```\n\n### `function chartSpecToCsv`\n\nSerialize a chart's data to CSV: one row per category, one column per series\n(`Category, <series 1>, ...`).\n\nA series that carries more than one number per category widens instead of\nlosing them. `ohlc` becomes four columns, `boxes` five plus its outliers,\n`errors` two, `lowValues` a low / high pair, `targets` a value / target\npair. This used to write `values` and nothing else, which quietly\nmade \"Export CSV\" on a candlestick chart hand back the closing prices only -\nthe screen-reader table was given the four real numbers on purpose and the\nexport, which is what people actually take away, was not.\n\nScatter has no categories, so it gets its own long-format table of points\nrather than exporting nothing at all.\n\nStill empty for the specs with no rectangular data to write: sankey, treemap,\ngauge and calendar.\n\n```ts\nexport function chartSpecToCsv(spec: ChartSpec): string {\n const series = spec.series ?? []\n // Scatter: one row per point. `categories` is empty for these, so the\n // category path below would return '' and the export button would do nothing.\n if (series.some((s) => s.points?.length)) {\n const header = ['Series', 'X', 'Y', 'Size', 'Label'].map(csvCell).join(',')\n const rows: string[] = []\n for (const s of series) {\n for (const p of s.points ?? []) {\n rows.push([s.label, p.x, p.y, p.r ?? '', p.label ?? ''].map(csvCell).join(','))\n }\n }\n return rows.length ? [header, ...rows].join('\\n') : ''\n }\n\n const cats = spec.categories ?? []\n if (!cats.length || !series.length) return ''\n\n // One header cell per column a series contributes. A plain series keeps its\n // bare label, so an existing export is byte-identical.\n const header: string[] = ['Category']\n for (const s of series) {\n if (s.ohlc) header.push(`${s.label} Open`, `${s.label} High`, `${s.label} Low`, `${s.label} Close`, ...(s.volumes ? [`${s.label} Volume`] : []))\n else if (s.boxes) header.push(`${s.label} Min`, `${s.label} Q1`, `${s.label} Median`, `${s.label} Q3`, `${s.label} Max`, `${s.label} Outliers`)\n else if (s.errors) header.push(s.label, `${s.label} Low`, `${s.label} High`)\n else if (s.lowValues) header.push(`${s.label} low`, `${s.label} high`)\n else if (s.targets) header.push(s.label, `${s.label} target`)\n else header.push(s.label)\n }\n\n const rows = cats.map((cat, i) => {\n const cells: unknown[] = [cat]\n for (const s of series) {\n if (s.ohlc) {\n const k = s.ohlc[i]\n cells.push(k?.o ?? '', k?.h ?? '', k?.l ?? '', k?.c ?? '')\n if (s.volumes) cells.push(s.volumes[i] ?? '')\n } else if (s.boxes) {\n const b = s.boxes[i]\n // Outliers are a list inside one cell; csvCell quotes it.\n cells.push(b?.min ?? '', b?.q1 ?? '', b?.median ?? '', b?.q3 ?? '', b?.max ?? '', b?.outliers?.join(' ') ?? '')\n } else if (s.errors) {\n const v = s.values[i]\n const e = s.errors[i]\n const lo = e == null ? '' : typeof e === 'number' ? (v ?? 0) - Math.abs(e) : Math.min(e.lo, e.hi)\n const hi = e == null ? '' : typeof e === 'number' ? (v ?? 0) + Math.abs(e) : Math.max(e.lo, e.hi)\n cells.push(v ?? '', lo, hi)\n } else if (s.lowValues) {\n cells.push(s.lowValues[i] ?? '', s.values[i] ?? '')\n } else if (s.targets) {\n cells.push(s.values[i] ?? '', s.targets[i] ?? '')\n } else {\n cells.push(s.values[i] ?? '')\n }\n }\n return cells.map(csvCell).join(',')\n })\n return [header.map(csvCell).join(','), ...rows].join('\\n')\n}\n```\n\n### `function chartCsvExportable`\n\nWhether {@link chartSpecToCsv} would produce anything, without building it.\n\nThe chart panel disables its CSV menu item on this. It has to be a predicate\nrather than `chartSpecToCsv(spec) !== ''` because that runs on every render,\nand serialising a 100,000-point series to decide whether to grey out a button\nis not a thing to do sixty times a second.\n\n```ts\nexport function chartCsvExportable(spec: ChartSpec): boolean {\n const series = spec.series ?? []\n if (series.some((s) => s.points?.length)) return true\n return !!(spec.categories?.length && series.length)\n}\n```\n\n### `function downloadChartCsv`\n\nDownload the chart's data as a `.csv` file. Returns false if there's no\n rectangular category/series data to export.\n\n```ts\nexport function downloadChartCsv(spec: ChartSpec, filename = 'chart.csv'): boolean {\n const csv = chartSpecToCsv(spec)\n if (!csv) return false\n const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }))\n triggerDownload(url, filename)\n setTimeout(() => URL.revokeObjectURL(url), 1000)\n return true\n}\n```\n"
7863
+ "markdown": "# `@svgrid/grid` · `chart-export.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-export.ts`.\n\n### `type ChartExportOptions`\n\nOptions for exporting a chart: the filename, and the background to paint behind it.\n\n```ts\nexport type ChartExportOptions = {\n /** Background color of the exported image. Default: the grid background. */\n background?: string\n /** PNG pixel scale (1 = viewBox size). Default 2 (retina). */\n scale?: number\n}\n```\n\n### `function chartToSvgString`\n\nSerialize the chart SVG to a standalone, self-styled SVG string.\n\n```ts\nexport function chartToSvgString(\n source: SVGSVGElement | HTMLElement,\n options: ChartExportOptions = {},\n): string\n```\n\n### `function downloadChartSvg`\n\nDownload the chart as an `.svg` file.\n\n```ts\nexport function downloadChartSvg(\n source: SVGSVGElement | HTMLElement,\n filename = 'chart.svg',\n options: ChartExportOptions = {},\n): void\n```\n\n### `function chartToPngBlob`\n\nRasterize the chart to a PNG `Blob`.\n\n```ts\nexport function chartToPngBlob(\n source: SVGSVGElement | HTMLElement,\n options: ChartExportOptions = {},\n): Promise<Blob>\n```\n\n### `function downloadChartPng`\n\nDownload the chart as a `.png` file.\n\n```ts\nexport async function downloadChartPng(\n source: SVGSVGElement | HTMLElement,\n filename = 'chart.png',\n options: ChartExportOptions = {},\n): Promise<void>\n```\n\n### `function chartSpecToCsv`\n\nSerialize a chart's data to CSV: one row per category, one column per series\n(`Category, <series 1>, ...`).\n\nA series that carries more than one number per category widens instead of\nlosing them. `ohlc` becomes four columns, `boxes` five plus its outliers,\n`errors` two, `lowValues` a low / high pair, `targets` a value / target\npair. This used to write `values` and nothing else, which quietly\nmade \"Export CSV\" on a candlestick chart hand back the closing prices only -\nthe screen-reader table was given the four real numbers on purpose and the\nexport, which is what people actually take away, was not.\n\nScatter has no categories, so it gets its own long-format table of points\nrather than exporting nothing at all.\n\nStill empty for the specs with no rectangular data to write: sankey, treemap,\ngauge and calendar.\n\n```ts\nexport function chartSpecToCsv(spec: ChartSpec): string\n```\n\n### `function chartCsvExportable`\n\nWhether {@link chartSpecToCsv} would produce anything, without building it.\n\nThe chart panel disables its CSV menu item on this. It has to be a predicate\nrather than `chartSpecToCsv(spec) !== ''` because that runs on every render,\nand serialising a 100,000-point series to decide whether to grey out a button\nis not a thing to do sixty times a second.\n\n```ts\nexport function chartCsvExportable(spec: ChartSpec): boolean\n```\n\n### `function downloadChartCsv`\n\nDownload the chart's data as a `.csv` file. Returns false if there's no\n rectangular category/series data to export.\n\n```ts\nexport function downloadChartCsv(spec: ChartSpec, filename = 'chart.csv'): boolean\n```\n"
7793
7864
  },
7794
7865
  {
7795
7866
  "slug": "reference/auto/svgrid-grid-chart-financial",
7796
7867
  "path": "docs/reference/auto/svgrid-grid-chart-financial.md",
7797
7868
  "title": "@svgrid/grid · chart-financial.ts",
7798
7869
  "section": "API reference",
7799
- "markdown": "# `@svgrid/grid` · `chart-financial.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-financial.ts`.\n\n### `function heikinAshi`\n\nHeikin-Ashi (\"average bar\") candles from ordinary OHLC bars. Each close is\nthe mean of the four prices, each open the midpoint of the previous\nHeikin-Ashi body, and the high / low stretch to include both. Runs of one\ncolour then read as trends, at the cost of the true open and close.\n`null` bars (gaps) stay null and reset the chain.\n\n```ts\nexport function heikinAshi(bars: ReadonlyArray<OhlcBar | null>): Array<OhlcBar | null> {\n const out: Array<OhlcBar | null> = new Array(bars.length)\n let prev: OhlcBar | null = null\n for (let i = 0; i < bars.length; i += 1) {\n const b = bars[i]\n if (!b || ![b.o, b.h, b.l, b.c].every(Number.isFinite)) {\n out[i] = null\n prev = null\n continue\n }\n const c = (b.o + b.h + b.l + b.c) / 4\n const o = prev ? (prev.o + prev.c) / 2 : (b.o + b.c) / 2\n const ha: OhlcBar = { o, c, h: Math.max(b.h, o, c), l: Math.min(b.l, o, c) }\n out[i] = ha\n prev = ha\n }\n return out\n}\n```\n\n### `function resampleOhlc`\n\nRoll daily (or finer) bars up to a coarser calendar bucket: the first\nopen, the highest high, the lowest low, the last close, the summed volume.\nCategories are ISO dates and come back as the bucket starts (`bucketStart`),\nsorted; bars whose date does not parse are dropped. Pass `volumes` to get\nthem summed alongside.\n\n```ts\nexport function resampleOhlc(\n categories: ReadonlyArray<string>,\n ohlc: ReadonlyArray<OhlcBar | null>,\n opts: { bucket: ChartTimeBucket; volumes?: ReadonlyArray<number> },\n): { categories: string[]; ohlc: Array<OhlcBar | null>; volumes?: number[] } {\n const groups = new Map<string, { bar: OhlcBar | null; vol: number; first: number; last: number }>()\n const order: Array<[string, number]> = []\n for (let i = 0; i < categories.length; i += 1) {\n const t = Date.parse(categories[i]!)\n if (!Number.isFinite(t)) continue\n const key = bucketStart(t, opts.bucket)\n if (!key) continue\n let g = groups.get(key)\n if (!g) {\n g = { bar: null, vol: 0, first: Infinity, last: -Infinity }\n groups.set(key, g)\n order.push([key, Date.parse(key)])\n }\n const b = ohlc[i]\n if (b) {\n // Rows may arrive out of order: the open is the EARLIEST bar's and the\n // close the LATEST bar's, by date, not by position.\n if (!g.bar) g.bar = { ...b }\n else {\n g.bar.h = Math.max(g.bar.h, b.h)\n g.bar.l = Math.min(g.bar.l, b.l)\n if (t >= g.last) g.bar.c = b.c\n if (t <= g.first) g.bar.o = b.o\n }\n if (t > g.last) g.last = t\n if (t < g.first) g.first = t\n }\n const v = opts.volumes?.[i]\n if (Number.isFinite(v)) g.vol += v!\n }\n order.sort((a, b) => a[1] - b[1])\n const out = {\n categories: order.map(([k]) => k),\n ohlc: order.map(([k]) => groups.get(k)!.bar),\n ...(opts.volumes ? { volumes: order.map(([k]) => groups.get(k)!.vol) } : {}),\n }\n return out\n}\n```\n\n### `type OhlcColumns`\n\nWhat the grid's chart panel stores for a price chart: the column ids.\n\n```ts\nexport type OhlcColumns = { open: string | null; high: string | null; low: string | null; close: string | null; volume: string | null }\n```\n\n### `function guessOhlcColumns`\n\nGuess the price columns from their names: the first numeric column called\nopen / high / low / close (or last, price) / volume. What the chart panel\nshows before the reader picks anything; a picked column always wins.\n\n```ts\nexport function guessOhlcColumns(\n measures: ReadonlyArray<{ id: string; field: string; label: string }>,\n picked?: Partial<OhlcColumns> | null,\n): OhlcColumns {\n const guess = (re: RegExp) => measures.find((m) => re.test(m.field) || re.test(m.label))?.id ?? null\n return {\n open: picked?.open ?? guess(/open/i),\n high: picked?.high ?? guess(/high/i),\n low: picked?.low ?? guess(/low/i),\n close: picked?.close ?? guess(/close|last|price/i),\n volume: picked?.volume ?? guess(/vol/i),\n }\n}\n```\n\n### `function ohlcDirectOptions`\n\nThe `rowsToDirectSpec` options for the grid panel's price chart, or null\nwhile a price column is still unpicked. `fieldOf` maps a column id to its\nfield name; the date column is the category.\n\n```ts\nexport function ohlcDirectOptions(\n fieldOf: (id: string | null) => string | null | undefined,\n dateId: string | null,\n cols: OhlcColumns,\n extra: { bucket?: ChartTimeBucket | null; candleStyle?: ChartSpec['candleStyle'] | null },\n): { category: string; ohlc: NonNullable<Parameters<typeof import('./chart').rowsToDirectSpec>[2]['ohlc']> } | null {\n const date = fieldOf(dateId)\n const open = fieldOf(cols.open)\n const high = fieldOf(cols.high)\n const low = fieldOf(cols.low)\n const close = fieldOf(cols.close)\n if (!date || !open || !high || !low || !close) return null\n const volume = fieldOf(cols.volume)\n return {\n category: date,\n ohlc: {\n open, high, low, close,\n ...(volume ? { volume } : {}),\n ...(extra.bucket ? { bucket: extra.bucket } : {}),\n ...(extra.candleStyle ? { candleStyle: extra.candleStyle } : {}),\n lastPriceLine: true,\n },\n }\n}\n```\n\n### `type ChartPanelIndicator`\n\nThe indicator names the grid's chart panel offers.\n\n```ts\nexport type ChartPanelIndicator = 'volume' | 'rsi' | 'macd' | 'stochastic' | 'atr' | 'obv' | 'sma' | 'ema' | 'bb' | 'vwap'\n```\n\n### `function splitPanelIndicators`\n\nSplit the panel's indicator list into the panes that go under the price\n(in order) and the one overlay that rides on it (a series carries a single\n`overlay`, so the first overlay kind wins).\n\n```ts\nexport function splitPanelIndicators(kinds: ReadonlyArray<ChartPanelIndicator>): { panes: ChartIndicatorSpec[]; overlay: SeriesOverlay | null } {\n const OVERLAY: Partial<Record<ChartPanelIndicator, SeriesOverlay>> = { sma: 'sma:20', ema: 'ema:20', bb: 'bb:20:2', vwap: 'vwap' }\n const panes: ChartIndicatorSpec[] = []\n let overlay: SeriesOverlay | null = null\n for (const k of kinds) {\n const o = OVERLAY[k]\n if (o) { overlay ??= o; continue }\n if (k === 'volume' || k === 'rsi' || k === 'macd' || k === 'stochastic' || k === 'atr' || k === 'obv') panes.push({ kind: k })\n }\n return { panes, overlay }\n}\n```\n\n### `function rowsToOhlcSpec`\n\nA candlestick spec straight from rows: one bar per date (sorted), with the\nvolume alongside when a field is named, optionally rolled up to a calendar\nbucket first. The x axis is ordinal-time, so weekends and holidays leave no\ngaps.\n\n```ts\nexport function rowsToOhlcSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n date: keyof T & string\n open: keyof T & string\n high: keyof T & string\n low: keyof T & string\n close: keyof T & string\n volume?: keyof T & string\n bucket?: ChartTimeBucket\n /** The series label. Default \"Price\". */\n label?: string\n type?: 'candlestick' | 'ohlc'\n candleStyle?: ChartSpec['candleStyle']\n lastPriceLine?: boolean\n },\n): ChartSpec {\n const num = (v: unknown): number => (typeof v === 'number' ? v : Number(v))\n const sorted = rows\n .map((r) => ({ r, t: Date.parse(String(r[opts.date])) }))\n .filter((x) => Number.isFinite(x.t))\n .sort((a, b) => a.t - b.t)\n let categories = sorted.map((x) => new Date(x.t).toISOString().slice(0, 10))\n let ohlc: Array<OhlcBar | null> = sorted.map(({ r }) => {\n const b = { o: num(r[opts.open]), h: num(r[opts.high]), l: num(r[opts.low]), c: num(r[opts.close]) }\n return [b.o, b.h, b.l, b.c].every(Number.isFinite) ? b : null\n })\n let volumes = opts.volume ? sorted.map(({ r }) => num(r[opts.volume!])) : undefined\n if (opts.bucket) {\n const rolled = resampleOhlc(categories, ohlc, { bucket: opts.bucket, volumes })\n categories = rolled.categories\n ohlc = rolled.ohlc\n volumes = rolled.volumes\n }\n const label = opts.label ?? 'Price'\n const series: ChartSeries = { label, values: ohlc.map((b) => (b ? b.c : Number.NaN)), ohlc, ...(volumes ? { volumes } : {}) }\n return {\n type: opts.type ?? 'candlestick',\n categories,\n series: [series],\n xType: 'ordinal-time',\n ...(opts.candleStyle ? { candleStyle: opts.candleStyle } : {}),\n ...(opts.lastPriceLine ? { lastPriceLine: true } : {}),\n }\n}\n```\n"
7870
+ "markdown": "# `@svgrid/grid` · `chart-financial.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-financial.ts`.\n\n### `function heikinAshi`\n\nHeikin-Ashi (\"average bar\") candles from ordinary OHLC bars. Each close is\nthe mean of the four prices, each open the midpoint of the previous\nHeikin-Ashi body, and the high / low stretch to include both. Runs of one\ncolour then read as trends, at the cost of the true open and close.\n`null` bars (gaps) stay null and reset the chain.\n\n```ts\nexport function heikinAshi(bars: ReadonlyArray<OhlcBar | null>): Array<OhlcBar | null>\n```\n\n### `function resampleOhlc`\n\nRoll daily (or finer) bars up to a coarser calendar bucket: the first\nopen, the highest high, the lowest low, the last close, the summed volume.\nCategories are ISO dates and come back as the bucket starts (`bucketStart`),\nsorted; bars whose date does not parse are dropped. Pass `volumes` to get\nthem summed alongside.\n\n```ts\nexport function resampleOhlc(\n categories: ReadonlyArray<string>,\n ohlc: ReadonlyArray<OhlcBar | null>,\n opts: { bucket: ChartTimeBucket; volumes?: ReadonlyArray<number> },\n): { categories: string[]; ohlc: Array<OhlcBar | null>; volumes?: number[] }\n```\n\n### `type OhlcColumns`\n\nWhat the grid's chart panel stores for a price chart: the column ids.\n\n```ts\nexport type OhlcColumns = { open: string | null; high: string | null; low: string | null; close: string | null; volume: string | null }\n```\n\n### `function guessOhlcColumns`\n\nGuess the price columns from their names: the first numeric column called\nopen / high / low / close (or last, price) / volume. What the chart panel\nshows before the reader picks anything; a picked column always wins.\n\n```ts\nexport function guessOhlcColumns(\n measures: ReadonlyArray<{ id: string; field: string; label: string }>,\n picked?: Partial<OhlcColumns> | null,\n): OhlcColumns\n```\n\n### `function ohlcDirectOptions`\n\nThe `rowsToDirectSpec` options for the grid panel's price chart, or null\nwhile a price column is still unpicked. `fieldOf` maps a column id to its\nfield name; the date column is the category.\n\n```ts\nexport function ohlcDirectOptions(\n fieldOf: (id: string | null) => string | null | undefined,\n dateId: string | null,\n cols: OhlcColumns,\n extra: { bucket?: ChartTimeBucket | null; candleStyle?: ChartSpec['candleStyle'] | null },\n): { category: string; ohlc: NonNullable<Parameters<typeof import('./chart').rowsToDirectSpec>[2]['ohlc']> } | null\n```\n\n### `type ChartPanelIndicator`\n\nThe indicator names the grid's chart panel offers.\n\n```ts\nexport type ChartPanelIndicator = 'volume' | 'rsi' | 'macd' | 'stochastic' | 'atr' | 'obv' | 'sma' | 'ema' | 'bb' | 'vwap'\n```\n\n### `function splitPanelIndicators`\n\nSplit the panel's indicator list into the panes that go under the price\n(in order) and the one overlay that rides on it (a series carries a single\n`overlay`, so the first overlay kind wins).\n\n```ts\nexport function splitPanelIndicators(kinds: ReadonlyArray<ChartPanelIndicator>): { panes: ChartIndicatorSpec[]; overlay: SeriesOverlay | null }\n```\n\n### `function rowsToOhlcSpec`\n\nA candlestick spec straight from rows: one bar per date (sorted), with the\nvolume alongside when a field is named, optionally rolled up to a calendar\nbucket first. The x axis is ordinal-time, so weekends and holidays leave no\ngaps.\n\n```ts\nexport function rowsToOhlcSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n date: keyof T & string\n open: keyof T & string\n high: keyof T & string\n low: keyof T & string\n close: keyof T & string\n volume?: keyof T & string\n bucket?: ChartTimeBucket\n /** The series label. Default \"Price\". */\n label?: string\n type?: 'candlestick' | 'ohlc'\n candleStyle?: ChartSpec['candleStyle']\n lastPriceLine?: boolean\n },\n): ChartSpec\n```\n"
7800
7871
  },
7801
7872
  {
7802
7873
  "slug": "reference/auto/svgrid-grid-chart-format",
7803
7874
  "path": "docs/reference/auto/svgrid-grid-chart-format.md",
7804
7875
  "title": "@svgrid/grid · chart-format.ts",
7805
7876
  "section": "API reference",
7806
- "markdown": "# `@svgrid/grid` · `chart-format.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-format.ts`.\n\n### `function formatChartValue`\n\nFormat a numeric value for display, honouring an optional `valueFormat`.\n\nTwo modes, on purpose. With no `locale` and no `currency` this is the original\nlocale-free output: the compact `1.2k` / `1.2M` base, currency prefixed with\n`$` (sign outside), percent multiplied by 100 and suffixed `%`. Set either one\nand it switches to `Intl.NumberFormat`, so separators, the decimal mark and the\ncompact suffixes all follow the locale.\n\nKeeping the old path as the default is deliberate rather than lazy. `Intl`'s\ncompact notation is not the same string even for `en-US` (`1.2K`, capital),\nso formatting everything through it would silently restyle every axis in every\nexisting chart. Opting in is the only version of this that is not a surprise.\n\n```ts\nexport function formatChartValue(\n n: number,\n format?: ChartValueFormat,\n opts?: ChartFormatLocale,\n): string {\n if (!Number.isFinite(n)) return ''\n const localized = opts && (opts.locale || opts.currency)\n if (localized) {\n // Compact notation because these are axis ticks and data labels, where a\n // full-precision number is what makes an axis unreadable.\n const style = format === 'currency' ? 'currency' : format === 'percent' ? 'percent' : 'decimal'\n const o: Intl.NumberFormatOptions = { notation: 'compact', maximumFractionDigits: 1 }\n if (style === 'currency') {\n o.style = 'currency'\n // `style: 'currency'` throws without a code, so fall back to the symbol\n // this used to hard-code rather than refusing to draw the chart.\n o.currency = opts!.currency || 'USD'\n } else if (style === 'percent') {\n o.style = 'percent'\n }\n return getNumberFormatter(opts!.locale, o).format(n)\n }\n if (format === 'currency') return `${n < 0 ? '-' : ''}$${fmtTick(Math.abs(n))}`\n if (format === 'percent') {\n const p = n * 100\n return `${Math.round(p * 10) / 10}%`\n }\n return fmtTick(n)\n}\n```\n"
7877
+ "markdown": "# `@svgrid/grid` · `chart-format.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-format.ts`.\n\n### `function formatChartValue`\n\nFormat a numeric value for display, honouring an optional `valueFormat`.\n\nTwo modes, on purpose. With no `locale` and no `currency` this is the original\nlocale-free output: the compact `1.2k` / `1.2M` base, currency prefixed with\n`$` (sign outside), percent multiplied by 100 and suffixed `%`. Set either one\nand it switches to `Intl.NumberFormat`, so separators, the decimal mark and the\ncompact suffixes all follow the locale.\n\nKeeping the old path as the default is deliberate rather than lazy. `Intl`'s\ncompact notation is not the same string even for `en-US` (`1.2K`, capital),\nso formatting everything through it would silently restyle every axis in every\nexisting chart. Opting in is the only version of this that is not a surprise.\n\n```ts\nexport function formatChartValue(\n n: number,\n format?: ChartValueFormat,\n opts?: ChartFormatLocale,\n): string\n```\n"
7807
7878
  },
7808
7879
  {
7809
7880
  "slug": "reference/auto/svgrid-grid-chart-hierarchy",
7810
7881
  "path": "docs/reference/auto/svgrid-grid-chart-hierarchy.md",
7811
7882
  "title": "@svgrid/grid · chart-hierarchy.ts",
7812
7883
  "section": "API reference",
7813
- "markdown": "# `@svgrid/grid` · `chart-hierarchy.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-hierarchy.ts`.\n\n### `function drillTree`\n\nThe subtree at `path` (a list of node names from the root's children down),\nor the tree itself for an empty path. What a drilldown shows after each\nclick: the clicked node becomes the root. Null when the path does not exist.\n\n```ts\nexport function drillTree(tree: TreeNode, path: ReadonlyArray<string>): TreeNode | null {\n let node: TreeNode | undefined = tree\n for (const name of path) {\n node = node?.children?.find((c) => c.name === name)\n if (!node) return null\n }\n return node ?? null\n}\n```\n\n### `function pathTo`\n\nThe path (node names from the root's children) to the first node called\n`name`, depth first, or null. What a click on a leaf's label needs.\n\n```ts\nexport function pathTo(tree: TreeNode, name: string): string[] | null {\n const walk = (n: TreeNode, acc: string[]): string[] | null => {\n for (const c of n.children ?? []) {\n const next = [...acc, c.name]\n if (c.name === name) return next\n const deeper = walk(c, next)\n if (deeper) return deeper\n }\n return null\n }\n return walk(tree, [])\n}\n```\n"
7884
+ "markdown": "# `@svgrid/grid` · `chart-hierarchy.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-hierarchy.ts`.\n\n### `function drillTree`\n\nThe subtree at `path` (a list of node names from the root's children down),\nor the tree itself for an empty path. What a drilldown shows after each\nclick: the clicked node becomes the root. Null when the path does not exist.\n\n```ts\nexport function drillTree(tree: TreeNode, path: ReadonlyArray<string>): TreeNode | null\n```\n\n### `function pathTo`\n\nThe path (node names from the root's children) to the first node called\n`name`, depth first, or null. What a click on a leaf's label needs.\n\n```ts\nexport function pathTo(tree: TreeNode, name: string): string[] | null\n```\n"
7814
7885
  },
7815
7886
  {
7816
7887
  "slug": "reference/auto/svgrid-grid-chart-indicators",
7817
7888
  "path": "docs/reference/auto/svgrid-grid-chart-indicators.md",
7818
7889
  "title": "@svgrid/grid · chart-indicators.ts",
7819
7890
  "section": "API reference",
7820
- "markdown": "# `@svgrid/grid` · `chart-indicators.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-indicators.ts`.\n\n### `type ChartIndicatorSpec`\n\nWhich indicator a pane shows, and with what parameters.\n\n```ts\nexport type ChartIndicatorSpec = {\n kind: 'rsi' | 'macd' | 'stochastic' | 'atr' | 'obv' | 'volume'\n /** The series (by label) the indicator reads. Defaults to the first\n * series with `ohlc`, else the first series. */\n source?: string\n /** Periods: `period` (RSI / ATR / stochastic %K), `fast` / `slow` /\n * `signal` (MACD), `smooth` (stochastic %D). Each has the usual default. */\n params?: { period?: number; fast?: number; slow?: number; signal?: number; smooth?: number }\n /** Pane height in px; the default is a third of the main chart. */\n height?: number\n}\n```\n\n### `function wma`\n\nWeighted moving average: the latest value weighs `period`, the oldest 1.\n\n```ts\nexport function wma(values: ReadonlyArray<number>, period: number): number[] {\n const n = values.length\n const p = Math.max(1, Math.floor(period))\n const out = nanArray(n)\n const denom = (p * (p + 1)) / 2\n for (let i = p - 1; i < n; i += 1) {\n let sum = 0\n let ok = true\n for (let k = 0; k < p; k += 1) {\n const v = values[i - k]!\n if (!Number.isFinite(v)) { ok = false; break }\n sum += v * (p - k)\n }\n if (ok) out[i] = sum / denom\n }\n return out\n}\n```\n\n### `function bollingerBands`\n\nBollinger bands: a simple moving average with a band `k` standard\ndeviations either side (population deviation, as the terminals compute it).\n\n```ts\nexport function bollingerBands(values: ReadonlyArray<number>, period = 20, k = 2): { middle: number[]; upper: number[]; lower: number[] } {\n const n = values.length\n const p = Math.max(1, Math.floor(period))\n const middle = simpleMovingAverage(values as number[], p)\n const upper = nanArray(n)\n const lower = nanArray(n)\n for (let i = p - 1; i < n; i += 1) {\n const m = middle[i]!\n if (!Number.isFinite(m)) continue\n let ss = 0\n let count = 0\n for (let j = i - p + 1; j <= i; j += 1) {\n const v = values[j]!\n if (!Number.isFinite(v)) continue\n ss += (v - m) * (v - m)\n count += 1\n }\n const sd = count ? Math.sqrt(ss / count) : 0\n upper[i] = m + k * sd\n lower[i] = m - k * sd\n }\n return { middle, upper, lower }\n}\n```\n\n### `function rsi`\n\nRelative strength index over `period` bars, 0 to 100. The first value lands\nat index `period`; before it there is nothing to average.\n\n```ts\nexport function rsi(values: ReadonlyArray<number>, period = 14): number[] {\n const n = values.length\n const p = Math.max(1, Math.floor(period))\n const out = nanArray(n)\n if (n <= p) return out\n let gain = 0\n let loss = 0\n for (let i = 1; i <= p; i += 1) {\n const d = values[i]! - values[i - 1]!\n if (d > 0) gain += d\n else loss -= d\n }\n let avgGain = gain / p\n let avgLoss = loss / p\n const rs = (g: number, l: number) => (l === 0 ? 100 : 100 - 100 / (1 + g / l))\n out[p] = rs(avgGain, avgLoss)\n for (let i = p + 1; i < n; i += 1) {\n const d = values[i]! - values[i - 1]!\n avgGain = (avgGain * (p - 1) + (d > 0 ? d : 0)) / p\n avgLoss = (avgLoss * (p - 1) + (d < 0 ? -d : 0)) / p\n out[i] = rs(avgGain, avgLoss)\n }\n return out\n}\n```\n\n### `function macd`\n\nMoving average convergence / divergence: the fast EMA minus the slow one,\nits signal EMA, and the histogram between them.\n\n```ts\nexport function macd(values: ReadonlyArray<number>, fast = 12, slow = 26, signal = 9): { macd: number[]; signal: number[]; histogram: number[] } {\n const n = values.length\n const f = exponentialMovingAverage(values as number[], fast)\n const s = exponentialMovingAverage(values as number[], slow)\n const line = nanArray(n)\n // The slow EMA is only meaningful once it has seen `slow` values; before\n // that both averages are still warming up and the difference is noise.\n for (let i = slow - 1; i < n; i += 1) line[i] = f[i]! - s[i]!\n const sig = nanArray(n)\n const hist = nanArray(n)\n const alpha = 2 / (Math.max(1, signal) + 1)\n let prev: number | null = null\n let seen = 0\n for (let i = 0; i < n; i += 1) {\n const v = line[i]!\n if (!Number.isFinite(v)) continue\n seen += 1\n prev = prev == null ? v : alpha * v + (1 - alpha) * prev\n if (seen >= signal) {\n sig[i] = prev\n hist[i] = v - prev\n }\n }\n return { macd: line, signal: sig, histogram: hist }\n}\n```\n\n### `function vwap`\n\nVolume-weighted average price, cumulative from the first bar. Reset it per\nsession by resampling or slicing before calling.\n\n```ts\nexport function vwap(ohlc: ReadonlyArray<OhlcBar | null | undefined>, volumes: ReadonlyArray<number>): number[] {\n const n = ohlc.length\n const out = nanArray(n)\n let pv = 0\n let vol = 0\n for (let i = 0; i < n; i += 1) {\n const b = ohlc[i]\n const v = volumes[i]\n if (!b || !Number.isFinite(v)) { out[i] = vol > 0 ? pv / vol : Number.NaN; continue }\n pv += typical(b) * v!\n vol += v!\n out[i] = vol > 0 ? pv / vol : Number.NaN\n }\n return out\n}\n```\n\n### `function atr`\n\nAverage true range with Wilder's smoothing.\n\n```ts\nexport function atr(ohlc: ReadonlyArray<OhlcBar | null | undefined>, period = 14): number[] {\n const n = ohlc.length\n const p = Math.max(1, Math.floor(period))\n const out = nanArray(n)\n if (n < p) return out\n let sum = 0\n for (let i = 0; i < p; i += 1) {\n const tr = trueRange(ohlc, i)\n if (!Number.isFinite(tr)) return out\n sum += tr\n }\n let prev = sum / p\n out[p - 1] = prev\n for (let i = p; i < n; i += 1) {\n const tr = trueRange(ohlc, i)\n if (!Number.isFinite(tr)) { out[i] = Number.NaN; continue }\n prev = (prev * (p - 1) + tr) / p\n out[i] = prev\n }\n return out\n}\n```\n\n### `function stochastic`\n\nStochastic oscillator: %K is where the close sits in the last `period`\nbars' range (0 to 100), %D its `smooth`-bar simple average.\n\n```ts\nexport function stochastic(ohlc: ReadonlyArray<OhlcBar | null | undefined>, period = 14, smooth = 3): { k: number[]; d: number[] } {\n const n = ohlc.length\n const p = Math.max(1, Math.floor(period))\n const k = nanArray(n)\n for (let i = p - 1; i < n; i += 1) {\n let hi = -Infinity\n let lo = Infinity\n let ok = true\n for (let j = i - p + 1; j <= i; j += 1) {\n const b = ohlc[j]\n if (!b) { ok = false; break }\n if (b.h > hi) hi = b.h\n if (b.l < lo) lo = b.l\n }\n const c = ohlc[i]?.c\n if (!ok || c == null) continue\n k[i] = hi === lo ? 50 : ((c - lo) / (hi - lo)) * 100\n }\n // %D is a strict average: it starts once `smooth` %K values exist, rather\n // than averaging whatever is there (which is what the tolerant SMA does).\n const sm = Math.max(1, Math.floor(smooth))\n const d = nanArray(n)\n for (let i = sm - 1; i < n; i += 1) {\n let sum = 0\n let ok = true\n for (let j = i - sm + 1; j <= i; j += 1) {\n if (!Number.isFinite(k[j])) { ok = false; break }\n sum += k[j]!\n }\n if (ok) d[i] = sum / sm\n }\n return { k, d }\n}\n```\n\n### `function obv`\n\nOn-balance volume: a running total that adds volume on up closes and\n subtracts it on down closes.\n\n```ts\nexport function obv(closes: ReadonlyArray<number>, volumes: ReadonlyArray<number>): number[] {\n const n = closes.length\n const out = nanArray(n)\n let total = 0\n for (let i = 0; i < n; i += 1) {\n const v = volumes[i]\n if (!Number.isFinite(closes[i]) || !Number.isFinite(v)) { out[i] = total; continue }\n if (i > 0 && Number.isFinite(closes[i - 1])) {\n if (closes[i]! > closes[i - 1]!) total += v!\n else if (closes[i]! < closes[i - 1]!) total -= v!\n }\n out[i] = total\n }\n return out\n}\n```\n\n### `function computeOverlay`\n\nCompute overlay values for a series spec like 'sma:7' / 'ema:14' / 'wma:9' /\n'linear'. `'bb:N:K'` returns the band's middle line (the engine draws the\nband from `bollingerBands` itself) and `'vwap'` needs bars and volumes, so\nit comes back as gaps here; pass `extra` for those two.\n\n```ts\nexport function computeOverlay(values: number[], spec: SeriesOverlay, extra?: { ohlc?: ReadonlyArray<OhlcBar | null>; volumes?: ReadonlyArray<number> }): number[] {\n return computeOverlayFit(values, spec, extra).values\n}\n```\n\n### `function computeOverlayFit`\n\n{@link computeOverlay} plus what a regression knows about itself: its\nR-squared and equation. The moving averages, the bands and VWAP carry\nneither.\n\n```ts\nexport function computeOverlayFit(values: number[], spec: SeriesOverlay, extra?: { ohlc?: ReadonlyArray<OhlcBar | null>; volumes?: ReadonlyArray<number> }): { values: number[]; r2?: number; equation?: string } {\n const fit = (f: { fitted: number[]; r2: number; equation: string }) => (f.equation ? { values: f.fitted, r2: f.r2, equation: f.equation } : { values: f.fitted })\n const reg = regressionFit(values, spec)\n if (reg) return fit(reg)\n return { values: computeOverlayPlain(values, spec, extra) }\n}\n```\n\n### `function regressionFit`\n\nThe regression an overlay string names (`linear`, `poly:N`, `exp`, `log`,\n`power`), fitted to `values` on their index or on `xs`; `null` for the\nmoving averages and bands, which are not regressions. A scatter passes its\npoints' x and y so the curve is y on x, and reads `predict` to draw it.\n\n```ts\nexport function regressionFit(values: ReadonlyArray<number>, spec: SeriesOverlay, xs?: ReadonlyArray<number>): RegressionFit | null {\n if (spec === 'linear') return linearFit(values, xs)\n if (spec === 'exp') return exponentialFit(values, xs)\n if (spec === 'log') return logarithmicFit(values, xs)\n if (spec === 'power') return powerFit(values, xs)\n const poly = /^poly:(\\d+)$/.exec(spec)\n if (poly) return polynomialFit(values, Number(poly[1]), xs)\n return null\n}\n```\n\n### `function overlayName`\n\nThe name a tooltip or legend gives an overlay: `sma:20` reads \"SMA 20\",\n `poly:3` \"poly 3\", `bb:20:2` \"BB 20\", the rest as written.\n\n```ts\nexport function overlayName(spec: SeriesOverlay): string {\n const m = /^(sma|ema|wma|bb|poly):(\\d+)/.exec(spec)\n if (!m) return spec === 'linear' ? 'trend' : spec\n return `${m[1] === 'poly' ? 'poly' : m[1]!.toUpperCase()} ${m[2]}`\n}\n```\n\n### `function indicatorPane`\n\nBuild the spec of an indicator pane from a price spec: the same categories\nand x axis, the indicator's lines or bars, and the reference lines the\nindicator is read against (30 / 70 for RSI, 20 / 80 for the stochastic, a\nzero line for MACD). `SvChartPanes` stacks these under the price chart and\nsyncs them; a pane is also a complete spec for a standalone `SvChart`.\n\n```ts\nexport function indicatorPane(spec: ChartSpec, ind: ChartIndicatorSpec): ChartSpec {\n const src = sourceSeries(spec, ind)\n const n = spec.categories.length\n const closes = src ? closesOf(src) : nanArray(n)\n const ohlc = src?.ohlc ?? closes.map((c) => (Number.isFinite(c) ? { o: c, h: c, l: c, c } : null))\n const volumes = src?.volumes ?? nanArray(n)\n const params = ind.params ?? {}\n const base: Pick<ChartSpec, 'categories' | 'xType' | 'xAxis' | 'height' | 'palette' | 'valueFormat' | 'locale'> = {\n categories: spec.categories,\n xType: spec.xType,\n xAxis: spec.xAxis,\n height: ind.height ?? Math.max(90, Math.round((spec.height ?? 300) / 3)),\n palette: spec.palette,\n valueFormat: 'number',\n locale: spec.locale,\n }\n const refs = (lines: Array<[number, string]>): ChartReferenceLine[] =>\n lines.map(([value, label]) => ({ value, label, dashed: true }))\n switch (ind.kind) {\n case 'rsi': {\n const p = params.period ?? 14\n return { ...base, type: 'line', title: `RSI ${p}`, series: [{ label: `RSI ${p}`, values: rsi(closes, p), marker: 'none' }],\n yAxis: { min: 0, max: 100, tickInterval: 50, nice: false }, referenceLines: refs([[30, '30'], [70, '70']]) }\n }\n case 'stochastic': {\n const p = params.period ?? 14\n const sm = params.smooth ?? 3\n const { k, d } = stochastic(ohlc, p, sm)\n return { ...base, type: 'line', title: `Stochastic ${p}, ${sm}`, series: [\n { label: '%K', values: k, marker: 'none' }, { label: '%D', values: d, marker: 'none', dash: [4, 3] },\n ], yAxis: { min: 0, max: 100, tickInterval: 50, nice: false }, referenceLines: refs([[20, '20'], [80, '80']]) }\n }\n case 'macd': {\n const fast = params.fast ?? 12\n const slow = params.slow ?? 26\n const signal = params.signal ?? 9\n const m = macd(closes, fast, slow, signal)\n return { ...base, type: 'bar', title: `MACD ${fast}, ${slow}, ${signal}`, series: [\n { label: 'Histogram', values: m.histogram, colors: m.histogram.map((v) => (v < 0 ? '#ef4444' : '#16a34a')) },\n { label: 'MACD', values: m.macd, type: 'line', marker: 'none' },\n { label: 'Signal', values: m.signal, type: 'line', marker: 'none', dash: [4, 3] },\n ], referenceLines: refs([[0, '']]) }\n }\n case 'atr': {\n const p = params.period ?? 14\n return { ...base, type: 'line', title: `ATR ${p}`, series: [{ label: `ATR ${p}`, values: atr(ohlc, p), marker: 'none' }], yAxis: { min: 0 } }\n }\n case 'obv':\n return { ...base, type: 'line', title: 'OBV', series: [{ label: 'OBV', values: obv(closes, volumes), marker: 'none' }], valueFormat: 'compact' }\n case 'volume':\n default: {\n // Up bars in the up colour, down bars in the down colour, like the candles.\n const colors = ohlc.map((b, i) => {\n if (!b) return null\n const prev = i > 0 ? ohlc[i - 1] : null\n const up = prev ? b.c >= prev.c : b.c >= b.o\n return up ? '#16a34a' : '#ef4444'\n })\n return { ...base, type: 'bar', title: 'Volume', series: [{ label: 'Volume', values: volumes.slice(), colors }], yAxis: { min: 0 }, valueFormat: 'compact' }\n }\n }\n}\n```\n"
7891
+ "markdown": "# `@svgrid/grid` · `chart-indicators.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-indicators.ts`.\n\n### `type ChartIndicatorSpec`\n\nWhich indicator a pane shows, and with what parameters.\n\n```ts\nexport type ChartIndicatorSpec = {\n kind: 'rsi' | 'macd' | 'stochastic' | 'atr' | 'obv' | 'volume'\n /** The series (by label) the indicator reads. Defaults to the first\n * series with `ohlc`, else the first series. */\n source?: string\n /** Periods: `period` (RSI / ATR / stochastic %K), `fast` / `slow` /\n * `signal` (MACD), `smooth` (stochastic %D). Each has the usual default. */\n params?: { period?: number; fast?: number; slow?: number; signal?: number; smooth?: number }\n /** Pane height in px; the default is a third of the main chart. */\n height?: number\n}\n```\n\n### `function wma`\n\nWeighted moving average: the latest value weighs `period`, the oldest 1.\n\n```ts\nexport function wma(values: ReadonlyArray<number>, period: number): number[]\n```\n\n### `function bollingerBands`\n\nBollinger bands: a simple moving average with a band `k` standard\ndeviations either side (population deviation, as the terminals compute it).\n\n```ts\nexport function bollingerBands(values: ReadonlyArray<number>, period = 20, k = 2): { middle: number[]; upper: number[]; lower: number[] }\n```\n\n### `function rsi`\n\nRelative strength index over `period` bars, 0 to 100. The first value lands\nat index `period`; before it there is nothing to average.\n\n```ts\nexport function rsi(values: ReadonlyArray<number>, period = 14): number[]\n```\n\n### `function macd`\n\nMoving average convergence / divergence: the fast EMA minus the slow one,\nits signal EMA, and the histogram between them.\n\n```ts\nexport function macd(values: ReadonlyArray<number>, fast = 12, slow = 26, signal = 9): { macd: number[]; signal: number[]; histogram: number[] }\n```\n\n### `function vwap`\n\nVolume-weighted average price, cumulative from the first bar. Reset it per\nsession by resampling or slicing before calling.\n\n```ts\nexport function vwap(ohlc: ReadonlyArray<OhlcBar | null | undefined>, volumes: ReadonlyArray<number>): number[]\n```\n\n### `function atr`\n\nAverage true range with Wilder's smoothing.\n\n```ts\nexport function atr(ohlc: ReadonlyArray<OhlcBar | null | undefined>, period = 14): number[]\n```\n\n### `function stochastic`\n\nStochastic oscillator: %K is where the close sits in the last `period`\nbars' range (0 to 100), %D its `smooth`-bar simple average.\n\n```ts\nexport function stochastic(ohlc: ReadonlyArray<OhlcBar | null | undefined>, period = 14, smooth = 3): { k: number[]; d: number[] }\n```\n\n### `function obv`\n\nOn-balance volume: a running total that adds volume on up closes and\n subtracts it on down closes.\n\n```ts\nexport function obv(closes: ReadonlyArray<number>, volumes: ReadonlyArray<number>): number[]\n```\n\n### `function computeOverlay`\n\nCompute overlay values for a series spec like 'sma:7' / 'ema:14' / 'wma:9' /\n'linear'. `'bb:N:K'` returns the band's middle line (the engine draws the\nband from `bollingerBands` itself) and `'vwap'` needs bars and volumes, so\nit comes back as gaps here; pass `extra` for those two.\n\n```ts\nexport function computeOverlay(values: number[], spec: SeriesOverlay, extra?: { ohlc?: ReadonlyArray<OhlcBar | null>; volumes?: ReadonlyArray<number> }): number[]\n```\n\n### `function computeOverlayFit`\n\n{@link computeOverlay} plus what a regression knows about itself: its\nR-squared and equation. The moving averages, the bands and VWAP carry\nneither.\n\n```ts\nexport function computeOverlayFit(values: number[], spec: SeriesOverlay, extra?: { ohlc?: ReadonlyArray<OhlcBar | null>; volumes?: ReadonlyArray<number> }): { values: number[]; r2?: number; equation?: string }\n```\n\n### `function regressionFit`\n\nThe regression an overlay string names (`linear`, `poly:N`, `exp`, `log`,\n`power`), fitted to `values` on their index or on `xs`; `null` for the\nmoving averages and bands, which are not regressions. A scatter passes its\npoints' x and y so the curve is y on x, and reads `predict` to draw it.\n\n```ts\nexport function regressionFit(values: ReadonlyArray<number>, spec: SeriesOverlay, xs?: ReadonlyArray<number>): RegressionFit | null\n```\n\n### `function overlayName`\n\nThe name a tooltip or legend gives an overlay: `sma:20` reads \"SMA 20\",\n `poly:3` \"poly 3\", `bb:20:2` \"BB 20\", the rest as written.\n\n```ts\nexport function overlayName(spec: SeriesOverlay): string\n```\n\n### `function indicatorPane`\n\nBuild the spec of an indicator pane from a price spec: the same categories\nand x axis, the indicator's lines or bars, and the reference lines the\nindicator is read against (30 / 70 for RSI, 20 / 80 for the stochastic, a\nzero line for MACD). `SvChartPanes` stacks these under the price chart and\nsyncs them; a pane is also a complete spec for a standalone `SvChart`.\n\n```ts\nexport function indicatorPane(spec: ChartSpec, ind: ChartIndicatorSpec): ChartSpec\n```\n"
7821
7892
  },
7822
7893
  {
7823
7894
  "slug": "reference/auto/svgrid-grid-chart-messages",
7824
7895
  "path": "docs/reference/auto/svgrid-grid-chart-messages.md",
7825
7896
  "title": "@svgrid/grid · chart-messages.ts",
7826
7897
  "section": "API reference",
7827
- "markdown": "# `@svgrid/grid` · `chart-messages.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-messages.ts`.\n\n### `type ChartMessages`\n\nEvery localizable chart string, grouped by area in the comments.\n\n```ts\nexport type ChartMessages = {\n // The image and its data table\n /** The SVG's accessible name. `{type}` is the chart type. */\n chartLabel: string\n /** The hidden data table's caption. `{type}` is the chart type. */\n dataTable: string\n /** Appended to the caption when the table is capped. `{shown}` / `{total}`. */\n dataTableCapped: string\n noData: string\n /** A point with no value, in labels and the live region. */\n noValue: string\n // What the live region and the marks say\n /** The live region while stepping through series: `{series}`, `{value}`, `{category}`. */\n seriesAtCategory: string\n /** A dense chart's single hit zone: `{count}`, `{from}`, `{to}`. */\n densePoints: string\n /** Appended to a slice or cell label that drills further. */\n drillIn: string\n /** A sankey node's label: `{label}`, `{in}`, `{out}`. */\n sankeyNode: string\n /** The donut's centre caption under the total. */\n total: string\n /** A regression overlay's goodness of fit in the tooltip. `{value}` is 0..1. */\n rSquared: string\n /** The context menu item that copies the chart's plain-language summary. */\n describeChart: string\n /** The live region after the summary was copied. */\n describeCopied: string\n // Toolbar\n drillPath: string\n drillRoot: string\n dateRange: string\n /** A preset button's title. `{preset}` is its label. */\n showLast: string\n pan: string\n panTitle: string\n resetZoom: string\n resetZoomTitle: string\n annotate: string\n annotateOnTitle: string\n annotateOffTitle: string\n drawingTools: string\n /** A drawing tool button's title. `{tool}` is the tool's label. */\n draw: string\n toolTrend: string\n toolRay: string\n toolFib: string\n toolRect: string\n toolArrow: string\n toolText: string\n /** A drawing's accessible name. `{tool}` is the tool's label. */\n drawing: string\n deleteDrawing: string\n deleteDrawingTitle: string\n clearDrawings: string\n clearDrawingsTitle: string\n noteText: string\n /** A note marker's name while annotating. `{label}` is the note. */\n removeNote: string\n png: string\n downloadPng: string\n svg: string\n downloadSvg: string\n pdf: string\n downloadPdf: string\n downloadCsv: string\n print: string\n printTitle: string\n copy: string\n copied: string\n copyTitle: string\n copyAsImage: string\n // Context menu\n range: string\n series: string\n // Legend\n showSeries: string\n hideSeries: string\n isolateHint: string\n /** The overflow toggle. `{n}` is how many chips are folded away. */\n showMore: string\n showLess: string\n // Brush\n rangeBrush: string\n /** The brush's value text. `{from}` / `{to}` are the window's ends. */\n brushRange: string\n}\n```\n\n### `const defaultChartMessages`\n\nThe English defaults.\n\n```ts\nexport const defaultChartMessages: ChartMessages = {\n chartLabel: '{type} chart',\n dataTable: '{type} chart data',\n dataTableCapped: ', first {shown} of {total} rows',\n noData: 'No data',\n noValue: 'no value',\n seriesAtCategory: '{series}: {value} at {category}',\n densePoints: '{count} points, {from} to {to}. Arrow keys step through values.',\n drillIn: ', drill in',\n sankeyNode: '{label}: in {in}, out {out}',\n total: 'Total',\n rSquared: 'R\\u00b2 {value}',\n describeChart: 'Describe chart',\n describeCopied: 'Description copied',\n drillPath: 'Drilldown path',\n drillRoot: 'All',\n dateRange: 'Date range',\n showLast: 'Show the last {preset}',\n pan: 'Pan',\n panTitle: 'Drag the plot to pan the zoomed window',\n resetZoom: 'Reset zoom',\n resetZoomTitle: 'Reset zoom (or double-click the plot)',\n annotate: 'Annotate',\n annotateOnTitle: 'Click the plot to pin a note, or a marker to remove it',\n annotateOffTitle: 'Pin notes on the chart',\n drawingTools: 'Drawing tools',\n draw: 'Draw: {tool}',\n toolTrend: 'Trend',\n toolRay: 'Ray',\n toolFib: 'Fib',\n toolRect: 'Rect',\n toolArrow: 'Arrow',\n toolText: 'Text',\n drawing: '{tool} drawing',\n deleteDrawing: 'Delete',\n deleteDrawingTitle: 'Remove the selected drawing (Delete)',\n clearDrawings: 'Clear',\n clearDrawingsTitle: 'Remove every drawing',\n noteText: 'Note text',\n removeNote: 'Remove note: {label}',\n png: 'PNG',\n downloadPng: 'Download PNG',\n svg: 'SVG',\n downloadSvg: 'Download SVG',\n pdf: 'PDF',\n downloadPdf: 'Download PDF',\n downloadCsv: 'Download CSV',\n print: 'Print',\n printTitle: 'Print the chart',\n copy: 'Copy',\n copied: '✓ Copied',\n copyTitle: 'Copy chart as image',\n copyAsImage: 'Copy as image',\n range: 'Range',\n series: 'Series',\n showSeries: 'Show',\n hideSeries: 'Hide',\n isolateHint: 'double-click to isolate',\n showMore: '+{n} more',\n showLess: 'Show less',\n rangeBrush: 'Range brush',\n brushRange: '{from} to {to}',\n}\n```\n\n### `function resolveChartMessages`\n\nMerge a consumer's `localeText` over the English defaults. Undefined or\nempty values fall back to the default, so a partial map only replaces the\nkeys it sets.\n\n```ts\nexport function resolveChartMessages(overrides?: Partial<ChartMessages> | null): ChartMessages {\n return resolveMessages(defaultChartMessages, overrides)\n}\n```\n\n### `function chartMessage`\n\nFill a message's `{name}` placeholders. Unknown placeholders are left as\nthey are, so a translation that drops one loses nothing.\n\n```ts\nexport function chartMessage(template: string, vars: Record<string, string | number>): string {\n return template.replace(/\\{(\\w+)\\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m))\n}\n```\n"
7898
+ "markdown": "# `@svgrid/grid` · `chart-messages.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-messages.ts`.\n\n### `type ChartMessages`\n\nEvery localizable chart string, grouped by area in the comments.\n\n```ts\nexport type ChartMessages = {\n // The image and its data table\n /** The SVG's accessible name. `{type}` is the chart type. */\n chartLabel: string\n /** The hidden data table's caption. `{type}` is the chart type. */\n dataTable: string\n /** Appended to the caption when the table is capped. `{shown}` / `{total}`. */\n dataTableCapped: string\n noData: string\n /** A point with no value, in labels and the live region. */\n noValue: string\n // What the live region and the marks say\n /** The live region while stepping through series: `{series}`, `{value}`, `{category}`. */\n seriesAtCategory: string\n /** A dense chart's single hit zone: `{count}`, `{from}`, `{to}`. */\n densePoints: string\n /** Appended to a slice or cell label that drills further. */\n drillIn: string\n /** A sankey node's label: `{label}`, `{in}`, `{out}`. */\n sankeyNode: string\n /** The donut's centre caption under the total. */\n total: string\n /** A regression overlay's goodness of fit in the tooltip. `{value}` is 0..1. */\n rSquared: string\n /** The context menu item that copies the chart's plain-language summary. */\n describeChart: string\n /** The live region after the summary was copied. */\n describeCopied: string\n // Toolbar\n drillPath: string\n drillRoot: string\n dateRange: string\n /** A preset button's title. `{preset}` is its label. */\n showLast: string\n pan: string\n panTitle: string\n resetZoom: string\n resetZoomTitle: string\n annotate: string\n annotateOnTitle: string\n annotateOffTitle: string\n drawingTools: string\n /** A drawing tool button's title. `{tool}` is the tool's label. */\n draw: string\n toolTrend: string\n toolRay: string\n toolFib: string\n toolRect: string\n toolArrow: string\n toolText: string\n /** A drawing's accessible name. `{tool}` is the tool's label. */\n drawing: string\n deleteDrawing: string\n deleteDrawingTitle: string\n clearDrawings: string\n clearDrawingsTitle: string\n noteText: string\n /** A note marker's name while annotating. `{label}` is the note. */\n removeNote: string\n png: string\n downloadPng: string\n svg: string\n downloadSvg: string\n pdf: string\n downloadPdf: string\n downloadCsv: string\n print: string\n printTitle: string\n copy: string\n copied: string\n copyTitle: string\n copyAsImage: string\n // Context menu\n range: string\n series: string\n // Legend\n showSeries: string\n hideSeries: string\n isolateHint: string\n /** The overflow toggle. `{n}` is how many chips are folded away. */\n showMore: string\n showLess: string\n // Brush\n rangeBrush: string\n /** The brush's value text. `{from}` / `{to}` are the window's ends. */\n brushRange: string\n}\n```\n\n### `const defaultChartMessages`\n\nThe English defaults.\n\n```ts\nexport const defaultChartMessages: ChartMessages = {\n chartLabel: '{type} chart',\n dataTable: '{type} chart data',\n dataTableCapped: ', first {shown} of {total} rows',\n noData: 'No data',\n noValue: 'no value',\n seriesAtCategory: '{series}: {value} at {category}',\n densePoints: '{count} points, {from} to {to}. Arrow keys step through values.',\n drillIn: ', drill in',\n sankeyNode: '{label}: in {in}, out {out}',\n total: 'Total',\n rSquared: 'R\\u00b2 {value}',\n describeChart: 'Describe chart',\n describeCopied: 'Description copied',\n drillPath: 'Drilldown path',\n drillRoot: 'All',\n dateRange: 'Date range',\n showLast: 'Show the last {preset}',\n pan: 'Pan',\n panTitle: 'Drag the plot to pan the zoomed window',\n resetZoom: 'Reset zoom',\n resetZoomTitle: 'Reset zoom (or double-click the plot)',\n annotate: 'Annotate',\n annotateOnTitle: 'Click the plot to pin a note, or a marker to remove it',\n annotateOffTitle: 'Pin notes on the chart',\n drawingTools: 'Drawing tools',\n draw: 'Draw: {tool}',\n toolTrend: 'Trend',\n toolRay: 'Ray',\n toolFib: 'Fib',\n toolRect: 'Rect',\n toolArrow: 'Arrow',\n toolText: 'Text',\n drawing: '{tool} drawing',\n deleteDrawing: 'Delete',\n deleteDrawingTitle: 'Remove the selected drawing (Delete)',\n clearDrawings: 'Clear',\n clearDrawingsTitle: 'Remove every drawing',\n noteText: 'Note text',\n removeNote: 'Remove note: {label}',\n png: 'PNG',\n downloadPng: 'Download PNG',\n svg: 'SVG',\n downloadSvg: 'Download SVG',\n pdf: 'PDF',\n downloadPdf: 'Download PDF',\n downloadCsv: 'Download CSV',\n print: 'Print',\n printTitle: 'Print the chart',\n copy: 'Copy',\n copied: '✓ Copied',\n copyTitle: 'Copy chart as image',\n copyAsImage: 'Copy as image',\n range: 'Range',\n series: 'Series',\n showSeries: 'Show',\n hideSeries: 'Hide',\n isolateHint: 'double-click to isolate',\n showMore: '+{n} more',\n showLess: 'Show less',\n rangeBrush: 'Range brush',\n brushRange: '{from} to {to}',\n}\n```\n\n### `function resolveChartMessages`\n\nMerge a consumer's `localeText` over the English defaults. Undefined or\nempty values fall back to the default, so a partial map only replaces the\nkeys it sets.\n\n```ts\nexport function resolveChartMessages(overrides?: Partial<ChartMessages> | null): ChartMessages\n```\n\n### `function chartMessage`\n\nFill a message's `{name}` placeholders. Unknown placeholders are left as\nthey are, so a translation that drops one loses nothing.\n\n```ts\nexport function chartMessage(template: string, vars: Record<string, string | number>): string\n```\n"
7828
7899
  },
7829
7900
  {
7830
7901
  "slug": "reference/auto/svgrid-grid-chart-motion",
7831
7902
  "path": "docs/reference/auto/svgrid-grid-chart-motion.md",
7832
7903
  "title": "@svgrid/grid · chart-motion.ts",
7833
7904
  "section": "API reference",
7834
- "markdown": "# `@svgrid/grid` · `chart-motion.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-motion.ts`.\n\n### `function interpolateGeometry`\n\nThe geometry at fraction `t` (0..1) between `from` and `to`. At `t >= 1`\nthis is `to` itself, so a finished tween costs nothing.\n\n```ts\nexport function interpolateGeometry(from: ChartGeometry, to: ChartGeometry, t: number): ChartGeometry {\n if (t >= 1) return to\n if (t <= 0 && from.type === to.type) return from\n if (from.type !== to.type) return to\n return {\n ...to,\n bars: tweenBars(from.bars, to.bars, t, to.plot.y + to.plot.h),\n lines: tweenLines(from.lines, to.lines, t),\n candles: tweenCandles(from.candles, to.candles, t),\n slices: tweenSlices(from.slices, to.slices, t),\n arcs: tweenArcs(from.arcs, to.arcs, t),\n yTicks: to.yTicks.map((tick) => {\n const prev = from.yTicks.find((p) => p.value === tick.value)\n return prev ? { ...tick, y: r2(mix(prev.y, tick.y, t)) } : tick\n }),\n }\n}\n```\n"
7905
+ "markdown": "# `@svgrid/grid` · `chart-motion.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-motion.ts`.\n\n### `function interpolateGeometry`\n\nThe geometry at fraction `t` (0..1) between `from` and `to`. At `t >= 1`\nthis is `to` itself, so a finished tween costs nothing.\n\n```ts\nexport function interpolateGeometry(from: ChartGeometry, to: ChartGeometry, t: number): ChartGeometry\n```\n"
7835
7906
  },
7836
7907
  {
7837
7908
  "slug": "reference/auto/svgrid-grid-chart-panel-messages",
7838
7909
  "path": "docs/reference/auto/svgrid-grid-chart-panel-messages.md",
7839
7910
  "title": "@svgrid/grid · chart-panel-messages.ts",
7840
7911
  "section": "API reference",
7841
- "markdown": "# `@svgrid/grid` · `chart-panel-messages.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-panel-messages.ts`.\n\n### `type GridChartPanelMessages`\n\nEvery localizable chart panel and builder string.\n\n```ts\nexport type GridChartPanelMessages = {\n // Panel head and actions\n chartPanelTitle: string\n chartClearFilter: string\n chartExport: string\n chartExportLabel: string\n chartExportPng: string\n chartExportSvg: string\n chartExportPdf: string\n chartExportCsv: string\n chartExportCopy: string\n chartExportPrint: string\n chartExportDescribe: string\n chartAi: string\n chartAiLabel: string\n chartAiPlaceholder: string\n chartAiRun: string\n chartAiThinking: string\n chartAiExplain: string\n chartAiExplainTitle: string\n chartAiNoChart: string\n chartAiNoExplanation: string\n chartAiFailed: string\n chartBuild: string\n chartBuildLabel: string\n chartBuildTitle: string\n chartLinkBack: string\n chartUnlink: string\n chartLinkedTitle: string\n chartUnlinkedTitle: string\n chartAdd: string\n chartSave: string\n chartSaveLabel: string\n chartSavedTitle: string\n chartSaveName: string\n chartSaveNamePlaceholder: string\n chartSaveApply: string\n /** The pickers' note in pivot mode, where the pivot on screen is the chart. */\n chartPivotHint: string\n chartSaveRemove: string\n chartSavedEmpty: string\n chartMaximize: string\n chartRestore: string\n chartDock: string\n chartDockLabel: string\n chartPopOut: string\n chartPopOutLabel: string\n chartClose: string\n chartResize: string\n chartResizeWindow: string\n chartTabs: string\n chartRemoveTab: string\n chartRemove: string\n chartEmptyColumns: string\n chartEmptyData: string\n // Pickers\n chartType: string\n chartDate: string\n chartGroupBy: string\n chartFrom: string\n chartColumns: string\n chartSplitBy: string\n chartTo: string\n chartRows: string\n chartNone: string\n chartValue: string\n chartX: string\n chartY: string\n chartLow: string\n chartHigh: string\n chartOpen: string\n chartClosePrice: string\n chartVolume: string\n chartMetric: string\n chartTarget: string\n chartAggregate: string\n chartReduceSum: string\n chartReduceAvg: string\n chartReduceCount: string\n chartReduceMin: string\n chartReduceMax: string\n chartReduceMedian: string\n chartReduceP90: string\n chartReduceFirst: string\n chartReduceLast: string\n chartReduceCountDistinct: string\n chartBins: string\n chartBinsTitle: string\n chartShape: string\n chartShapeFunnel: string\n chartShapePyramid: string\n chartShapeCone: string\n chartCandles: string\n chartCandlesClassic: string\n chartCandlesHollow: string\n chartCandlesHeikinAshi: string\n chartIndicators: string\n chartIndVolume: string\n chartIndVolumeTitle: string\n chartIndRsi: string\n chartIndRsiTitle: string\n chartIndMacd: string\n chartIndMacdTitle: string\n chartIndStochastic: string\n chartIndStochasticTitle: string\n chartIndAtr: string\n chartIndAtrTitle: string\n chartIndObv: string\n chartIndObvTitle: string\n chartIndSma: string\n chartIndSmaTitle: string\n chartIndEma: string\n chartIndEmaTitle: string\n chartIndBb: string\n chartIndBbTitle: string\n chartIndVwap: string\n chartIndVwapTitle: string\n chartFormat: string\n chartFormatNumber: string\n chartFormatCurrency: string\n chartFormatPercent: string\n chartStacked: string\n chartStacked100: string\n chartStacked100Title: string\n chartHorizontal: string\n chartHorizontalTitle: string\n chartDonut: string\n chartColours: string\n chartPaletteTheme: string\n chartPaletteOcean: string\n chartPaletteSunset: string\n chartPaletteForest: string\n chartPaletteSlate: string\n chartLabels: string\n chartLogScale: string\n chartLogScaleTitle: string\n chartBucket: string\n chartBucketTitle: string\n chartBucketExact: string\n chartBucketDay: string\n chartBucketWeek: string\n chartBucketMonth: string\n chartBucketQuarter: string\n chartBucketYear: string\n chartDateAxis: string\n chartDateAxisTitle: string\n // Type names and their groups\n chartGroupCompare: string\n chartGroupPartOfWhole: string\n chartGroupFlow: string\n chartGroupDistribution: string\n chartGroupSingleValue: string\n chartGroupOverTime: string\n chartTypeBar: string\n chartTypeLine: string\n chartTypeArea: string\n chartTypeLollipop: string\n chartTypePareto: string\n chartTypeRangeBar: string\n chartTypeRangeArea: string\n chartTypeDumbbell: string\n chartTypeRadialColumn: string\n chartTypeRadialBar: string\n chartTypeNightingale: string\n chartTypePie: string\n chartTypeTreemap: string\n chartTypeSunburst: string\n chartTypeFunnel: string\n chartTypeWaterfall: string\n chartTypeSankey: string\n chartTypeChord: string\n chartTypeRadar: string\n chartTypeHeatmap: string\n chartTypeScatter: string\n chartTypeBoxplot: string\n chartTypeHistogram: string\n chartTypeGauge: string\n chartTypeBullet: string\n chartTypeCalendar: string\n chartTypeStream: string\n chartTypeCandlestick: string\n chartTypeOhlc: string\n // Why the chosen type cannot draw yet\n chartIssueHeatmap: string\n chartIssueSankey: string\n chartIssueRadar: string\n chartIssueFunnel: string\n chartIssueChord: string\n chartIssueStream: string\n chartIssueSecondMeasure: string\n chartIssueOhlcDate: string\n chartIssueOhlcColumns: string\n // Builder\n chartBuilderTitle: string\n chartBuilderTabType: string\n chartBuilderTabData: string\n chartBuilderTabFormat: string\n chartBuilderLinked: string\n chartBuilderFrozenAt: string\n chartBuilderFollows: string\n chartBuilderTitleField: string\n chartBuilderSubtitle: string\n chartBuilderCaption: string\n chartBuilderLegend: string\n chartLegendBottom: string\n chartLegendTop: string\n chartLegendLeft: string\n chartLegendRight: string\n chartLegendHidden: string\n chartBuilderDataLabels: string\n chartBuilderPanelSetting: string\n chartLabelsTop: string\n chartLabelsOutside: string\n chartLabelsInside: string\n chartLabelsCenter: string\n chartLabelsHidden: string\n chartBuilderSeriesLabels: string\n chartBuilderCrosshairLabels: string\n chartBuilderCompactBelow: string\n chartBuilderCompactBelowTitle: string\n chartBuilderValueAxis: string\n chartBuilderRightAxis: string\n chartBuilderCategoryAxis: string\n chartBuilderMin: string\n chartBuilderMax: string\n chartBuilderAuto: string\n chartBuilderOff: string\n chartBuilderGridLines: string\n chartBuilderAxisLabels: string\n chartBuilderLabelsAuto: string\n chartBuilderLabelsHorizontal: string\n chartBuilderLabelsTilted: string\n chartBuilderLabelsVertical: string\n chartBuilderSeries: string\n chartBuilderColor: string\n chartBuilderSeriesType: string\n chartBuilderAxis: string\n chartBuilderMarker: string\n chartBuilderWidth: string\n chartBuilderStack: string\n chartBuilderStackPlaceholder: string\n chartBuilderSeriesColorLabel: string\n chartBuilderSeriesTypeLabel: string\n chartBuilderSeriesAxisLabel: string\n chartBuilderSeriesMarkerLabel: string\n chartBuilderSeriesWidthLabel: string\n chartBuilderSeriesStackLabel: string\n chartBuilderChartType: string\n chartBuilderBar: string\n chartBuilderLine: string\n chartBuilderArea: string\n chartBuilderLeft: string\n chartBuilderRight: string\n chartBuilderStyle: string\n chartBuilderFontSize: string\n chartBuilderFontFamily: string\n chartBuilderBackground: string\n chartBuilderTextColor: string\n chartBuilderResetFormat: string\n}\n```\n\n### `const defaultChartPanelMessages`\n\nEnglish defaults: the literal strings the panel and the builder shipped with.\n\n```ts\nexport const defaultChartPanelMessages: GridChartPanelMessages = {\n chartPanelTitle: 'Chart',\n chartClearFilter: 'Clear filter',\n chartExport: 'Export',\n chartExportLabel: 'Export chart',\n chartExportPng: 'PNG image',\n chartExportSvg: 'SVG vector',\n chartExportPdf: 'PDF document',\n chartExportCsv: 'CSV data',\n chartExportCopy: 'Copy to clipboard',\n chartExportPrint: 'Print',\n chartExportDescribe: 'Describe chart',\n chartAi: 'AI',\n chartAiLabel: 'Chart with AI',\n chartAiPlaceholder: 'Describe a chart, e.g. revenue by region stacked by product',\n chartAiRun: 'Chart it',\n chartAiThinking: 'Thinking...',\n chartAiExplain: 'Explain',\n chartAiExplainTitle: 'Explain this chart in plain words',\n chartAiNoChart: \"Couldn't build a chart from that request.\",\n chartAiNoExplanation: \"Couldn't explain this chart.\",\n chartAiFailed: 'Something went wrong.',\n chartBuild: 'Build',\n chartBuildLabel: 'Open the chart builder',\n chartBuildTitle: 'Chart builder: type gallery, data and format',\n chartLinkBack: 'Link the chart back to the grid',\n chartUnlink: 'Unlink the chart from the grid',\n chartLinkedTitle: \"Linked: the chart follows the grid's rows. Click to freeze it.\",\n chartUnlinkedTitle: 'Unlinked: the chart keeps the data it has. Click to follow the grid again.',\n chartAdd: 'Add chart',\n chartSave: 'Save',\n chartSaveLabel: 'Saved charts',\n chartSavedTitle: 'Saved charts',\n chartSaveName: 'Save this chart as',\n chartSaveNamePlaceholder: 'Name',\n chartSaveApply: 'Apply',\n chartPivotHint: 'Charting the pivot: its row groups are the categories and its column groups the series.',\n chartSaveRemove: 'Remove',\n chartSavedEmpty: 'No saved charts yet.',\n chartMaximize: 'Maximize',\n chartRestore: 'Restore',\n chartDock: 'Dock',\n chartDockLabel: 'Dock chart',\n chartPopOut: 'Pop out',\n chartPopOutLabel: 'Pop out chart',\n chartClose: 'Close chart',\n chartResize: 'Resize chart panel',\n chartResizeWindow: 'Resize chart window',\n chartTabs: 'Charts',\n chartRemoveTab: 'Remove {title}',\n chartRemove: 'Remove',\n chartEmptyColumns: 'Charting needs at least one text column (to group by) and one numeric column (to measure).',\n chartEmptyData: 'No data to chart.',\n chartType: 'Type',\n chartDate: 'Date',\n chartGroupBy: 'Group by',\n chartFrom: 'From',\n chartColumns: 'Columns',\n chartSplitBy: 'Split by',\n chartTo: 'To',\n chartRows: 'Rows',\n chartNone: '(none)',\n chartValue: 'Value',\n chartX: 'X',\n chartY: 'Y',\n chartLow: 'Low',\n chartHigh: 'High',\n chartOpen: 'Open',\n chartClosePrice: 'Close',\n chartVolume: 'Volume',\n chartMetric: 'Metric',\n chartTarget: 'Target',\n chartAggregate: 'Aggregate',\n chartReduceSum: 'Sum',\n chartReduceAvg: 'Average',\n chartReduceCount: 'Count',\n chartReduceMin: 'Min',\n chartReduceMax: 'Max',\n chartReduceMedian: 'Median',\n chartReduceP90: '90th percentile',\n chartReduceFirst: 'First',\n chartReduceLast: 'Last',\n chartReduceCountDistinct: 'Distinct count',\n chartBins: 'Bins',\n chartBinsTitle: 'How many bins the sample is split into',\n chartShape: 'Shape',\n chartShapeFunnel: 'Funnel',\n chartShapePyramid: 'Pyramid',\n chartShapeCone: 'Cone',\n chartCandles: 'Candles',\n chartCandlesClassic: 'Classic',\n chartCandlesHollow: 'Hollow',\n chartCandlesHeikinAshi: 'Heikin-Ashi',\n chartIndicators: 'Indicators',\n chartIndVolume: 'Volume',\n chartIndVolumeTitle: 'Volume bars under the price',\n chartIndRsi: 'RSI',\n chartIndRsiTitle: 'Relative strength index, 14 bars',\n chartIndMacd: 'MACD',\n chartIndMacdTitle: 'MACD 12 / 26 / 9',\n chartIndStochastic: 'Stoch',\n chartIndStochasticTitle: 'Stochastic oscillator 14 / 3',\n chartIndAtr: 'ATR',\n chartIndAtrTitle: 'Average true range, 14 bars',\n chartIndObv: 'OBV',\n chartIndObvTitle: 'On-balance volume',\n chartIndSma: 'SMA 20',\n chartIndSmaTitle: '20-bar simple moving average on the price',\n chartIndEma: 'EMA 20',\n chartIndEmaTitle: '20-bar exponential moving average on the price',\n chartIndBb: 'Bollinger',\n chartIndBbTitle: 'Bollinger bands 20 / 2 on the price',\n chartIndVwap: 'VWAP',\n chartIndVwapTitle: 'Volume-weighted average price on the price',\n chartFormat: 'Format',\n chartFormatNumber: 'Number',\n chartFormatCurrency: 'Currency',\n chartFormatPercent: 'Percent',\n chartStacked: 'Stacked',\n chartStacked100: '100%',\n chartStacked100Title: 'Normalise each category to 100 percent',\n chartHorizontal: 'Horizontal',\n chartHorizontalTitle: 'Bars grow rightwards - suits long category labels',\n chartDonut: 'Donut',\n chartColours: 'Colours',\n chartPaletteTheme: 'Theme',\n chartPaletteOcean: 'Ocean',\n chartPaletteSunset: 'Sunset',\n chartPaletteForest: 'Forest',\n chartPaletteSlate: 'Slate',\n chartLabels: 'Labels',\n chartLogScale: 'Log scale',\n chartLogScaleTitle: 'Logarithmic value axis - flattens wide-range data',\n chartBucket: 'Bucket',\n chartBucketTitle: 'Group the dates by calendar unit: one bar per month instead of one per day',\n chartBucketExact: 'Exact',\n chartBucketDay: 'Day',\n chartBucketWeek: 'Week',\n chartBucketMonth: 'Month',\n chartBucketQuarter: 'Quarter',\n chartBucketYear: 'Year',\n chartDateAxis: 'Date axis',\n chartDateAxisTitle: 'Space points by actual date - real time ticks and proportional gaps',\n chartGroupCompare: 'Compare',\n chartGroupPartOfWhole: 'Part of a whole',\n chartGroupFlow: 'Flow',\n chartGroupDistribution: 'Distribution',\n chartGroupSingleValue: 'Single value',\n chartGroupOverTime: 'Over time',\n chartTypeBar: 'Bar',\n chartTypeLine: 'Line',\n chartTypeArea: 'Area',\n chartTypeLollipop: 'Lollipop',\n chartTypePareto: 'Pareto',\n chartTypeRangeBar: 'Range bar',\n chartTypeRangeArea: 'Range area',\n chartTypeDumbbell: 'Dumbbell',\n chartTypeRadialColumn: 'Radial column',\n chartTypeRadialBar: 'Radial bar',\n chartTypeNightingale: 'Nightingale',\n chartTypePie: 'Pie',\n chartTypeTreemap: 'Tree map',\n chartTypeSunburst: 'Sunburst',\n chartTypeFunnel: 'Funnel',\n chartTypeWaterfall: 'Waterfall',\n chartTypeSankey: 'Sankey',\n chartTypeChord: 'Chord',\n chartTypeRadar: 'Radar',\n chartTypeHeatmap: 'Heat map',\n chartTypeScatter: 'Scatter',\n chartTypeBoxplot: 'Box plot',\n chartTypeHistogram: 'Histogram',\n chartTypeGauge: 'Gauge',\n chartTypeBullet: 'Bullet',\n chartTypeCalendar: 'Calendar',\n chartTypeStream: 'Stream',\n chartTypeCandlestick: 'Candlestick',\n chartTypeOhlc: 'OHLC bars',\n chartIssueHeatmap: 'Heat map needs a Split by column for its rows.',\n chartIssueSankey: 'Sankey needs a Split by column: Group by is the source, Split by the target.',\n chartIssueRadar: 'Radar needs at least 3 groups.',\n chartIssueFunnel: 'Funnel needs at least 2 stages.',\n chartIssueChord: 'Chord needs a Split by column: Group by and Split by are the two ends of each flow.',\n chartIssueStream: 'Stream needs a Split by column: each split becomes a layer.',\n chartIssueSecondMeasure: 'Pick a second measure for the high end of the range.',\n chartIssueOhlcDate: 'Candlesticks need a date column.',\n chartIssueOhlcColumns: 'Pick the Open, High, Low and Close columns.',\n chartBuilderTitle: 'Chart builder',\n chartBuilderTabType: 'Type',\n chartBuilderTabData: 'Data',\n chartBuilderTabFormat: 'Format',\n chartBuilderLinked: 'Linked to the grid',\n chartBuilderFrozenAt: 'Frozen at {time}; edits, filters and new rows no longer change it.',\n chartBuilderFollows: \"The chart follows the grid's rows, filters and edits.\",\n chartBuilderTitleField: 'Title',\n chartBuilderSubtitle: 'Subtitle',\n chartBuilderCaption: 'Caption',\n chartBuilderLegend: 'Legend',\n chartLegendBottom: 'Bottom',\n chartLegendTop: 'Top',\n chartLegendLeft: 'Left',\n chartLegendRight: 'Right',\n chartLegendHidden: 'Hidden',\n chartBuilderDataLabels: 'Data labels',\n chartBuilderPanelSetting: 'Panel setting',\n chartLabelsTop: 'Top',\n chartLabelsOutside: 'Outside',\n chartLabelsInside: 'Inside',\n chartLabelsCenter: 'Center',\n chartLabelsHidden: 'Hidden',\n chartBuilderSeriesLabels: 'Series labels',\n chartBuilderCrosshairLabels: 'Crosshair labels',\n chartBuilderCompactBelow: 'Compact under',\n chartBuilderCompactBelowTitle: 'Below this width in px the chart drops its series and data labels, turns the category labels vertical and hides the legend',\n chartBuilderValueAxis: 'Value axis',\n chartBuilderRightAxis: 'Right axis',\n chartBuilderCategoryAxis: 'Category axis',\n chartBuilderMin: 'Min',\n chartBuilderMax: 'Max',\n chartBuilderAuto: 'auto',\n chartBuilderOff: 'off',\n chartBuilderGridLines: 'Grid lines',\n chartBuilderAxisLabels: 'Labels',\n chartBuilderLabelsAuto: 'Auto',\n chartBuilderLabelsHorizontal: 'Horizontal',\n chartBuilderLabelsTilted: 'Tilted',\n chartBuilderLabelsVertical: 'Vertical',\n chartBuilderSeries: 'Series',\n chartBuilderColor: 'Color',\n chartBuilderSeriesType: 'Type',\n chartBuilderAxis: 'Axis',\n chartBuilderMarker: 'Marker',\n chartBuilderWidth: 'Width',\n chartBuilderStack: 'Stack',\n chartBuilderStackPlaceholder: 'own',\n chartBuilderSeriesColorLabel: '{series} colour',\n chartBuilderSeriesTypeLabel: '{series} type',\n chartBuilderSeriesAxisLabel: '{series} axis',\n chartBuilderSeriesMarkerLabel: '{series} marker',\n chartBuilderSeriesWidthLabel: '{series} line width',\n chartBuilderSeriesStackLabel: '{series} stack group',\n chartBuilderChartType: 'Chart',\n chartBuilderBar: 'Bar',\n chartBuilderLine: 'Line',\n chartBuilderArea: 'Area',\n chartBuilderLeft: 'Left',\n chartBuilderRight: 'Right',\n chartBuilderStyle: 'Style',\n chartBuilderFontSize: 'Font size',\n chartBuilderFontFamily: 'Font',\n chartBuilderBackground: 'Background',\n chartBuilderTextColor: 'Text',\n chartBuilderResetFormat: 'Reset format',\n}\n```\n\n### `function resolveChartPanelMessages`\n\nMerge a consumer's `localization.text` over the English defaults. The map\nusually carries the chrome keys too; only the chart panel keys are read.\n\n```ts\nexport function resolveChartPanelMessages(overrides?: Partial<GridChartPanelMessages> | null): GridChartPanelMessages {\n return resolveMessages(defaultChartPanelMessages, overrides)\n}\n```\n\n### `function chartPanelMessage`\n\nFill `{name}` placeholders in a message.\n\n```ts\nexport function chartPanelMessage(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{(\\w+)\\}/g, (_, k: string) => (k in values ? String(values[k]) : `{${k}}`))\n}\n```\n"
7912
+ "markdown": "# `@svgrid/grid` · `chart-panel-messages.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-panel-messages.ts`.\n\n### `type GridChartPanelMessages`\n\nEvery localizable chart panel and builder string.\n\n```ts\nexport type GridChartPanelMessages = {\n // Panel head and actions\n chartPanelTitle: string\n chartClearFilter: string\n chartExport: string\n chartExportLabel: string\n chartExportPng: string\n chartExportSvg: string\n chartExportPdf: string\n chartExportCsv: string\n chartExportCopy: string\n chartExportPrint: string\n chartExportDescribe: string\n chartAi: string\n chartAiLabel: string\n chartAiPlaceholder: string\n chartAiRun: string\n chartAiThinking: string\n chartAiExplain: string\n chartAiExplainTitle: string\n chartAiNoChart: string\n chartAiNoExplanation: string\n chartAiFailed: string\n chartBuild: string\n chartBuildLabel: string\n chartBuildTitle: string\n chartLinkBack: string\n chartUnlink: string\n chartLinkedTitle: string\n chartUnlinkedTitle: string\n chartAdd: string\n chartSave: string\n chartSaveLabel: string\n chartSavedTitle: string\n chartSaveName: string\n chartSaveNamePlaceholder: string\n chartSaveApply: string\n /** The pickers' note in pivot mode, where the pivot on screen is the chart. */\n chartPivotHint: string\n chartSaveRemove: string\n chartSavedEmpty: string\n chartMaximize: string\n chartRestore: string\n chartDock: string\n chartDockLabel: string\n chartPopOut: string\n chartPopOutLabel: string\n chartClose: string\n chartResize: string\n chartResizeWindow: string\n chartTabs: string\n chartRemoveTab: string\n chartRemove: string\n chartEmptyColumns: string\n chartEmptyData: string\n // Pickers\n chartType: string\n chartDate: string\n chartGroupBy: string\n chartFrom: string\n chartColumns: string\n chartSplitBy: string\n chartTo: string\n chartRows: string\n chartNone: string\n chartValue: string\n chartX: string\n chartY: string\n chartLow: string\n chartHigh: string\n chartOpen: string\n chartClosePrice: string\n chartVolume: string\n chartMetric: string\n chartTarget: string\n chartAggregate: string\n chartReduceSum: string\n chartReduceAvg: string\n chartReduceCount: string\n chartReduceMin: string\n chartReduceMax: string\n chartReduceMedian: string\n chartReduceP90: string\n chartReduceFirst: string\n chartReduceLast: string\n chartReduceCountDistinct: string\n chartBins: string\n chartBinsTitle: string\n chartShape: string\n chartShapeFunnel: string\n chartShapePyramid: string\n chartShapeCone: string\n chartCandles: string\n chartCandlesClassic: string\n chartCandlesHollow: string\n chartCandlesHeikinAshi: string\n chartIndicators: string\n chartIndVolume: string\n chartIndVolumeTitle: string\n chartIndRsi: string\n chartIndRsiTitle: string\n chartIndMacd: string\n chartIndMacdTitle: string\n chartIndStochastic: string\n chartIndStochasticTitle: string\n chartIndAtr: string\n chartIndAtrTitle: string\n chartIndObv: string\n chartIndObvTitle: string\n chartIndSma: string\n chartIndSmaTitle: string\n chartIndEma: string\n chartIndEmaTitle: string\n chartIndBb: string\n chartIndBbTitle: string\n chartIndVwap: string\n chartIndVwapTitle: string\n chartFormat: string\n chartFormatNumber: string\n chartFormatCurrency: string\n chartFormatPercent: string\n chartStacked: string\n chartStacked100: string\n chartStacked100Title: string\n chartHorizontal: string\n chartHorizontalTitle: string\n chartDonut: string\n chartColours: string\n chartPaletteTheme: string\n chartPaletteOcean: string\n chartPaletteSunset: string\n chartPaletteForest: string\n chartPaletteSlate: string\n chartLabels: string\n chartLogScale: string\n chartLogScaleTitle: string\n chartBucket: string\n chartBucketTitle: string\n chartBucketExact: string\n chartBucketDay: string\n chartBucketWeek: string\n chartBucketMonth: string\n chartBucketQuarter: string\n chartBucketYear: string\n chartDateAxis: string\n chartDateAxisTitle: string\n // Type names and their groups\n chartGroupCompare: string\n chartGroupPartOfWhole: string\n chartGroupFlow: string\n chartGroupDistribution: string\n chartGroupSingleValue: string\n chartGroupOverTime: string\n chartTypeBar: string\n chartTypeLine: string\n chartTypeArea: string\n chartTypeLollipop: string\n chartTypePareto: string\n chartTypeRangeBar: string\n chartTypeRangeArea: string\n chartTypeDumbbell: string\n chartTypeRadialColumn: string\n chartTypeRadialBar: string\n chartTypeNightingale: string\n chartTypePie: string\n chartTypeTreemap: string\n chartTypeSunburst: string\n chartTypeFunnel: string\n chartTypeWaterfall: string\n chartTypeSankey: string\n chartTypeChord: string\n chartTypeRadar: string\n chartTypeHeatmap: string\n chartTypeScatter: string\n chartTypeBoxplot: string\n chartTypeHistogram: string\n chartTypeGauge: string\n chartTypeBullet: string\n chartTypeCalendar: string\n chartTypeStream: string\n chartTypeCandlestick: string\n chartTypeOhlc: string\n // Why the chosen type cannot draw yet\n chartIssueHeatmap: string\n chartIssueSankey: string\n chartIssueRadar: string\n chartIssueFunnel: string\n chartIssueChord: string\n chartIssueStream: string\n chartIssueSecondMeasure: string\n chartIssueOhlcDate: string\n chartIssueOhlcColumns: string\n // Builder\n chartBuilderTitle: string\n chartBuilderTabType: string\n chartBuilderTabData: string\n chartBuilderTabFormat: string\n chartBuilderLinked: string\n chartBuilderFrozenAt: string\n chartBuilderFollows: string\n chartBuilderTitleField: string\n chartBuilderSubtitle: string\n chartBuilderCaption: string\n chartBuilderLegend: string\n chartLegendBottom: string\n chartLegendTop: string\n chartLegendLeft: string\n chartLegendRight: string\n chartLegendHidden: string\n chartBuilderDataLabels: string\n chartBuilderPanelSetting: string\n chartLabelsTop: string\n chartLabelsOutside: string\n chartLabelsInside: string\n chartLabelsCenter: string\n chartLabelsHidden: string\n chartBuilderSeriesLabels: string\n chartBuilderCrosshairLabels: string\n chartBuilderCompactBelow: string\n chartBuilderCompactBelowTitle: string\n chartBuilderValueAxis: string\n chartBuilderRightAxis: string\n chartBuilderCategoryAxis: string\n chartBuilderMin: string\n chartBuilderMax: string\n chartBuilderAuto: string\n chartBuilderOff: string\n chartBuilderGridLines: string\n chartBuilderAxisLabels: string\n chartBuilderLabelsAuto: string\n chartBuilderLabelsHorizontal: string\n chartBuilderLabelsTilted: string\n chartBuilderLabelsVertical: string\n chartBuilderSeries: string\n chartBuilderColor: string\n chartBuilderSeriesType: string\n chartBuilderAxis: string\n chartBuilderMarker: string\n chartBuilderWidth: string\n chartBuilderStack: string\n chartBuilderStackPlaceholder: string\n chartBuilderSeriesColorLabel: string\n chartBuilderSeriesTypeLabel: string\n chartBuilderSeriesAxisLabel: string\n chartBuilderSeriesMarkerLabel: string\n chartBuilderSeriesWidthLabel: string\n chartBuilderSeriesStackLabel: string\n chartBuilderChartType: string\n chartBuilderBar: string\n chartBuilderLine: string\n chartBuilderArea: string\n chartBuilderLeft: string\n chartBuilderRight: string\n chartBuilderStyle: string\n chartBuilderFontSize: string\n chartBuilderFontFamily: string\n chartBuilderBackground: string\n chartBuilderTextColor: string\n chartBuilderResetFormat: string\n}\n```\n\n### `const defaultChartPanelMessages`\n\nEnglish defaults: the literal strings the panel and the builder shipped with.\n\n```ts\nexport const defaultChartPanelMessages: GridChartPanelMessages = {\n chartPanelTitle: 'Chart',\n chartClearFilter: 'Clear filter',\n chartExport: 'Export',\n chartExportLabel: 'Export chart',\n chartExportPng: 'PNG image',\n chartExportSvg: 'SVG vector',\n chartExportPdf: 'PDF document',\n chartExportCsv: 'CSV data',\n chartExportCopy: 'Copy to clipboard',\n chartExportPrint: 'Print',\n chartExportDescribe: 'Describe chart',\n chartAi: 'AI',\n chartAiLabel: 'Chart with AI',\n chartAiPlaceholder: 'Describe a chart, e.g. revenue by region stacked by product',\n chartAiRun: 'Chart it',\n chartAiThinking: 'Thinking...',\n chartAiExplain: 'Explain',\n chartAiExplainTitle: 'Explain this chart in plain words',\n chartAiNoChart: \"Couldn't build a chart from that request.\",\n chartAiNoExplanation: \"Couldn't explain this chart.\",\n chartAiFailed: 'Something went wrong.',\n chartBuild: 'Build',\n chartBuildLabel: 'Open the chart builder',\n chartBuildTitle: 'Chart builder: type gallery, data and format',\n chartLinkBack: 'Link the chart back to the grid',\n chartUnlink: 'Unlink the chart from the grid',\n chartLinkedTitle: \"Linked: the chart follows the grid's rows. Click to freeze it.\",\n chartUnlinkedTitle: 'Unlinked: the chart keeps the data it has. Click to follow the grid again.',\n chartAdd: 'Add chart',\n chartSave: 'Save',\n chartSaveLabel: 'Saved charts',\n chartSavedTitle: 'Saved charts',\n chartSaveName: 'Save this chart as',\n chartSaveNamePlaceholder: 'Name',\n chartSaveApply: 'Apply',\n chartPivotHint: 'Charting the pivot: its row groups are the categories and its column groups the series.',\n chartSaveRemove: 'Remove',\n chartSavedEmpty: 'No saved charts yet.',\n chartMaximize: 'Maximize',\n chartRestore: 'Restore',\n chartDock: 'Dock',\n chartDockLabel: 'Dock chart',\n chartPopOut: 'Pop out',\n chartPopOutLabel: 'Pop out chart',\n chartClose: 'Close chart',\n chartResize: 'Resize chart panel',\n chartResizeWindow: 'Resize chart window',\n chartTabs: 'Charts',\n chartRemoveTab: 'Remove {title}',\n chartRemove: 'Remove',\n chartEmptyColumns: 'Charting needs at least one text column (to group by) and one numeric column (to measure).',\n chartEmptyData: 'No data to chart.',\n chartType: 'Type',\n chartDate: 'Date',\n chartGroupBy: 'Group by',\n chartFrom: 'From',\n chartColumns: 'Columns',\n chartSplitBy: 'Split by',\n chartTo: 'To',\n chartRows: 'Rows',\n chartNone: '(none)',\n chartValue: 'Value',\n chartX: 'X',\n chartY: 'Y',\n chartLow: 'Low',\n chartHigh: 'High',\n chartOpen: 'Open',\n chartClosePrice: 'Close',\n chartVolume: 'Volume',\n chartMetric: 'Metric',\n chartTarget: 'Target',\n chartAggregate: 'Aggregate',\n chartReduceSum: 'Sum',\n chartReduceAvg: 'Average',\n chartReduceCount: 'Count',\n chartReduceMin: 'Min',\n chartReduceMax: 'Max',\n chartReduceMedian: 'Median',\n chartReduceP90: '90th percentile',\n chartReduceFirst: 'First',\n chartReduceLast: 'Last',\n chartReduceCountDistinct: 'Distinct count',\n chartBins: 'Bins',\n chartBinsTitle: 'How many bins the sample is split into',\n chartShape: 'Shape',\n chartShapeFunnel: 'Funnel',\n chartShapePyramid: 'Pyramid',\n chartShapeCone: 'Cone',\n chartCandles: 'Candles',\n chartCandlesClassic: 'Classic',\n chartCandlesHollow: 'Hollow',\n chartCandlesHeikinAshi: 'Heikin-Ashi',\n chartIndicators: 'Indicators',\n chartIndVolume: 'Volume',\n chartIndVolumeTitle: 'Volume bars under the price',\n chartIndRsi: 'RSI',\n chartIndRsiTitle: 'Relative strength index, 14 bars',\n chartIndMacd: 'MACD',\n chartIndMacdTitle: 'MACD 12 / 26 / 9',\n chartIndStochastic: 'Stoch',\n chartIndStochasticTitle: 'Stochastic oscillator 14 / 3',\n chartIndAtr: 'ATR',\n chartIndAtrTitle: 'Average true range, 14 bars',\n chartIndObv: 'OBV',\n chartIndObvTitle: 'On-balance volume',\n chartIndSma: 'SMA 20',\n chartIndSmaTitle: '20-bar simple moving average on the price',\n chartIndEma: 'EMA 20',\n chartIndEmaTitle: '20-bar exponential moving average on the price',\n chartIndBb: 'Bollinger',\n chartIndBbTitle: 'Bollinger bands 20 / 2 on the price',\n chartIndVwap: 'VWAP',\n chartIndVwapTitle: 'Volume-weighted average price on the price',\n chartFormat: 'Format',\n chartFormatNumber: 'Number',\n chartFormatCurrency: 'Currency',\n chartFormatPercent: 'Percent',\n chartStacked: 'Stacked',\n chartStacked100: '100%',\n chartStacked100Title: 'Normalise each category to 100 percent',\n chartHorizontal: 'Horizontal',\n chartHorizontalTitle: 'Bars grow rightwards - suits long category labels',\n chartDonut: 'Donut',\n chartColours: 'Colours',\n chartPaletteTheme: 'Theme',\n chartPaletteOcean: 'Ocean',\n chartPaletteSunset: 'Sunset',\n chartPaletteForest: 'Forest',\n chartPaletteSlate: 'Slate',\n chartLabels: 'Labels',\n chartLogScale: 'Log scale',\n chartLogScaleTitle: 'Logarithmic value axis - flattens wide-range data',\n chartBucket: 'Bucket',\n chartBucketTitle: 'Group the dates by calendar unit: one bar per month instead of one per day',\n chartBucketExact: 'Exact',\n chartBucketDay: 'Day',\n chartBucketWeek: 'Week',\n chartBucketMonth: 'Month',\n chartBucketQuarter: 'Quarter',\n chartBucketYear: 'Year',\n chartDateAxis: 'Date axis',\n chartDateAxisTitle: 'Space points by actual date - real time ticks and proportional gaps',\n chartGroupCompare: 'Compare',\n chartGroupPartOfWhole: 'Part of a whole',\n chartGroupFlow: 'Flow',\n chartGroupDistribution: 'Distribution',\n chartGroupSingleValue: 'Single value',\n chartGroupOverTime: 'Over time',\n chartTypeBar: 'Bar',\n chartTypeLine: 'Line',\n chartTypeArea: 'Area',\n chartTypeLollipop: 'Lollipop',\n chartTypePareto: 'Pareto',\n chartTypeRangeBar: 'Range bar',\n chartTypeRangeArea: 'Range area',\n chartTypeDumbbell: 'Dumbbell',\n chartTypeRadialColumn: 'Radial column',\n chartTypeRadialBar: 'Radial bar',\n chartTypeNightingale: 'Nightingale',\n chartTypePie: 'Pie',\n chartTypeTreemap: 'Tree map',\n chartTypeSunburst: 'Sunburst',\n chartTypeFunnel: 'Funnel',\n chartTypeWaterfall: 'Waterfall',\n chartTypeSankey: 'Sankey',\n chartTypeChord: 'Chord',\n chartTypeRadar: 'Radar',\n chartTypeHeatmap: 'Heat map',\n chartTypeScatter: 'Scatter',\n chartTypeBoxplot: 'Box plot',\n chartTypeHistogram: 'Histogram',\n chartTypeGauge: 'Gauge',\n chartTypeBullet: 'Bullet',\n chartTypeCalendar: 'Calendar',\n chartTypeStream: 'Stream',\n chartTypeCandlestick: 'Candlestick',\n chartTypeOhlc: 'OHLC bars',\n chartIssueHeatmap: 'Heat map needs a Split by column for its rows.',\n chartIssueSankey: 'Sankey needs a Split by column: Group by is the source, Split by the target.',\n chartIssueRadar: 'Radar needs at least 3 groups.',\n chartIssueFunnel: 'Funnel needs at least 2 stages.',\n chartIssueChord: 'Chord needs a Split by column: Group by and Split by are the two ends of each flow.',\n chartIssueStream: 'Stream needs a Split by column: each split becomes a layer.',\n chartIssueSecondMeasure: 'Pick a second measure for the high end of the range.',\n chartIssueOhlcDate: 'Candlesticks need a date column.',\n chartIssueOhlcColumns: 'Pick the Open, High, Low and Close columns.',\n chartBuilderTitle: 'Chart builder',\n chartBuilderTabType: 'Type',\n chartBuilderTabData: 'Data',\n chartBuilderTabFormat: 'Format',\n chartBuilderLinked: 'Linked to the grid',\n chartBuilderFrozenAt: 'Frozen at {time}; edits, filters and new rows no longer change it.',\n chartBuilderFollows: \"The chart follows the grid's rows, filters and edits.\",\n chartBuilderTitleField: 'Title',\n chartBuilderSubtitle: 'Subtitle',\n chartBuilderCaption: 'Caption',\n chartBuilderLegend: 'Legend',\n chartLegendBottom: 'Bottom',\n chartLegendTop: 'Top',\n chartLegendLeft: 'Left',\n chartLegendRight: 'Right',\n chartLegendHidden: 'Hidden',\n chartBuilderDataLabels: 'Data labels',\n chartBuilderPanelSetting: 'Panel setting',\n chartLabelsTop: 'Top',\n chartLabelsOutside: 'Outside',\n chartLabelsInside: 'Inside',\n chartLabelsCenter: 'Center',\n chartLabelsHidden: 'Hidden',\n chartBuilderSeriesLabels: 'Series labels',\n chartBuilderCrosshairLabels: 'Crosshair labels',\n chartBuilderCompactBelow: 'Compact under',\n chartBuilderCompactBelowTitle: 'Below this width in px the chart drops its series and data labels, turns the category labels vertical and hides the legend',\n chartBuilderValueAxis: 'Value axis',\n chartBuilderRightAxis: 'Right axis',\n chartBuilderCategoryAxis: 'Category axis',\n chartBuilderMin: 'Min',\n chartBuilderMax: 'Max',\n chartBuilderAuto: 'auto',\n chartBuilderOff: 'off',\n chartBuilderGridLines: 'Grid lines',\n chartBuilderAxisLabels: 'Labels',\n chartBuilderLabelsAuto: 'Auto',\n chartBuilderLabelsHorizontal: 'Horizontal',\n chartBuilderLabelsTilted: 'Tilted',\n chartBuilderLabelsVertical: 'Vertical',\n chartBuilderSeries: 'Series',\n chartBuilderColor: 'Color',\n chartBuilderSeriesType: 'Type',\n chartBuilderAxis: 'Axis',\n chartBuilderMarker: 'Marker',\n chartBuilderWidth: 'Width',\n chartBuilderStack: 'Stack',\n chartBuilderStackPlaceholder: 'own',\n chartBuilderSeriesColorLabel: '{series} colour',\n chartBuilderSeriesTypeLabel: '{series} type',\n chartBuilderSeriesAxisLabel: '{series} axis',\n chartBuilderSeriesMarkerLabel: '{series} marker',\n chartBuilderSeriesWidthLabel: '{series} line width',\n chartBuilderSeriesStackLabel: '{series} stack group',\n chartBuilderChartType: 'Chart',\n chartBuilderBar: 'Bar',\n chartBuilderLine: 'Line',\n chartBuilderArea: 'Area',\n chartBuilderLeft: 'Left',\n chartBuilderRight: 'Right',\n chartBuilderStyle: 'Style',\n chartBuilderFontSize: 'Font size',\n chartBuilderFontFamily: 'Font',\n chartBuilderBackground: 'Background',\n chartBuilderTextColor: 'Text',\n chartBuilderResetFormat: 'Reset format',\n}\n```\n\n### `function resolveChartPanelMessages`\n\nMerge a consumer's `localization.text` over the English defaults. The map\nusually carries the chrome keys too; only the chart panel keys are read.\n\n```ts\nexport function resolveChartPanelMessages(overrides?: Partial<GridChartPanelMessages> | null): GridChartPanelMessages\n```\n\n### `function chartPanelMessage`\n\nFill `{name}` placeholders in a message.\n\n```ts\nexport function chartPanelMessage(template: string, values: Record<string, string | number>): string\n```\n"
7842
7913
  },
7843
7914
  {
7844
7915
  "slug": "reference/auto/svgrid-grid-chart-pivot",
7845
7916
  "path": "docs/reference/auto/svgrid-grid-chart-pivot.md",
7846
7917
  "title": "@svgrid/grid · chart-pivot.ts",
7847
7918
  "section": "API reference",
7848
- "markdown": "# `@svgrid/grid` · `chart-pivot.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-pivot.ts`.\n\n### `type PivotResultLike`\n\nWhat {@link pivotResultToChartSpec} reads: the engine's rows and column tree, loosely typed so either package's result fits.\n\n```ts\nexport type PivotResultLike = {\n rows: ReadonlyArray<Record<string, unknown>>\n columns: ReadonlyArray<unknown>\n}\n```\n\n### `type PivotResultChartOptions`\n\nOptions for {@link pivotResultToChartSpec}.\n\n```ts\nexport type PivotResultChartOptions = {\n /** Chart type. Default `'bar'`. A type that reads rows directly (scatter, gauge, box plot, histogram, ranges, bullet, candles) cannot be built from a pivot; see {@link pivotChartType}. */\n type?: ChartType\n /** Stack the series. Default false. */\n stacked?: boolean\n /** Stack to 100%. Implies `stacked`. */\n stacked100?: boolean\n /** Include the grand-total column / row as a series / category. Default false. */\n includeTotals?: boolean\n /** Cap the number of categories (row leaves) charted. */\n maxCategories?: number\n /**\n * The measure's cell format, carried to the chart as `valueFormat` (with\n * `currency` and `locale`), so a cell the table shows as \"$469,662\" charts\n * as \"$470k\" on the axis and \"$469,662\" in the tooltip rather than \"470k\".\n * With several measures in different formats, pass none.\n */\n format?: CellFormatConfig\n /**\n * The layout's measures, each with its cell `format`, when the caller has\n * them rather than one format: used as `format` when they agree, ignored\n * when a layout mixes a currency and a count (a \"$\" on the count would be\n * wrong).\n */\n measures?: ReadonlyArray<{ format?: unknown }>\n /** Name the value axis. Default: the measure's label when the layout has one measure, nothing otherwise; `null` for none. */\n yAxisTitle?: string | null\n /** Series colours, when the caller has a palette. */\n palette?: string[]\n}\n```\n\n### `function pivotChartType`\n\nThe type a pivot chart can draw: the one asked for, or a bar chart when that type cannot be built from a pivot.\n\n```ts\nexport function pivotChartType(type: ChartType | undefined): ChartType {\n return !type || UNSHAPED.has(type) ? 'bar' : type\n}\n```\n\n### `function pivotFilterColumn`\n\nThe grid column a click on a pivot chart filters: the innermost row\ndimension, when the grid has a column for that field. A category of the\nchart is one value of it, so a value filter there narrows the source rows\nand the pivot with them.\n\n```ts\nexport function pivotFilterColumn(\n rowFields: ReadonlyArray<string>,\n columns: ReadonlyArray<{ id: string }>,\n fieldOf: (id: string) => string | undefined,\n): string | null {\n const field = rowFields[rowFields.length - 1]\n return (field && columns.find((c) => fieldOf(c.id) === field)?.id) || null\n}\n```\n\n### `function bucketsToChartSpec`\n\nServer aggregates as a spec: the grid panel's `charting.getAggregate` hands\nback `{ category, series?, value }` buckets and this lays them out as one\nseries per distinct `series` (or a single one), categories in first-seen\norder, a missing cell as 0.\n\n```ts\nexport function bucketsToChartSpec(\n buckets: ReadonlyArray<{ category: string; series?: string; value: number }>,\n type: ChartType,\n hasSeries: boolean,\n): ChartSpec {\n const cats: string[] = []\n const catIdx = new Map<string, number>()\n const seriesMap = new Map<string, number[]>()\n for (const b of buckets) {\n let ci = catIdx.get(b.category)\n if (ci === undefined) {\n ci = cats.length\n catIdx.set(b.category, ci)\n cats.push(b.category)\n }\n const key = hasSeries ? (b.series ?? '') : 'value'\n let arr = seriesMap.get(key)\n if (!arr) {\n arr = []\n seriesMap.set(key, arr)\n }\n arr[ci] = (arr[ci] ?? 0) + b.value\n }\n return {\n type,\n categories: cats,\n series: [...seriesMap.entries()].map(([label, values]) => ({ label, values: cats.map((_, i) => values[i] ?? 0) })),\n }\n}\n```\n\n### `function pivotResultToChartSpec`\n\nA computed pivot as a chart spec. Row leaves become the categories (nested\nrows a grouped axis), column leaves the series, totals are left out unless\nasked for, the measure's format and name come along, and an empty cell is\na gap.\n\n```ts\nexport function pivotResultToChartSpec(result: PivotResultLike, opts: PivotResultChartOptions = {}): ChartSpec {\n const type = pivotChartType(opts.type)\n\n // Category rows: the row-axis leaves. Fall back to the grand-total (single\n // \"All\") row when no row dims are configured, then to every row.\n let catRows = result.rows.filter((r) => r.__pivotKind === 'leaf')\n if (!catRows.length) catRows = result.rows.filter((r) => r.__pivotKind === 'grandTotal')\n if (!catRows.length) catRows = result.rows.slice()\n if (opts.maxCategories && catRows.length > opts.maxCategories) catRows = catRows.slice(0, opts.maxCategories)\n // Categories are the leaf's OWN label; when rows are nested, emit a parent\n // tier (categoryGroups) so the axis reads \"Americas | Canada, USA ...\" as a\n // grouped axis rather than colliding on a bare repeated leaf label.\n const byId = new Map(result.rows.map((r) => [r.__pivotId as string, r]))\n const ownLabel = (r: Record<string, unknown>) => String(r.__pivotLabel ?? '').trim() || '(blank)'\n const categories = catRows.map(ownLabel)\n const parentOf = (r: Record<string, unknown>) => (r.__pivotParentId ? byId.get(r.__pivotParentId as string) : undefined)\n const nested = catRows.length > 0 && catRows.every((r) => parentOf(r) !== undefined)\n let categoryGroups: Array<{ label: string; span: number }> | undefined\n if (nested) {\n categoryGroups = []\n let prevId: unknown\n for (const r of catRows) {\n const pid = r.__pivotParentId\n const last = categoryGroups[categoryGroups.length - 1]\n if (last && pid === prevId) last.span += 1\n else {\n categoryGroups.push({ label: ownLabel(parentOf(r)!), span: 1 })\n prevId = pid\n }\n }\n }\n\n // Collect the leaf value columns, carrying the accumulated column-group path\n // so a series can be labelled by its column path (\"Q1\", or \"Q1 · Revenue\").\n type Leaf = { id: string; path: string[]; header: string }\n const leaves: Leaf[] = []\n const walk = (cols: LooseColumn[] | undefined, path: string[]): void => {\n for (const c of cols ?? []) {\n if (!c || c.id === '__pivotRowHeader') continue\n // Skip the grand-total column group (and its leaves) unless asked for.\n if (!opts.includeTotals && typeof c.id === 'string' && c.id.startsWith('pv_group__grand')) continue\n if (Array.isArray(c.columns)) walk(c.columns, [...path, String(c.header ?? '')])\n else if (typeof c.id === 'string') leaves.push({ id: c.id, path, header: String(c.header ?? '') })\n }\n }\n walk(result.columns as LooseColumn[], [])\n\n const filtered = opts.includeTotals ? leaves : leaves.filter((l) => !l.id.includes('__total'))\n const uniqueHeaders = new Set(filtered.map((l) => l.header))\n const series = filtered.map((l) => ({\n label: l.path.length === 0 ? l.header : uniqueHeaders.size > 1 ? [...l.path, l.header].join(' · ') : l.path.join(' · '),\n values: catRows.map((r) => {\n const v = r[l.id]\n // An empty cell (an average over no rows is null) is a gap in the\n // chart, not a zero bar; a sum over no rows is the 0 the engine wrote.\n if (v == null || v === '') return Number.NaN\n return typeof v === 'number' ? v : Number(v)\n }),\n }))\n\n // With one measure the value axis can carry its name; the series are then\n // the column-axis values and say nothing about what is measured.\n const measureLabel = uniqueHeaders.size === 1 && filtered.length ? filtered[0]!.header : ''\n const yAxisTitle = opts.yAxisTitle === undefined ? measureLabel : opts.yAxisTitle\n const formats = (opts.measures ?? []).map((m) => m.format as CellFormatConfig | undefined)\n const agreed = formats[0] && formats.every((f) => f && JSON.stringify(f) === JSON.stringify(formats[0])) ? formats[0] : undefined\n const fmt = chartFormat(opts.format ?? agreed)\n\n return {\n type,\n categories,\n series,\n ...(categoryGroups && categoryGroups.length > 1 ? { categoryGroups } : {}),\n ...(opts.stacked || opts.stacked100 ? { stacked: true } : {}),\n ...(opts.stacked100 ? { stacked100: true } : {}),\n ...(opts.palette ? { palette: opts.palette } : {}),\n ...fmt,\n ...(yAxisTitle ? { yAxis: { ...fmt.yAxis, title: yAxisTitle } } : {}),\n }\n}\n```\n"
7919
+ "markdown": "# `@svgrid/grid` · `chart-pivot.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-pivot.ts`.\n\n### `type PivotResultLike`\n\nWhat {@link pivotResultToChartSpec} reads: the engine's rows and column tree, loosely typed so either package's result fits.\n\n```ts\nexport type PivotResultLike = {\n rows: ReadonlyArray<Record<string, unknown>>\n columns: ReadonlyArray<unknown>\n}\n```\n\n### `type PivotResultChartOptions`\n\nOptions for {@link pivotResultToChartSpec}.\n\n```ts\nexport type PivotResultChartOptions = {\n /** Chart type. Default `'bar'`. A type that reads rows directly (scatter, gauge, box plot, histogram, ranges, bullet, candles) cannot be built from a pivot; see {@link pivotChartType}. */\n type?: ChartType\n /** Stack the series. Default false. */\n stacked?: boolean\n /** Stack to 100%. Implies `stacked`. */\n stacked100?: boolean\n /** Include the grand-total column / row as a series / category. Default false. */\n includeTotals?: boolean\n /** Cap the number of categories (row leaves) charted. */\n maxCategories?: number\n /**\n * The measure's cell format, carried to the chart as `valueFormat` (with\n * `currency` and `locale`), so a cell the table shows as \"$469,662\" charts\n * as \"$470k\" on the axis and \"$469,662\" in the tooltip rather than \"470k\".\n * With several measures in different formats, pass none.\n */\n format?: CellFormatConfig\n /**\n * The layout's measures, each with its cell `format`, when the caller has\n * them rather than one format: used as `format` when they agree, ignored\n * when a layout mixes a currency and a count (a \"$\" on the count would be\n * wrong).\n */\n measures?: ReadonlyArray<{ format?: unknown }>\n /** Name the value axis. Default: the measure's label when the layout has one measure, nothing otherwise; `null` for none. */\n yAxisTitle?: string | null\n /** Series colours, when the caller has a palette. */\n palette?: string[]\n}\n```\n\n### `function pivotChartType`\n\nThe type a pivot chart can draw: the one asked for, or a bar chart when that type cannot be built from a pivot.\n\n```ts\nexport function pivotChartType(type: ChartType | undefined): ChartType\n```\n\n### `function pivotFilterColumn`\n\nThe grid column a click on a pivot chart filters: the innermost row\ndimension, when the grid has a column for that field. A category of the\nchart is one value of it, so a value filter there narrows the source rows\nand the pivot with them.\n\n```ts\nexport function pivotFilterColumn(\n rowFields: ReadonlyArray<string>,\n columns: ReadonlyArray<{ id: string }>,\n fieldOf: (id: string) => string | undefined,\n): string | null\n```\n\n### `function bucketsToChartSpec`\n\nServer aggregates as a spec: the grid panel's `charting.getAggregate` hands\nback `{ category, series?, value }` buckets and this lays them out as one\nseries per distinct `series` (or a single one), categories in first-seen\norder, a missing cell as 0.\n\n```ts\nexport function bucketsToChartSpec(\n buckets: ReadonlyArray<{ category: string; series?: string; value: number }>,\n type: ChartType,\n hasSeries: boolean,\n): ChartSpec\n```\n\n### `function pivotResultToChartSpec`\n\nA computed pivot as a chart spec. Row leaves become the categories (nested\nrows a grouped axis), column leaves the series, totals are left out unless\nasked for, the measure's format and name come along, and an empty cell is\na gap.\n\n```ts\nexport function pivotResultToChartSpec(result: PivotResultLike, opts: PivotResultChartOptions = {}): ChartSpec\n```\n"
7849
7920
  },
7850
7921
  {
7851
7922
  "slug": "reference/auto/svgrid-grid-chart-polar",
7852
7923
  "path": "docs/reference/auto/svgrid-grid-chart-polar.md",
7853
7924
  "title": "@svgrid/grid · chart-polar.ts",
7854
7925
  "section": "API reference",
7855
- "markdown": "# `@svgrid/grid` · `chart-polar.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-polar.ts`.\n\n### `function arcPath`\n\nAn annular sector from angle `a0` to `a1` between radii `r0` and `r1`, as\nan SVG path. `r0 = 0` gives a wedge; a span of a full turn gives a ring.\nExposed so a custom mark can match the built-in polar types exactly.\n\n```ts\nexport function arcPath(cx: number, cy: number, r0: number, r1: number, a0: number, a1: number): string {\n const TAU = Math.PI * 2\n const span = Math.max(0, Math.min(TAU, a1 - a0))\n if (span <= 0 || r1 <= 0) return ''\n const px = (r: number, a: number) => `${round(cx + r * Math.cos(a))},${round(cy + r * Math.sin(a))}`\n if (span >= TAU - 1e-6) {\n // Two half-arcs, because a single arc cannot describe a full circle.\n const outer = `M${px(r1, a0)} A${round(r1)},${round(r1)} 0 1 1 ${px(r1, a0 + Math.PI)} A${round(r1)},${round(r1)} 0 1 1 ${px(r1, a0)} Z`\n if (r0 <= 0) return outer\n return `${outer} M${px(r0, a0)} A${round(r0)},${round(r0)} 0 1 0 ${px(r0, a0 + Math.PI)} A${round(r0)},${round(r0)} 0 1 0 ${px(r0, a0)} Z`\n }\n const large = span > Math.PI ? 1 : 0\n if (r0 <= 0) {\n return `M${round(cx)},${round(cy)} L${px(r1, a0)} A${round(r1)},${round(r1)} 0 ${large} 1 ${px(r1, a1)} Z`\n }\n return (\n `M${px(r1, a0)} A${round(r1)},${round(r1)} 0 ${large} 1 ${px(r1, a1)} ` +\n `L${px(r0, a1)} A${round(r0)},${round(r0)} 0 ${large} 0 ${px(r0, a0)} Z`\n )\n}\n```\n"
7926
+ "markdown": "# `@svgrid/grid` · `chart-polar.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-polar.ts`.\n\n### `function arcPath`\n\nAn annular sector from angle `a0` to `a1` between radii `r0` and `r1`, as\nan SVG path. `r0 = 0` gives a wedge; a span of a full turn gives a ring.\nExposed so a custom mark can match the built-in polar types exactly.\n\n```ts\nexport function arcPath(cx: number, cy: number, r0: number, r1: number, a0: number, a1: number): string\n```\n"
7856
7927
  },
7857
7928
  {
7858
7929
  "slug": "reference/auto/svgrid-grid-chart-samples",
7859
7930
  "path": "docs/reference/auto/svgrid-grid-chart-samples.md",
7860
7931
  "title": "@svgrid/grid · chart-samples.ts",
7861
7932
  "section": "API reference",
7862
- "markdown": "# `@svgrid/grid` · `chart-samples.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-samples.ts`.\n\n### `const CHART_TYPE_LABELS`\n\nThe label a type gallery shows for each type.\n\n```ts\nexport const CHART_TYPE_LABELS: Record<ChartType, string> = {\n bar: 'Bar', line: 'Line', area: 'Area', pie: 'Pie', scatter: 'Scatter', heatmap: 'Heat map', waterfall: 'Waterfall',\n funnel: 'Funnel', radar: 'Radar', calendar: 'Calendar', gauge: 'Gauge', treemap: 'Tree map', sankey: 'Sankey',\n candlestick: 'Candlestick', ohlc: 'OHLC', boxplot: 'Box plot', histogram: 'Histogram', 'range-bar': 'Range bar',\n 'range-area': 'Range area', lollipop: 'Lollipop', dumbbell: 'Dumbbell', pareto: 'Pareto', stream: 'Stream',\n sunburst: 'Sunburst', 'radial-bar': 'Radial bar', 'radial-column': 'Radial column', nightingale: 'Nightingale',\n chord: 'Chord', bullet: 'Bullet',\n}\n```\n\n### `function sampleChartSpec`\n\nA complete, small spec of the given type, drawn from the shared sample\ndataset. Pass a `palette` to colour it like the chart it stands in for.\n\n```ts\nexport function sampleChartSpec(type: ChartType, palette?: string[]): ChartSpec {\n const data = rows()\n const byRegion = rowsToChartSpec(data, { type: 'bar', category: 'region', value: 'revenue' })\n const byRegionChannel = rowsToChartSpec(data, { type: 'bar', category: 'region', value: 'revenue', series: 'channel' })\n const byMonth = rowsToChartSpec(data, { type: 'line', category: 'day', value: 'revenue', bucket: 'month' })\n const byMonthChannel = rowsToChartSpec(data, { type: 'area', category: 'day', value: 'revenue', series: 'channel', bucket: 'month' })\n const ranged = () => rowsToRangeSpec(\n byRegion.categories.map((c, i) => ({ region: c, cost: byRegion.series[0]!.values[i]! * 0.6, revenue: byRegion.series[0]!.values[i]! })),\n { category: 'region', low: 'cost', high: 'revenue' },\n )\n const ohlc = () => {\n const v = byMonth.series[0]!.values\n const bars = v.map((c, i) => { const o = i ? v[i - 1]! : c * 0.95; return { o, c, h: Math.max(o, c) * 1.04, l: Math.min(o, c) * 0.96 } })\n return { categories: byMonth.categories, series: [{ label: 'Revenue', values: v, ohlc: bars }], xType: 'ordinal-time' as const }\n }\n let spec: ChartSpec\n switch (type) {\n case 'line': spec = { ...byMonthChannel, type: 'line' }; break\n case 'area': spec = { ...byMonthChannel, type: 'area', stacked: true }; break\n case 'lollipop': spec = { ...byRegion, type: 'lollipop' }; break\n case 'dumbbell': spec = { ...ranged(), type: 'dumbbell' }; break\n case 'range-bar': spec = ranged(); break\n case 'range-area': spec = { ...byMonth, type: 'range-area', series: [{ label: 'Band', values: byMonth.series[0]!.values.map((v) => v * 1.15), lowValues: byMonth.series[0]!.values.map((v) => v * 0.85) }] }; break\n case 'pareto': spec = { ...rowsToChartSpec(data, { type: 'bar', category: 'channel', value: 'units' }), type: 'pareto' }; break\n case 'radial-column': spec = { ...byRegionChannel, type: 'radial-column', stacked: true }; break\n case 'radial-bar': spec = { ...byRegion, type: 'radial-bar' }; break\n case 'nightingale': spec = { ...byMonth, type: 'nightingale' }; break\n case 'pie': spec = { ...byRegion, type: 'pie', innerRadius: 0.55 }; break\n case 'treemap': spec = { ...byRegionChannel, type: 'treemap', treemap: specToTreemap(byRegionChannel) }; break\n case 'sunburst': spec = { ...byRegionChannel, type: 'sunburst', tree: specToTreemap(byRegionChannel) }; break\n case 'funnel': spec = { type: 'funnel', categories: ['Visits', 'Sign-ups', 'Trials', 'Paid'], series: [{ label: 'Users', values: [12400, 5100, 2300, 880] }] }; break\n case 'waterfall': spec = { type: 'waterfall', categories: ['Start', 'Web', 'Retail', 'Partner', 'Returns', 'End'], series: [{ label: 'P&L', values: [120, 48, 31, 22, -19, 0] }], waterfallTotals: [true, false, false, false, false, true] }; break\n case 'sankey': { const f = specToSankey(byRegionChannel); spec = { ...byRegionChannel, type: 'sankey', sankeyNodes: f.nodes, sankeyLinks: f.links }; break }\n case 'chord': { const f = specToSankey(byRegionChannel); spec = { ...byRegionChannel, type: 'chord', sankeyNodes: f.nodes, sankeyLinks: f.links }; break }\n case 'radar': spec = { ...byRegionChannel, type: 'radar' }; break\n case 'heatmap': spec = { ...byRegionChannel, type: 'heatmap' }; break\n case 'scatter': spec = rowsToScatterSpec(data.slice(0, 80), { x: 'cost', y: 'revenue', series: 'channel', r: 'units' }); break\n case 'boxplot': spec = rowsToBoxSpec(data, { category: 'region', value: 'revenue' }); break\n case 'histogram': spec = rowsToHistogramSpec(data, { value: 'revenue', bins: 10 }); break\n case 'gauge': spec = { type: 'gauge', categories: [], series: [], gaugeValue: 72, gaugeMin: 0, gaugeMax: 100, gaugeTarget: 80, gaugeUnit: '%', gaugeRanges: [{ from: 0, to: 50, color: '#ef4444' }, { from: 50, to: 75, color: '#f59e0b' }, { from: 75, to: 100, color: '#16a34a' }] }; break\n case 'bullet': spec = { type: 'bullet', categories: byRegion.categories, series: [{ label: 'Revenue', values: byRegion.series[0]!.values, targets: byRegion.series[0]!.values.map((v, i) => v * (0.9 + (i % 3) * 0.1)) }] }; break\n case 'calendar': { const daily = rowsToChartSpec(data, { type: 'bar', category: 'day', value: 'units' }); spec = { ...daily, type: 'calendar', calendarValues: specToCalendar(daily) }; break }\n case 'stream': spec = { ...byMonthChannel, type: 'stream', stacked: true, stackOffset: 'wiggle' }; break\n case 'candlestick': spec = { type: 'candlestick', ...ohlc() }; break\n case 'ohlc': spec = { type: 'ohlc', ...ohlc() }; break\n case 'bar':\n default: spec = { ...byRegionChannel, type: 'bar' }\n }\n return palette ? { ...spec, palette } : spec\n}\n```\n\n### `function sampleChartThumb`\n\nA sample spec trimmed for a thumbnail: no titles, no axis labels, small.\n\n```ts\nexport function sampleChartThumb(type: ChartType, palette?: string[], width = 150, height = 92): ChartSpec {\n const s = sampleChartSpec(type, palette)\n return {\n ...s, width, height, title: undefined, yAxisTitle: undefined, xAxisTitle: undefined, referenceLines: undefined,\n xAxis: { ...(s.xAxis ?? {}), labels: false, title: undefined },\n yAxis: { ...(s.yAxis ?? {}), labels: false, title: undefined },\n y2Axis: { ...(s.y2Axis ?? {}), labels: false, title: undefined },\n }\n}\n```\n"
7933
+ "markdown": "# `@svgrid/grid` · `chart-samples.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-samples.ts`.\n\n### `const CHART_TYPE_LABELS`\n\nThe label a type gallery shows for each type.\n\n```ts\nexport const CHART_TYPE_LABELS: Record<ChartType, string> = {\n bar: 'Bar', line: 'Line', area: 'Area', pie: 'Pie', scatter: 'Scatter', heatmap: 'Heat map', waterfall: 'Waterfall',\n funnel: 'Funnel', radar: 'Radar', calendar: 'Calendar', gauge: 'Gauge', treemap: 'Tree map', sankey: 'Sankey',\n candlestick: 'Candlestick', ohlc: 'OHLC', boxplot: 'Box plot', histogram: 'Histogram', 'range-bar': 'Range bar',\n 'range-area': 'Range area', lollipop: 'Lollipop', dumbbell: 'Dumbbell', pareto: 'Pareto', stream: 'Stream',\n sunburst: 'Sunburst', 'radial-bar': 'Radial bar', 'radial-column': 'Radial column', nightingale: 'Nightingale',\n chord: 'Chord', bullet: 'Bullet',\n}\n```\n\n### `function sampleChartSpec`\n\nA complete, small spec of the given type, drawn from the shared sample\ndataset. Pass a `palette` to colour it like the chart it stands in for.\n\n```ts\nexport function sampleChartSpec(type: ChartType, palette?: string[]): ChartSpec\n```\n\n### `function sampleChartThumb`\n\nA sample spec trimmed for a thumbnail: no titles, no axis labels, small.\n\n```ts\nexport function sampleChartThumb(type: ChartType, palette?: string[], width = 150, height = 92): ChartSpec\n```\n"
7863
7934
  },
7864
7935
  {
7865
7936
  "slug": "reference/auto/svgrid-grid-chart-scale",
7866
7937
  "path": "docs/reference/auto/svgrid-grid-chart-scale.md",
7867
7938
  "title": "@svgrid/grid · chart-scale.ts",
7868
7939
  "section": "API reference",
7869
- "markdown": "# `@svgrid/grid` · `chart-scale.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-scale.ts`.\n\n### `const DEFAULT_PALETTE`\n\nSeries colours used when a {@link ChartSeries} sets none, in order.\n\n```ts\nexport const DEFAULT_PALETTE = [\n '#2563eb',\n '#16a34a',\n '#f59e0b',\n '#ef4444',\n '#8b5cf6',\n '#0ea5e9',\n '#ec4899',\n '#14b8a6',\n]\n```\n\n### `function sampleGradient`\n\nSample a hex color from an array of hex stops at fractional position t.\n Linearly interpolates between the two nearest stops in RGB space.\n\n```ts\nexport function sampleGradient(stops: string[], t: number): string {\n if (!stops.length) return '#888'\n const clamped = Math.max(0, Math.min(1, t))\n if (stops.length === 1) return stops[0]!\n const pos = clamped * (stops.length - 1)\n const i = Math.floor(pos)\n const frac = pos - i\n const a = hexToRgb(stops[i]!)\n const b = hexToRgb(stops[Math.min(stops.length - 1, i + 1)]!)\n if (!a || !b) return stops[i] ?? '#888'\n const lerp = (x: number, y: number) => Math.round(x + (y - x) * frac)\n const toHex = (n: number) => n.toString(16).padStart(2, '0')\n return '#' + toHex(lerp(a.r, b.r)) + toHex(lerp(a.g, b.g)) + toHex(lerp(a.b, b.b))\n}\n```\n\n### `function pickContrastText`\n\nPick a black or white text color that has the better contrast against\n the given background. Uses the WCAG relative-luminance heuristic.\n\n```ts\nexport function pickContrastText(bgHex: string): string {\n const rgb = hexToRgb(bgHex)\n if (!rgb) return '#0f172a'\n const lin = (c: number) => {\n const s = c / 255\n return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4)\n }\n const L = 0.2126 * lin(rgb.r) + 0.7152 * lin(rgb.g) + 0.0722 * lin(rgb.b)\n return L > 0.5 ? '#0f172a' : '#ffffff'\n}\n```\n\n### `function niceLogScale`\n\nPick the largest power of 10 that fits at the bottom of [min,max], and\n the smallest that covers the top, then enumerate decade boundaries. Used\n by log-scale axes (yScale: 'log').\n\n```ts\nexport function niceLogScale(min: number, max: number): NiceScale {\n // Only positive values are plottable on a log scale; callers should\n // strip non-positive values before passing them in.\n if (!Number.isFinite(min) || min <= 0) min = 1\n if (!Number.isFinite(max) || max <= min) max = min * 10\n const lo = Math.floor(Math.log10(min))\n const hi = Math.ceil(Math.log10(max))\n const ticks: number[] = []\n for (let p = lo; p <= hi; p += 1) ticks.push(Math.pow(10, p))\n return { min: Math.pow(10, lo), max: Math.pow(10, hi), step: 10, ticks }\n}\n```\n\n### `function niceScale`\n\nRound a [min,max] domain out to nice tick boundaries.\n\n```ts\nexport function niceScale(min: number, max: number, tickCount = 4): NiceScale {\n if (!Number.isFinite(min) || !Number.isFinite(max)) {\n min = 0\n max = 1\n }\n if (min === max) {\n if (min === 0) max = 1\n else {\n min = Math.min(0, min)\n max = Math.max(0, max)\n }\n if (min === max) max = min + 1\n }\n const range = niceNum(max - min, false)\n const step = niceNum(range / Math.max(1, tickCount), true)\n const nMin = Math.floor(min / step) * step\n const nMax = Math.ceil(max / step) * step\n const ticks: number[] = []\n for (let v = nMin; v <= nMax + step * 0.5; v += step) ticks.push(round(v))\n return { min: nMin, max: nMax, step, ticks }\n}\n```\n\n### `function axisScale`\n\nA value-axis domain that honours an axis config on top of the data extent:\na pinned `min` / `max` (hard edges - marks past them are clipped), an exact\n`tickInterval`, a `tickCount`, and `nice: false` for the raw extent with\nevenly spaced ticks. With no config this is exactly {@link niceScale}.\n\n```ts\nexport function axisScale(\n dataMin: number,\n dataMax: number,\n axis: { min?: number; max?: number; nice?: boolean; tickCount?: number; tickInterval?: number } = {},\n): NiceScale {\n let min = axis.min ?? dataMin\n let max = axis.max ?? dataMax\n if (!Number.isFinite(min) || !Number.isFinite(max)) {\n min = Number.isFinite(min) ? min : 0\n max = Number.isFinite(max) ? max : min + 1\n }\n const nice = axis.nice !== false\n const interval = axis.tickInterval\n if (interval && interval > 0 && Number.isFinite(interval)) {\n // An explicit interval is the whole axis: the ends land on multiples of it\n // (unless pinned) and every tick is one interval apart.\n if (nice && axis.min == null) min = Math.floor(min / interval) * interval\n if (nice && axis.max == null) max = Math.ceil(max / interval) * interval\n if (max <= min) max = min + interval\n const ticks: number[] = []\n const first = Math.ceil(min / interval - 1e-9) * interval\n // Cap the count so a tiny interval on a huge domain cannot hang the layout.\n // `+ 0` turns the -0 that `Math.ceil` hands back at the origin into a plain 0.\n for (let v = first, n = 0; v <= max + interval * 1e-6 && n < 1000; v += interval, n += 1) ticks.push(round(v) + 0)\n return { min, max, step: interval, ticks }\n }\n if (nice) {\n const ns = niceScale(min, max, axis.tickCount ?? 4)\n if (axis.min == null && axis.max == null) return ns\n // A pinned end wins over the rounding, and ticks past it go.\n const lo = axis.min ?? ns.min\n const hi = axis.max ?? ns.max\n return { min: lo, max: hi, step: ns.step, ticks: ns.ticks.filter((t) => t >= lo - 1e-9 && t <= hi + 1e-9) }\n }\n if (max <= min) max = min + 1\n const n = Math.max(1, Math.round(axis.tickCount ?? 4))\n const step = (max - min) / n\n const ticks = Array.from({ length: n + 1 }, (_, i) => round(min + step * i))\n return { min, max, step, ticks }\n}\n```\n\n### `function ordinalDateTicks`\n\nTick positions for an ordinal (evenly spaced) date axis, as INDICES into\n`times`.\n\nA time axis can put a tick anywhere, because x is a function of the\ntimestamp. An ordinal axis cannot: x is a function of the index, so a tick\nhas to land on a point that exists. This picks the first point of each\ncalendar unit - day, week, month, year, whichever gets closest to `target`\nticks without going over - so labels sit on real sessions and a weekend or a\nholiday never stretches the spacing.\n\n```ts\nexport function ordinalDateTicks(times: number[], target = 6): number[] {\n if (times.length <= 1) return times.length ? [0] : []\n const keyOf: Record<string, (d: Date) => number | string> = {\n day: (d) => `${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}`,\n // Weeks start on Monday: day 0 of the epoch was a Thursday, so +3 puts\n // the boundary there (+4 put it on Sunday, and weekly ticks sat on Sundays).\n week: (d) => Math.floor((Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) / DAY + 3) / 7),\n month: (d) => `${d.getUTCFullYear()}-${d.getUTCMonth()}`,\n year: (d) => d.getUTCFullYear(),\n }\n let chosen: number[] | null = null\n for (const unit of ['day', 'week', 'month', 'year'] as const) {\n const at: number[] = []\n let prev: number | string | null = null\n for (let i = 0; i < times.length; i += 1) {\n const t = times[i]!\n if (!Number.isFinite(t)) continue\n const k = keyOf[unit]!(new Date(t))\n if (k !== prev) at.push(i)\n prev = k\n }\n chosen = at\n if (at.length <= target * 2) break\n }\n let out = chosen ?? []\n // Even the coarsest unit can be too dense (a decade of yearly points), and a\n // single trading day yields one boundary. Thin, or fall back to plain strides.\n if (out.length > target) {\n const stride = Math.ceil(out.length / target)\n out = out.filter((_, i) => i % stride === 0)\n }\n if (out.length < 2) {\n const stride = Math.max(1, Math.ceil(times.length / target))\n out = times.map((_, i) => i).filter((i) => i % stride === 0)\n }\n return out\n}\n```\n"
7940
+ "markdown": "# `@svgrid/grid` · `chart-scale.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-scale.ts`.\n\n### `const DEFAULT_PALETTE`\n\nSeries colours used when a {@link ChartSeries} sets none, in order.\n\n```ts\nexport const DEFAULT_PALETTE = [\n '#2563eb',\n '#16a34a',\n '#f59e0b',\n '#ef4444',\n '#8b5cf6',\n '#0ea5e9',\n '#ec4899',\n '#14b8a6',\n]\n```\n\n### `function sampleGradient`\n\nSample a hex color from an array of hex stops at fractional position t.\n Linearly interpolates between the two nearest stops in RGB space.\n\n```ts\nexport function sampleGradient(stops: string[], t: number): string\n```\n\n### `function pickContrastText`\n\nPick a black or white text color that has the better contrast against\n the given background. Uses the WCAG relative-luminance heuristic.\n\n```ts\nexport function pickContrastText(bgHex: string): string\n```\n\n### `function niceLogScale`\n\nPick the largest power of 10 that fits at the bottom of [min,max], and\n the smallest that covers the top, then enumerate decade boundaries. Used\n by log-scale axes (yScale: 'log').\n\n```ts\nexport function niceLogScale(min: number, max: number): NiceScale\n```\n\n### `function niceScale`\n\nRound a [min,max] domain out to nice tick boundaries.\n\n```ts\nexport function niceScale(min: number, max: number, tickCount = 4): NiceScale\n```\n\n### `function axisScale`\n\nA value-axis domain that honours an axis config on top of the data extent:\na pinned `min` / `max` (hard edges - marks past them are clipped), an exact\n`tickInterval`, a `tickCount`, and `nice: false` for the raw extent with\nevenly spaced ticks. With no config this is exactly {@link niceScale}.\n\n```ts\nexport function axisScale(\n dataMin: number,\n dataMax: number,\n axis: { min?: number; max?: number; nice?: boolean; tickCount?: number; tickInterval?: number } = {},\n): NiceScale\n```\n\n### `function ordinalDateTicks`\n\nTick positions for an ordinal (evenly spaced) date axis, as INDICES into\n`times`.\n\nA time axis can put a tick anywhere, because x is a function of the\ntimestamp. An ordinal axis cannot: x is a function of the index, so a tick\nhas to land on a point that exists. This picks the first point of each\ncalendar unit - day, week, month, year, whichever gets closest to `target`\nticks without going over - so labels sit on real sessions and a weekend or a\nholiday never stretches the spacing.\n\n```ts\nexport function ordinalDateTicks(times: number[], target = 6): number[]\n```\n"
7870
7941
  },
7871
7942
  {
7872
7943
  "slug": "reference/auto/svgrid-grid-chart-stats",
7873
7944
  "path": "docs/reference/auto/svgrid-grid-chart-stats.md",
7874
7945
  "title": "@svgrid/grid · chart-stats.ts",
7875
7946
  "section": "API reference",
7876
- "markdown": "# `@svgrid/grid` · `chart-stats.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-stats.ts`.\n\n### `function boxStats`\n\nFive-number summary of a raw sample, with the 1.5 IQR whisker rule.\n\nWhiskers stop at the last observation INSIDE the fence rather than at the\nfence itself, which is what makes them read as real data; anything past them\ncomes back in `outliers`. Quartiles use linear interpolation between the two\nneighbouring order statistics.\n\nReturns `null` for an empty sample, so a category with no observations is a\ngap rather than a box drawn at zero.\n\n```ts\nexport function boxStats(sample: ReadonlyArray<number>, whisker = 1.5): BoxStats | null {\n const v = sample.filter((n) => Number.isFinite(n)).slice().sort((a, b) => a - b)\n if (!v.length) return null\n const q = (p: number) => {\n const pos = (v.length - 1) * p\n const lo = Math.floor(pos)\n const hi = Math.ceil(pos)\n return lo === hi ? v[lo]! : v[lo]! + (v[hi]! - v[lo]!) * (pos - lo)\n }\n const q1 = q(0.25)\n const median = q(0.5)\n const q3 = q(0.75)\n const fenceLo = q1 - whisker * (q3 - q1)\n const fenceHi = q3 + whisker * (q3 - q1)\n const inside = v.filter((n) => n >= fenceLo && n <= fenceHi)\n const outliers = v.filter((n) => n < fenceLo || n > fenceHi)\n return {\n // `inside` can only be empty if every point is an outlier, which the fence\n // rule makes impossible (q1 and q3 are always within it) - but a degenerate\n // sample should still produce a box rather than `undefined` coordinates.\n min: inside.length ? inside[0]! : v[0]!,\n q1,\n median,\n q3,\n max: inside.length ? inside[inside.length - 1]! : v[v.length - 1]!,\n ...(outliers.length ? { outliers } : {}),\n }\n}\n```\n\n### `type RegressionFit`\n\nA regression's result: the fitted value at every index (NaN where the\nsource was non-finite or the model cannot take the value), R-squared\nagainst the finite source values, the equation, and `predict`, the model\nat any x. With no `xs` the x of a value is its index, which is what a\ncategory chart's overlay wants; a scatter passes its points' x values, so\nthe fit is y on x and `predict` draws the curve across the plot.\n\n```ts\nexport type RegressionFit = { fitted: number[]; r2: number; equation: string; predict: (x: number) => number }\n```\n\n### `function rSquared`\n\nR-squared of a fit: 1 minus residual over total variance across the\n indices where both the value and the fit are finite. 0 when there is no\n variance to explain.\n\n```ts\nexport function rSquared(values: ReadonlyArray<number>, fitted: ReadonlyArray<number>): number {\n let n = 0\n let mean = 0\n for (let i = 0; i < values.length; i += 1) {\n if (Number.isFinite(values[i]) && Number.isFinite(fitted[i])) { n += 1; mean += values[i]! }\n }\n if (n < 2) return 0\n mean /= n\n let ssRes = 0\n let ssTot = 0\n for (let i = 0; i < values.length; i += 1) {\n if (!Number.isFinite(values[i]) || !Number.isFinite(fitted[i])) continue\n ssRes += (values[i]! - fitted[i]!) ** 2\n ssTot += (values[i]! - mean) ** 2\n }\n if (ssTot === 0) return ssRes === 0 ? 1 : 0\n return Math.max(0, Math.min(1, 1 - ssRes / ssTot))\n}\n```\n\n### `function polynomialFit`\n\nLeast-squares polynomial of `degree` (clamped to 1..6) through\n(x, values[i]), x the index or the caller's `xs`. The x values are\nnormalised to [-1, 1] before the normal equations are solved, so a\ndegree-6 fit over a thousand points does not lose the low coefficients to\nrounding. Non-finite values are skipped and fitted as NaN.\n\n```ts\nexport function polynomialFit(values: ReadonlyArray<number>, degree: number, xs?: ReadonlyArray<number>): RegressionFit {\n const d = Math.max(1, Math.min(6, Math.round(degree)))\n const n = values.length\n const nan = NO_FIT(values)\n const X = xsOf(values, xs)\n const idx: number[] = []\n for (let i = 0; i < n; i += 1) if (Number.isFinite(values[i]) && Number.isFinite(X[i])) idx.push(i)\n if (idx.length <= d) return nan\n let lo = Infinity\n let hi = -Infinity\n for (const i of idx) { lo = Math.min(lo, X[i]!); hi = Math.max(hi, X[i]!) }\n if (!xs) { lo = 0; hi = Math.max(1, n - 1) }\n const scale = Math.max(hi - lo, 1e-12)\n const nx = (x: number) => (2 * (x - lo)) / scale - 1\n // Normal equations: sum x^(j+k) c_k = sum x^j y.\n const a: number[][] = Array.from({ length: d + 1 }, () => new Array(d + 1).fill(0))\n const b: number[] = new Array(d + 1).fill(0)\n for (const i of idx) {\n const x = nx(X[i]!)\n const y = values[i]!\n const pow: number[] = [1]\n for (let k = 1; k <= 2 * d; k += 1) pow.push(pow[k - 1]! * x)\n for (let j = 0; j <= d; j += 1) {\n b[j]! += pow[j]! * y\n for (let k = 0; k <= d; k += 1) a[j]![k]! += pow[j + k]!\n }\n }\n const c = solve(a, b)\n if (!c) return nan\n const predict = (x: number) => {\n const u = nx(x)\n let y = 0\n let p = 1\n for (let k = 0; k <= d; k += 1) { y += c[k]! * p; p *= u }\n return y\n }\n const fitted = values.map((v, i) => (Number.isFinite(v) && Number.isFinite(X[i]) ? predict(X[i]!) : NaN))\n const terms = c.map((ck, k) => (k === 0 ? fmtCoef(ck) : `${fmtCoef(ck)} u^${k}`)).reverse()\n const u = xs ? `u = 2(x - ${fmtCoef(lo)})/${fmtCoef(scale)} - 1` : `u = 2x/${scale} - 1`\n return { fitted, r2: rSquared(values, fitted), equation: `y = ${terms.join(' + ')} (${u})`, predict }\n}\n```\n\n### `function linearFit`\n\nOrdinary least squares of values on their index, or on `xs`, as a {@link RegressionFit}.\n\n```ts\nexport function linearFit(values: ReadonlyArray<number>, xs?: ReadonlyArray<number>): RegressionFit {\n const X = xsOf(values, xs)\n const { slope, intercept, ok } = lineThrough(X, values)\n if (!ok) return NO_FIT(values)\n const predict = (x: number) => slope * x + intercept\n const fitted = values.map((v, i) => (Number.isFinite(v) && Number.isFinite(X[i]) ? predict(X[i]!) : NaN))\n return { fitted, r2: rSquared(values, fitted), equation: `y = ${fmtCoef(slope)} x + ${fmtCoef(intercept)}`, predict }\n}\n```\n\n### `function exponentialFit`\n\nFit y = a * e^(b x) by least squares on ln y, x the index or `xs`;\n values at or below zero cannot be logged and are skipped (fitted as NaN).\n\n```ts\nexport function exponentialFit(values: ReadonlyArray<number>, xs?: ReadonlyArray<number>): RegressionFit {\n const X = xsOf(values, xs)\n const logs = values.map((v) => (Number.isFinite(v) && v > 0 ? Math.log(v) : NaN))\n const { slope: b, intercept, ok } = lineThrough(X, logs)\n if (!ok) return NO_FIT(values)\n const a = Math.exp(intercept)\n const predict = (x: number) => a * Math.exp(b * x)\n const fitted = values.map((v, i) => (Number.isFinite(v) && v > 0 && Number.isFinite(X[i]) ? predict(X[i]!) : NaN))\n return { fitted, r2: rSquared(values, fitted), equation: `y = ${fmtCoef(a)} e^(${fmtCoef(b)} x)`, predict }\n}\n```\n\n### `function logarithmicFit`\n\nFit y = a + b ln(x + 1) by least squares (x the index, shifted by one so\n the first point has a logarithm), or y = a + b ln(x) on `xs`, where\n points with x at or below zero are skipped.\n\n```ts\nexport function logarithmicFit(values: ReadonlyArray<number>, xs?: ReadonlyArray<number>): RegressionFit {\n const shift = xs ? 0 : 1\n const lx = xsOf(values, xs).map((x) => (x + shift > 0 ? Math.log(x + shift) : NaN))\n const { slope, intercept, ok } = lineThrough(lx, values)\n if (!ok) return NO_FIT(values)\n const predict = (x: number) => (x + shift > 0 ? intercept + slope * Math.log(x + shift) : NaN)\n const fitted = values.map((v, i) => (Number.isFinite(v) && Number.isFinite(lx[i]) ? intercept + slope * lx[i]! : NaN))\n const arg = xs ? 'x' : 'x + 1'\n return { fitted, r2: rSquared(values, fitted), equation: `y = ${fmtCoef(intercept)} + ${fmtCoef(slope)} ln(${arg})`, predict }\n}\n```\n\n### `function powerFit`\n\nFit y = a (x + 1)^b by least squares on ln y against ln(x + 1), or\n y = a x^b on `xs`; values (and x on `xs`) at or below zero are skipped\n (fitted as NaN).\n\n```ts\nexport function powerFit(values: ReadonlyArray<number>, xs?: ReadonlyArray<number>): RegressionFit {\n const shift = xs ? 0 : 1\n const lx = xsOf(values, xs).map((x) => (x + shift > 0 ? Math.log(x + shift) : NaN))\n const logs = values.map((v) => (Number.isFinite(v) && v > 0 ? Math.log(v) : NaN))\n const { slope, intercept, ok } = lineThrough(lx, logs)\n if (!ok) return NO_FIT(values)\n const a = Math.exp(intercept)\n const predict = (x: number) => (x + shift > 0 ? a * Math.pow(x + shift, slope) : NaN)\n const fitted = values.map((v, i) => (Number.isFinite(v) && v > 0 && Number.isFinite(lx[i]) ? a * Math.exp(slope * lx[i]!) : NaN))\n const arg = xs ? 'x' : '(x + 1)'\n return { fitted, r2: rSquared(values, fitted), equation: `y = ${fmtCoef(a)} ${arg}^${fmtCoef(slope)}`, predict }\n}\n```\n\n### `function simpleMovingAverage`\n\nSimple moving average over a window of `period` values. Window centres\n trail to the right (typical for time-series). NaN for points before the\n window is full.\n\n```ts\nexport function simpleMovingAverage(values: number[], period: number): number[] {\n if (period < 1) return values.slice()\n const out: number[] = new Array(values.length).fill(NaN)\n let sum = 0, count = 0\n for (let i = 0; i < values.length; i += 1) {\n const v = values[i]!\n if (Number.isFinite(v)) { sum += v; count += 1 }\n if (i >= period) {\n const drop = values[i - period]!\n if (Number.isFinite(drop)) { sum -= drop; count -= 1 }\n }\n if (i >= period - 1 && count > 0) out[i] = sum / count\n }\n return out\n}\n```\n\n### `function exponentialMovingAverage`\n\nExponential moving average. Smoothing factor alpha = 2 / (period + 1).\n\n```ts\nexport function exponentialMovingAverage(values: number[], period: number): number[] {\n const alpha = 2 / (Math.max(1, period) + 1)\n const out: number[] = new Array(values.length).fill(NaN)\n let prev: number | null = null\n for (let i = 0; i < values.length; i += 1) {\n const v = values[i]!\n if (!Number.isFinite(v)) { out[i] = prev ?? NaN; continue }\n prev = prev == null ? v : alpha * v + (1 - alpha) * prev\n out[i] = prev\n }\n return out\n}\n```\n\n### `function reducerNeedsSamples`\n\nThe reducers that need every observation, not a running sum and count.\n\n```ts\nexport function reducerNeedsSamples(reducer: ChartReducer): boolean {\n return !(reducer === 'sum' || reducer === 'avg' || reducer === 'count')\n}\n```\n\n### `function reduceValues`\n\nCollapse a group's observations to one number. `sum` / `avg` / `count` are\nwhat `rowsToChartSpec` always did; the rest are the ones a pivot table\noffers and a chart panel was missing: `min`, `max`, `median`, `first`,\n`last`, `countDistinct`, and `pN` for the Nth percentile (`'p90'`). An\nempty group reduces to 0 for `sum` / `count` and to NaN otherwise, so a\nmissing bucket draws as a gap rather than as a fake zero.\n\n```ts\nexport function reduceValues(samples: ReadonlyArray<number>, reducer: ChartReducer): number {\n const n = samples.length\n switch (reducer) {\n case 'count':\n return n\n case 'sum': {\n let s = 0\n for (const v of samples) s += v\n return s\n }\n case 'avg': {\n if (!n) return 0\n let s = 0\n for (const v of samples) s += v\n return s / n\n }\n case 'min':\n return n ? Math.min(...samples) : Number.NaN\n case 'max':\n return n ? Math.max(...samples) : Number.NaN\n case 'first':\n return n ? samples[0]! : Number.NaN\n case 'last':\n return n ? samples[n - 1]! : Number.NaN\n case 'countDistinct':\n return new Set(samples).size\n case 'median':\n return percentile(samples, 50)\n default: {\n const m = /^p(\\d+(?:\\.\\d+)?)$/.exec(reducer)\n return m ? percentile(samples, Number(m[1])) : Number.NaN\n }\n }\n}\n```\n\n### `function percentile`\n\nThe p-th percentile (0..100) by linear interpolation between order statistics.\n\n```ts\nexport function percentile(samples: ReadonlyArray<number>, p: number): number {\n const v = samples.filter((n) => Number.isFinite(n)).slice().sort((a, b) => a - b)\n if (!v.length) return Number.NaN\n const pos = (v.length - 1) * Math.max(0, Math.min(100, p)) / 100\n const lo = Math.floor(pos)\n const hi = Math.ceil(pos)\n return lo === hi ? v[lo]! : v[lo]! + (v[hi]! - v[lo]!) * (pos - lo)\n}\n```\n\n### `type ChartTimeBucket`\n\nHow `rowsToChartSpec` groups dates when `bucket` is set.\n\n```ts\nexport type ChartTimeBucket = 'day' | 'week' | 'month' | 'quarter' | 'year'\n```\n\n### `function bucketStart`\n\nThe ISO date (`YYYY-MM-DD`, UTC) that starts the bucket containing `date`:\nthe day itself, the Monday of its week, the first of its month, quarter or\nyear. Returns `''` for a value that is not a date, so the caller can drop\nthe row rather than file it under 1970.\n\n```ts\nexport function bucketStart(date: string | number | Date, bucket: ChartTimeBucket): string {\n const t = date instanceof Date ? date.getTime() : typeof date === 'number' ? date : Date.parse(date)\n if (!Number.isFinite(t)) return ''\n const d = new Date(t)\n const y = d.getUTCFullYear()\n const m = d.getUTCMonth()\n let out: Date\n switch (bucket) {\n case 'day':\n out = new Date(Date.UTC(y, m, d.getUTCDate()))\n break\n case 'week': {\n // Monday-based, which is what a business calendar reads.\n const day = (d.getUTCDay() + 6) % 7\n out = new Date(Date.UTC(y, m, d.getUTCDate() - day))\n break\n }\n case 'month':\n out = new Date(Date.UTC(y, m, 1))\n break\n case 'quarter':\n out = new Date(Date.UTC(y, m - (m % 3), 1))\n break\n default:\n out = new Date(Date.UTC(y, 0, 1))\n }\n return out.toISOString().slice(0, 10)\n}\n```\n\n### `type ChartBins`\n\nWhat {@link binValues} returns: one category per bin plus the edges.\n\n```ts\nexport type ChartBins = {\n /** Bin midpoints as strings, ready to be the categories of a numeric axis. */\n categories: string[]\n /** Observations per bin. */\n counts: number[]\n /** Bin edges, one more than there are bins. */\n edges: number[]\n /** Width of every bin. */\n width: number\n}\n```\n\n### `function binValues`\n\nBin a raw sample for a histogram. The bin count comes from `bins`, from a\n`binWidth`, or from a rule: `'sturges'` (default, log2 n + 1), `'fd'`\n(Freedman-Diaconis, 2 IQR / cbrt n) or `'sqrt'`. The range is the data's\nextent unless `min` / `max` pin it; the top edge is inclusive. Edges are\nrounded to a sensible precision for the width, so labels read as `10, 20,\n30` rather than `10.000000001`.\n\n```ts\nexport function binValues(\n values: ReadonlyArray<number>,\n opts: { bins?: number; binWidth?: number; method?: 'sturges' | 'fd' | 'sqrt'; min?: number; max?: number } = {},\n): ChartBins {\n const v = values.filter((n) => Number.isFinite(n))\n if (!v.length) return { categories: [], counts: [], edges: [], width: 0 }\n const lo = opts.min ?? Math.min(...v)\n let hi = opts.max ?? Math.max(...v)\n if (hi <= lo) hi = lo + 1\n let count: number\n if (opts.bins && opts.bins > 0) count = Math.round(opts.bins)\n else if (opts.binWidth && opts.binWidth > 0) count = Math.max(1, Math.ceil((hi - lo) / opts.binWidth))\n else if (opts.method === 'sqrt') count = Math.ceil(Math.sqrt(v.length))\n else if (opts.method === 'fd') {\n const iqr = percentile(v, 75) - percentile(v, 25)\n const w = iqr > 0 ? (2 * iqr) / Math.cbrt(v.length) : 0\n count = w > 0 ? Math.ceil((hi - lo) / w) : Math.ceil(Math.log2(v.length) + 1)\n } else count = Math.ceil(Math.log2(v.length) + 1)\n count = Math.max(1, Math.min(1000, count))\n const width = opts.binWidth && opts.binWidth > 0 ? opts.binWidth : (hi - lo) / count\n // Precision from the width: a 0.25 width keeps two decimals, a 10 width none.\n const decimals = width >= 1 ? 0 : Math.min(6, Math.ceil(-Math.log10(width)) + 1)\n const fix = (n: number) => Number(n.toFixed(decimals))\n const edges: number[] = []\n for (let i = 0; i <= count; i += 1) edges.push(fix(lo + i * width))\n const counts = new Array<number>(count).fill(0)\n for (const n of v) {\n let i = Math.floor((n - lo) / width)\n if (i >= count) i = count - 1\n if (i < 0) i = 0\n counts[i] = (counts[i] ?? 0) + 1\n }\n const categories = counts.map((_, i) => String(fix(lo + (i + 0.5) * width)))\n return { categories, counts, edges, width }\n}\n```\n"
7947
+ "markdown": "# `@svgrid/grid` · `chart-stats.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-stats.ts`.\n\n### `function boxStats`\n\nFive-number summary of a raw sample, with the 1.5 IQR whisker rule.\n\nWhiskers stop at the last observation INSIDE the fence rather than at the\nfence itself, which is what makes them read as real data; anything past them\ncomes back in `outliers`. Quartiles use linear interpolation between the two\nneighbouring order statistics.\n\nReturns `null` for an empty sample, so a category with no observations is a\ngap rather than a box drawn at zero.\n\n```ts\nexport function boxStats(sample: ReadonlyArray<number>, whisker = 1.5): BoxStats | null\n```\n\n### `type RegressionFit`\n\nA regression's result: the fitted value at every index (NaN where the\nsource was non-finite or the model cannot take the value), R-squared\nagainst the finite source values, the equation, and `predict`, the model\nat any x. With no `xs` the x of a value is its index, which is what a\ncategory chart's overlay wants; a scatter passes its points' x values, so\nthe fit is y on x and `predict` draws the curve across the plot.\n\n```ts\nexport type RegressionFit = { fitted: number[]; r2: number; equation: string; predict: (x: number) => number }\n```\n\n### `function rSquared`\n\nR-squared of a fit: 1 minus residual over total variance across the\n indices where both the value and the fit are finite. 0 when there is no\n variance to explain.\n\n```ts\nexport function rSquared(values: ReadonlyArray<number>, fitted: ReadonlyArray<number>): number\n```\n\n### `function polynomialFit`\n\nLeast-squares polynomial of `degree` (clamped to 1..6) through\n(x, values[i]), x the index or the caller's `xs`. The x values are\nnormalised to [-1, 1] before the normal equations are solved, so a\ndegree-6 fit over a thousand points does not lose the low coefficients to\nrounding. Non-finite values are skipped and fitted as NaN.\n\n```ts\nexport function polynomialFit(values: ReadonlyArray<number>, degree: number, xs?: ReadonlyArray<number>): RegressionFit\n```\n\n### `function linearFit`\n\nOrdinary least squares of values on their index, or on `xs`, as a {@link RegressionFit}.\n\n```ts\nexport function linearFit(values: ReadonlyArray<number>, xs?: ReadonlyArray<number>): RegressionFit\n```\n\n### `function exponentialFit`\n\nFit y = a * e^(b x) by least squares on ln y, x the index or `xs`;\n values at or below zero cannot be logged and are skipped (fitted as NaN).\n\n```ts\nexport function exponentialFit(values: ReadonlyArray<number>, xs?: ReadonlyArray<number>): RegressionFit\n```\n\n### `function logarithmicFit`\n\nFit y = a + b ln(x + 1) by least squares (x the index, shifted by one so\n the first point has a logarithm), or y = a + b ln(x) on `xs`, where\n points with x at or below zero are skipped.\n\n```ts\nexport function logarithmicFit(values: ReadonlyArray<number>, xs?: ReadonlyArray<number>): RegressionFit\n```\n\n### `function powerFit`\n\nFit y = a (x + 1)^b by least squares on ln y against ln(x + 1), or\n y = a x^b on `xs`; values (and x on `xs`) at or below zero are skipped\n (fitted as NaN).\n\n```ts\nexport function powerFit(values: ReadonlyArray<number>, xs?: ReadonlyArray<number>): RegressionFit\n```\n\n### `function simpleMovingAverage`\n\nSimple moving average over a window of `period` values. Window centres\n trail to the right (typical for time-series). NaN for points before the\n window is full.\n\n```ts\nexport function simpleMovingAverage(values: number[], period: number): number[]\n```\n\n### `function exponentialMovingAverage`\n\nExponential moving average. Smoothing factor alpha = 2 / (period + 1).\n\n```ts\nexport function exponentialMovingAverage(values: number[], period: number): number[]\n```\n\n### `function reducerNeedsSamples`\n\nThe reducers that need every observation, not a running sum and count.\n\n```ts\nexport function reducerNeedsSamples(reducer: ChartReducer): boolean\n```\n\n### `function reduceValues`\n\nCollapse a group's observations to one number. `sum` / `avg` / `count` are\nwhat `rowsToChartSpec` always did; the rest are the ones a pivot table\noffers and a chart panel was missing: `min`, `max`, `median`, `first`,\n`last`, `countDistinct`, and `pN` for the Nth percentile (`'p90'`). An\nempty group reduces to 0 for `sum` / `count` and to NaN otherwise, so a\nmissing bucket draws as a gap rather than as a fake zero.\n\n```ts\nexport function reduceValues(samples: ReadonlyArray<number>, reducer: ChartReducer): number\n```\n\n### `function percentile`\n\nThe p-th percentile (0..100) by linear interpolation between order statistics.\n\n```ts\nexport function percentile(samples: ReadonlyArray<number>, p: number): number\n```\n\n### `type ChartTimeBucket`\n\nHow `rowsToChartSpec` groups dates when `bucket` is set.\n\n```ts\nexport type ChartTimeBucket = 'day' | 'week' | 'month' | 'quarter' | 'year'\n```\n\n### `function bucketStart`\n\nThe ISO date (`YYYY-MM-DD`, UTC) that starts the bucket containing `date`:\nthe day itself, the Monday of its week, the first of its month, quarter or\nyear. Returns `''` for a value that is not a date, so the caller can drop\nthe row rather than file it under 1970.\n\n```ts\nexport function bucketStart(date: string | number | Date, bucket: ChartTimeBucket): string\n```\n\n### `type ChartBins`\n\nWhat {@link binValues} returns: one category per bin plus the edges.\n\n```ts\nexport type ChartBins = {\n /** Bin midpoints as strings, ready to be the categories of a numeric axis. */\n categories: string[]\n /** Observations per bin. */\n counts: number[]\n /** Bin edges, one more than there are bins. */\n edges: number[]\n /** Width of every bin. */\n width: number\n}\n```\n\n### `function binValues`\n\nBin a raw sample for a histogram. The bin count comes from `bins`, from a\n`binWidth`, or from a rule: `'sturges'` (default, log2 n + 1), `'fd'`\n(Freedman-Diaconis, 2 IQR / cbrt n) or `'sqrt'`. The range is the data's\nextent unless `min` / `max` pin it; the top edge is inclusive. Edges are\nrounded to a sensible precision for the width, so labels read as `10, 20,\n30` rather than `10.000000001`.\n\n```ts\nexport function binValues(\n values: ReadonlyArray<number>,\n opts: { bins?: number; binWidth?: number; method?: 'sturges' | 'fd' | 'sqrt'; min?: number; max?: number } = {},\n): ChartBins\n```\n"
7877
7948
  },
7878
7949
  {
7879
7950
  "slug": "reference/auto/svgrid-grid-chart-stream",
7880
7951
  "path": "docs/reference/auto/svgrid-grid-chart-stream.md",
7881
7952
  "title": "@svgrid/grid · chart-stream.ts",
7882
7953
  "section": "API reference",
7883
- "markdown": "# `@svgrid/grid` · `chart-stream.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-stream.ts`.\n\n### `type ChartPoint`\n\nOne new category with its values, for {@link appendPoints}.\n\n```ts\nexport type ChartPoint = {\n /** The category label (a date string on a time axis). */\n category: string\n /** One value per series in spec order, or values keyed by series label;\n * a series not named gets a gap (NaN). */\n values: ReadonlyArray<number> | Record<string, number>\n /** The bar for a candlestick series (the first series with `ohlc`). */\n ohlc?: OhlcBar | null\n /** The volume for that series. */\n volume?: number\n /** Row ids behind the point, one array per series in spec order. */\n rowIds?: ReadonlyArray<ReadonlyArray<string | number>>\n /** Confidence band ends, one per series in spec order. */\n upper?: ReadonlyArray<number>\n lower?: ReadonlyArray<number>\n /** Range low / bullet target, one per series in spec order. */\n low?: ReadonlyArray<number>\n target?: ReadonlyArray<number>\n}\n```\n\n### `type AppendPointsOptions`\n\nWhat {@link appendPoints} takes besides the points.\n\n```ts\nexport type AppendPointsOptions = {\n /** Keep only the last `window` categories after appending. */\n window?: number\n}\n```\n\n### `function appendPoints`\n\nAppend one or more points to a spec and return the new spec, trimmed to\nthe trailing `window` categories when one is given. Every array a series\ncarries per category (values, row ids, bands, candles, volumes, colours,\nmarkers, errors, lows, targets) grows by the same count, with a gap where\nthe point says nothing; so do the spec-level ones (waterfall totals). The\ninput is never mutated: only the arrays that grow are copied, which keeps\nSvelte's state diffing cheap at 4 Hz.\n\n```ts\nexport function appendPoints(spec: ChartSpec, points: ChartPoint | ReadonlyArray<ChartPoint>, opts: AppendPointsOptions = {}): ChartSpec {\n const list = Array.isArray(points) ? (points as ReadonlyArray<ChartPoint>) : [points as ChartPoint]\n if (!list.length) return opts.window ? trim(spec, opts.window) : spec\n const categories = [...spec.categories, ...list.map((p) => p.category)]\n const ohlcOwner = spec.series.findIndex((s) => s.ohlc)\n const series = spec.series.map((s, si) => {\n const next: ChartSeries = { ...s, values: [...s.values] }\n for (const p of list) {\n const v = Array.isArray(p.values) ? (p.values as ReadonlyArray<number>)[si] : (p.values as Record<string, number>)[s.label]\n next.values.push(typeof v === 'number' ? v : Number.NaN)\n }\n for (const key of PER_CATEGORY_SERIES_KEYS) {\n if (key === 'values') continue\n const has = s[key] !== undefined\n // A key the series does not carry is only created when a point brings\n // it (a candle, a volume), so a plain line stays a plain line.\n const brings = list.some((p) =>\n (key === 'ohlc' && p.ohlc !== undefined && si === (ohlcOwner < 0 ? 0 : ohlcOwner)) ||\n (key === 'volumes' && p.volume !== undefined && si === (ohlcOwner < 0 ? 0 : ohlcOwner)) ||\n (key === 'rowIds' && p.rowIds?.[si] !== undefined) ||\n (key === 'upperValues' && p.upper?.[si] !== undefined) ||\n (key === 'lowerValues' && p.lower?.[si] !== undefined) ||\n (key === 'lowValues' && p.low?.[si] !== undefined) ||\n (key === 'targets' && p.target?.[si] !== undefined))\n if (!has && !brings) continue\n const base: unknown[] = has ? [...(s[key] as unknown[])] : new Array(s.values.length).fill(gapFor(key))\n for (const p of list) {\n let v: unknown = undefined\n if (key === 'ohlc' && si === (ohlcOwner < 0 ? 0 : ohlcOwner)) v = p.ohlc\n else if (key === 'volumes' && si === (ohlcOwner < 0 ? 0 : ohlcOwner)) v = p.volume\n else if (key === 'rowIds') v = p.rowIds?.[si]\n else if (key === 'upperValues') v = p.upper?.[si]\n else if (key === 'lowerValues') v = p.lower?.[si]\n else if (key === 'lowValues') v = p.low?.[si]\n else if (key === 'targets') v = p.target?.[si]\n base.push(v === undefined ? gapFor(key) : v)\n }\n ;(next as unknown as Record<string, unknown>)[key] = base\n }\n return next\n })\n let out: ChartSpec = { ...spec, categories, series }\n for (const key of PER_CATEGORY_SPEC_KEYS) {\n const arr = spec[key] as unknown[] | undefined\n if (arr) (out as unknown as Record<string, unknown>)[key] = [...arr, ...list.map(() => false)]\n }\n if (opts.window) out = trim(out, opts.window)\n return out\n}\n```\n"
7954
+ "markdown": "# `@svgrid/grid` · `chart-stream.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-stream.ts`.\n\n### `type ChartPoint`\n\nOne new category with its values, for {@link appendPoints}.\n\n```ts\nexport type ChartPoint = {\n /** The category label (a date string on a time axis). */\n category: string\n /** One value per series in spec order, or values keyed by series label;\n * a series not named gets a gap (NaN). */\n values: ReadonlyArray<number> | Record<string, number>\n /** The bar for a candlestick series (the first series with `ohlc`). */\n ohlc?: OhlcBar | null\n /** The volume for that series. */\n volume?: number\n /** Row ids behind the point, one array per series in spec order. */\n rowIds?: ReadonlyArray<ReadonlyArray<string | number>>\n /** Confidence band ends, one per series in spec order. */\n upper?: ReadonlyArray<number>\n lower?: ReadonlyArray<number>\n /** Range low / bullet target, one per series in spec order. */\n low?: ReadonlyArray<number>\n target?: ReadonlyArray<number>\n}\n```\n\n### `type AppendPointsOptions`\n\nWhat {@link appendPoints} takes besides the points.\n\n```ts\nexport type AppendPointsOptions = {\n /** Keep only the last `window` categories after appending. */\n window?: number\n}\n```\n\n### `function appendPoints`\n\nAppend one or more points to a spec and return the new spec, trimmed to\nthe trailing `window` categories when one is given. Every array a series\ncarries per category (values, row ids, bands, candles, volumes, colours,\nmarkers, errors, lows, targets) grows by the same count, with a gap where\nthe point says nothing; so do the spec-level ones (waterfall totals). The\ninput is never mutated: only the arrays that grow are copied, which keeps\nSvelte's state diffing cheap at 4 Hz.\n\n```ts\nexport function appendPoints(spec: ChartSpec, points: ChartPoint | ReadonlyArray<ChartPoint>, opts: AppendPointsOptions = {}): ChartSpec\n```\n"
7884
7955
  },
7885
7956
  {
7886
7957
  "slug": "reference/auto/svgrid-grid-chart-summary",
7887
7958
  "path": "docs/reference/auto/svgrid-grid-chart-summary.md",
7888
7959
  "title": "@svgrid/grid · chart-summary.ts",
7889
7960
  "section": "API reference",
7890
- "markdown": "# `@svgrid/grid` · `chart-summary.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-summary.ts`.\n\n### `type ChartSummaryOptions`\n\nWhat {@link chartSummary} takes.\n\n```ts\nexport type ChartSummaryOptions = {\n /** How numbers are written. Default: the spec's `valueFormat` / `locale` / `currency`. */\n formatValue?: (v: number) => string\n /** How many series a cartesian chart describes before it says \"and N more\". Default 4. */\n maxSeries?: number\n}\n```\n\n### `function chartSummary`\n\nDescribe a spec in plain words. Never throws: an empty spec of any type\ncomes back as \"No data.\" so a live region always has something to say.\n\n```ts\nexport function chartSummary(spec: ChartSpec, opts: ChartSummaryOptions = {}): string {\n const fmt = opts.formatValue ?? ((v: number) => formatChartValue(v, spec.valueFormat, spec))\n const max = opts.maxSeries ?? 4\n const cats = spec.categories ?? []\n const series = (spec.series ?? []).filter((s) => s.visible !== false)\n const type = spec.type\n try {\n if (type === 'pie' || type === 'radial-bar' || type === 'nightingale') {\n const s = series[0]\n if (!s || !s.values.some(finite)) return 'No data.'\n return shares(cats, s.values, fmt, 'slice')\n }\n if (type === 'treemap' || type === 'sunburst') {\n const root = spec.treemap ?? spec.tree\n const kids = root?.children ?? []\n if (!kids.length) return 'No data.'\n const total = (n: { value?: number; children?: Array<{ value?: number; children?: unknown[] }> }): number =>\n n.value ?? (n.children ?? []).reduce((a, c) => a + total(c as never), 0)\n return shares(kids.map((k) => k.name), kids.map((k) => total(k)), fmt, 'node')\n }\n if (type === 'gauge') {\n if (!finite(spec.gaugeValue)) return 'No data.'\n const lo = spec.gaugeMin ?? 0\n const hi = spec.gaugeMax ?? 100\n const share = hi > lo ? Math.round(((spec.gaugeValue - lo) / (hi - lo)) * 100) : 0\n const target = finite(spec.gaugeTarget) ? `, ${spec.gaugeValue >= spec.gaugeTarget ? 'above' : 'below'} the target of ${fmt(spec.gaugeTarget)}` : ''\n return `${fmt(spec.gaugeValue)}${spec.gaugeUnit ? ' ' + spec.gaugeUnit : ''}, ${share}% of the way from ${fmt(lo)} to ${fmt(hi)}${target}.`\n }\n if (type === 'scatter') {\n const pts = series.flatMap((s) => s.points ?? []).filter((p) => finite(p.x) && finite(p.y))\n if (!pts.length) return 'No data.'\n const r = pearson(pts.map((p) => p.x), pts.map((p) => p.y))\n const strength = Math.abs(r) >= 0.7 ? 'strong' : Math.abs(r) >= 0.4 ? 'moderate' : Math.abs(r) >= 0.2 ? 'weak' : 'no'\n const sign = r > 0 ? 'positive' : 'negative'\n const rel = strength === 'no' ? 'no clear correlation' : `a ${strength} ${sign} correlation (r ${r.toFixed(2)})`\n return `${pts.length} points in ${series.length} series with ${rel} between x and y.`\n }\n if (type === 'candlestick' || type === 'ohlc') {\n const s = series.find((x) => x.ohlc) ?? series[0]\n const bars = (s?.ohlc ?? []).filter((b): b is NonNullable<typeof b> => !!b)\n if (!s || !bars.length) return 'No data.'\n const last = bars[bars.length - 1]!\n const prev = bars.length > 1 ? bars[bars.length - 2]! : null\n const hi = Math.max(...bars.map((b) => b.h))\n const lo = Math.min(...bars.map((b) => b.l))\n const move = prev ? `, ${last.c >= prev.c ? 'up' : 'down'} ${pct(prev.c, last.c)} on the session` : ''\n return `${s.label}: last close ${fmt(last.c)}${move}, ranging ${fmt(lo)} to ${fmt(hi)} over ${bars.length} bars.`\n }\n if (type === 'heatmap') {\n let best: { v: number; row: string; col: string } | null = null\n for (const s of series) s.values.forEach((v, i) => { if (finite(v) && (!best || v > best.v)) best = { v, row: s.label, col: cats[i] ?? String(i) } })\n if (!best) return 'No data.'\n const b = best as { v: number; row: string; col: string }\n return `${series.length} rows by ${cats.length} columns; the highest cell is ${fmt(b.v)} at ${b.row} and ${b.col}.`\n }\n if (type === 'calendar') {\n const days = (spec.calendarValues ?? []).filter((d) => finite(d.value))\n if (!days.length) return 'No data.'\n const top = days.reduce((a, d) => (d.value > a.value ? d : a), days[0]!)\n const total = days.reduce((a, d) => a + d.value, 0)\n return `${days.length} days totalling ${fmt(total)}; the busiest is ${top.date} at ${fmt(top.value)}.`\n }\n if (type === 'funnel') {\n const s = series[0]\n const vals = (s?.values ?? []).filter(finite)\n if (!s || vals.length < 2) return s && vals.length === 1 ? `${cats[0] ?? s.label}: ${fmt(vals[0]!)}.` : 'No data.'\n const first = vals[0]!\n const last = vals[vals.length - 1]!\n const conv = first ? Math.round((last / first) * 100) : 0\n let worstDrop = 0\n let worstAt = ''\n for (let i = 1; i < vals.length; i += 1) {\n const drop = vals[i - 1]! ? 1 - vals[i]! / vals[i - 1]! : 0\n if (drop > worstDrop) { worstDrop = drop; worstAt = cats[i] ?? `step ${i + 1}` }\n }\n return `${conv}% of ${fmt(first)} at ${cats[0] ?? 'the top'} reach ${cats[vals.length - 1] ?? 'the bottom'}${worstAt ? `; the biggest drop is into ${worstAt} (${Math.round(worstDrop * 100)}% lost)` : ''}.`\n }\n if (type === 'boxplot') {\n let widest: { label: string; spread: number } | null = null\n for (const s of series) for (const b of s.boxes ?? []) {\n if (!b) continue\n const spread = b.q3 - b.q1\n if (!widest || spread > widest.spread) widest = { label: s.label, spread }\n }\n if (!widest) return 'No data.'\n return `${series.length} distributions over ${cats.length} categories; ${widest.label} has the widest interquartile range at ${fmt(widest.spread)}.`\n }\n if (type === 'sankey' || type === 'chord') {\n const links = spec.sankeyLinks ?? []\n if (!links.length) return 'No data.'\n const total = links.reduce((a, l) => a + (finite(l.value) ? l.value : 0), 0)\n const top = [...links].sort((a, b) => b.value - a.value)[0]!\n return `${links.length} flows totalling ${fmt(total)}; the largest is ${top.source} to ${top.target} at ${fmt(top.value)}.`\n }\n // Cartesian families: one sentence per series, up to the cap.\n const usable = series.filter((s) => s.values.some(finite) || s.ohlc)\n if (!usable.length) return 'No data.'\n const shown = usable.slice(0, max)\n const parts = shown.map((s) => describeSeries(s, cats, fmt))\n const more = usable.length > shown.length ? ` And ${usable.length - shown.length} more series.` : ''\n return `${parts.join(' ')}${more}`\n } catch {\n return 'No data.'\n }\n}\n```\n"
7961
+ "markdown": "# `@svgrid/grid` · `chart-summary.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-summary.ts`.\n\n### `type ChartSummaryOptions`\n\nWhat {@link chartSummary} takes.\n\n```ts\nexport type ChartSummaryOptions = {\n /** How numbers are written. Default: the spec's `valueFormat` / `locale` / `currency`. */\n formatValue?: (v: number) => string\n /** How many series a cartesian chart describes before it says \"and N more\". Default 4. */\n maxSeries?: number\n}\n```\n\n### `function chartSummary`\n\nDescribe a spec in plain words. Never throws: an empty spec of any type\ncomes back as \"No data.\" so a live region always has something to say.\n\n```ts\nexport function chartSummary(spec: ChartSpec, opts: ChartSummaryOptions = {}): string\n```\n"
7891
7962
  },
7892
7963
  {
7893
7964
  "slug": "reference/auto/svgrid-grid-chart-sync.svelte",
7894
7965
  "path": "docs/reference/auto/svgrid-grid-chart-sync.svelte.md",
7895
7966
  "title": "@svgrid/grid · chart-sync.svelte.ts",
7896
7967
  "section": "API reference",
7897
- "markdown": "# `@svgrid/grid` · `chart-sync.svelte.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-sync.svelte.ts`.\n\n### `type ChartSyncState`\n\nWhat one chart publishes for the others: the hovered category (its label,\n index and, when the category parses as a date, its time) and the window.\n\n```ts\nexport type ChartSyncState = {\n hover: { label: string; index: number; time: number | null; from: symbol } | null\n zoom: { window: ChartZoomWindow | null; count: number; from: symbol; labels: [string, string] | null } | null\n}\n```\n\n### `function syncGroupState`\n\nThe live entry for a group, created on first use.\n\n```ts\nexport function syncGroupState(name: string): ChartSyncState {\n const existing = groups.get(name)\n if (existing) return existing\n const fresh = $state<ChartSyncState>({ hover: null, zoom: null })\n groups.set(name, fresh)\n return fresh\n}\n```\n\n### `function publishSyncHover`\n\nPublish a hover (or clear it with null).\n\n```ts\nexport function publishSyncHover(name: string, hover: ChartSyncState['hover']): void {\n syncGroupState(name).hover = hover\n}\n```\n\n### `function publishSyncZoom`\n\nPublish a zoom window (null = the whole axis) with the axis length it\n was made against and the category labels at its two ends, so a chart with\n a different axis can map it by date.\n\n```ts\nexport function publishSyncZoom(name: string, window: ChartZoomWindow | null, count: number, from: symbol, labels: [string, string] | null = null): void {\n syncGroupState(name).zoom = { window, count, from, labels }\n}\n```\n"
7968
+ "markdown": "# `@svgrid/grid` · `chart-sync.svelte.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-sync.svelte.ts`.\n\n### `type ChartSyncState`\n\nWhat one chart publishes for the others: the hovered category (its label,\n index and, when the category parses as a date, its time) and the window.\n\n```ts\nexport type ChartSyncState = {\n hover: { label: string; index: number; time: number | null; from: symbol } | null\n zoom: { window: ChartZoomWindow | null; count: number; from: symbol; labels: [string, string] | null } | null\n}\n```\n\n### `function syncGroupState`\n\nThe live entry for a group, created on first use.\n\n```ts\nexport function syncGroupState(name: string): ChartSyncState\n```\n\n### `function publishSyncHover`\n\nPublish a hover (or clear it with null).\n\n```ts\nexport function publishSyncHover(name: string, hover: ChartSyncState['hover']): void\n```\n\n### `function publishSyncZoom`\n\nPublish a zoom window (null = the whole axis) with the axis length it\n was made against and the category labels at its two ends, so a chart with\n a different axis can map it by date.\n\n```ts\nexport function publishSyncZoom(name: string, window: ChartZoomWindow | null, count: number, from: symbol, labels: [string, string] | null = null): void\n```\n"
7898
7969
  },
7899
7970
  {
7900
7971
  "slug": "reference/auto/svgrid-grid-chart-table",
7901
7972
  "path": "docs/reference/auto/svgrid-grid-chart-table.md",
7902
7973
  "title": "@svgrid/grid · chart-table.ts",
7903
7974
  "section": "API reference",
7904
- "markdown": "# `@svgrid/grid` · `chart-table.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-table.ts`.\n\n### `type ChartTableColumn`\n\nOne column of a chart's table: what `SvGrid` needs to draw it.\n\n```ts\nexport type ChartTableColumn = {\n field: string\n header: string\n cellDataType?: 'number' | 'text' | 'date'\n format?: CellFormatConfig\n width?: number\n}\n```\n\n### `type ChartTable`\n\nA chart's data as a table: grid columns and plain row objects.\n\n```ts\nexport type ChartTable = {\n columns: ChartTableColumn[]\n rows: Array<Record<string, unknown>>\n}\n```\n\n### `function chartSpecToTable`\n\nThe rows and columns a chart spec amounts to. Never throws: a spec with\nnothing to tabulate comes back with no rows and no columns.\n\n```ts\nexport function chartSpecToTable(spec: ChartSpec): ChartTable {\n const fmt = formatOf(spec.valueFormat, spec)\n // A series on the right axis reads in that axis's format: a margin of 0.29\n // beside a revenue in dollars is \"29%\", not \"$0.29\".\n const fmt2 = formatOf(spec.y2Axis?.format, spec)\n const numCol = (field: string, header: string, right = false): ChartTableColumn => {\n const f = right ? fmt2 : fmt\n return { field, header, cellDataType: 'number', ...(f ? { format: f } : {}) }\n }\n const textCol = (field: string, header: string): ChartTableColumn => ({ field, header })\n const series = spec.series ?? []\n\n // Scatter and bubble: one row per point.\n if (series.some((s) => s.points?.length)) {\n const rows: Array<Record<string, unknown>> = []\n for (const s of series) for (const p of s.points ?? []) rows.push({ series: s.label, x: num(p.x), y: num(p.y), size: num(p.r), label: p.label ?? '' })\n return { columns: [textCol('series', 'Series'), numCol('x', 'X'), numCol('y', 'Y'), numCol('size', 'Size'), textCol('label', 'Label')], rows }\n }\n // Sankey and chord: one row per link.\n if (spec.sankeyLinks?.length) {\n const names = new Map((spec.sankeyNodes ?? []).map((n) => [n.id, n.label ?? n.id]))\n const rows = spec.sankeyLinks.map((l) => ({ source: names.get(l.source) ?? l.source, target: names.get(l.target) ?? l.target, value: num(l.value) }))\n return { columns: [textCol('source', 'Source'), textCol('target', 'Target'), numCol('value', 'Value')], rows }\n }\n // Tree map and sunburst: one row per leaf, a column per level.\n const tree = spec.tree ?? spec.treemap\n if (tree && (spec.type === 'treemap' || spec.type === 'sunburst' || !spec.categories?.length)) {\n const rows: Array<Record<string, unknown>> = []\n let depth = 0\n const walk = (n: TreeNode, path: string[]) => {\n if (n.children?.length) {\n for (const c of n.children) walk(c, [...path, c.name])\n return\n }\n depth = Math.max(depth, path.length)\n const row: Record<string, unknown> = { value: num(n.value) }\n path.forEach((seg, i) => (row[`level${i + 1}`] = seg))\n rows.push(row)\n }\n walk(tree, [])\n const columns: ChartTableColumn[] = []\n for (let i = 1; i <= depth; i += 1) columns.push(textCol(`level${i}`, depth === 1 ? 'Name' : `Level ${i}`))\n columns.push(numCol('value', 'Value'))\n return { columns, rows }\n }\n // Calendar: one row per day.\n if (spec.calendarValues?.length) {\n return {\n columns: [{ field: 'date', header: 'Date', cellDataType: 'date' }, numCol('value', 'Value')],\n rows: spec.calendarValues.map((d) => ({ date: d.date, value: num(d.value) })),\n }\n }\n // Gauge: the one reading and its scale.\n if (spec.type === 'gauge') {\n return {\n columns: [textCol('metric', 'Metric'), numCol('value', spec.gaugeUnit ? `Value (${spec.gaugeUnit})` : 'Value'), numCol('min', 'Min'), numCol('max', 'Max'), numCol('target', 'Target')],\n rows: [{ metric: spec.title ?? spec.series[0]?.label ?? 'Value', value: num(spec.gaugeValue), min: num(spec.gaugeMin ?? 0), max: num(spec.gaugeMax ?? 100), target: num(spec.gaugeTarget) }],\n }\n }\n\n // Everything else reads categories x series: one row per category, one\n // column per number a series carries.\n const cats = spec.categories ?? []\n if (!cats.length || !series.length) return { columns: [], rows: [] }\n const columns: ChartTableColumn[] = []\n const groups = spec.categoryGroups\n if (groups?.length) columns.push(textCol('group', 'Group'))\n const edges = spec.binEdges\n const xType = spec.xAxis?.type ?? spec.xType\n const dated = xType === 'time' || xType === 'ordinal-time'\n const catHeader = spec.xAxis?.title ?? spec.xAxisTitle ?? (dated ? 'Date' : 'Category')\n if (edges && edges.length === cats.length + 1) columns.push(numCol('from', 'From'), numCol('to', 'To'))\n else columns.push(dated ? { field: 'category', header: catHeader, cellDataType: 'date' } : textCol('category', catHeader))\n const fields: Array<{ field: string; pick: (i: number) => unknown }> = []\n series.forEach((s, si) => {\n const key = (suffix: string) => `s${si}${suffix}`\n const add = (suffix: string, header: string, pick: (i: number) => unknown) => {\n columns.push(numCol(key(suffix), header, s.axis === 'right'))\n fields.push({ field: key(suffix), pick })\n }\n if (s.ohlc) {\n add('o', `${s.label} Open`, (i) => num(s.ohlc![i]?.o))\n add('h', `${s.label} High`, (i) => num(s.ohlc![i]?.h))\n add('l', `${s.label} Low`, (i) => num(s.ohlc![i]?.l))\n add('c', `${s.label} Close`, (i) => num(s.ohlc![i]?.c))\n if (s.volumes) add('v', `${s.label} Volume`, (i) => num(s.volumes![i]))\n } else if (s.boxes) {\n add('min', `${s.label} Min`, (i) => num(s.boxes![i]?.min))\n add('q1', `${s.label} Q1`, (i) => num(s.boxes![i]?.q1))\n add('med', `${s.label} Median`, (i) => num(s.boxes![i]?.median))\n add('q3', `${s.label} Q3`, (i) => num(s.boxes![i]?.q3))\n add('max', `${s.label} Max`, (i) => num(s.boxes![i]?.max))\n columns.push(textCol(key('out'), `${s.label} Outliers`))\n fields.push({ field: key('out'), pick: (i) => s.boxes![i]?.outliers?.join(' ') ?? '' })\n } else if (s.errors) {\n add('', s.label, (i) => num(s.values[i]))\n add('lo', `${s.label} Low`, (i) => {\n const v = s.values[i], e = s.errors![i]\n return e == null || !Number.isFinite(v) ? null : typeof e === 'number' ? (v as number) - Math.abs(e) : Math.min(e.lo, e.hi)\n })\n add('hi', `${s.label} High`, (i) => {\n const v = s.values[i], e = s.errors![i]\n return e == null || !Number.isFinite(v) ? null : typeof e === 'number' ? (v as number) + Math.abs(e) : Math.max(e.lo, e.hi)\n })\n } else if (s.lowValues) {\n add('lo', `${s.label} Low`, (i) => num(s.lowValues![i]))\n add('hi', `${s.label} High`, (i) => num(s.values[i]))\n } else if (s.targets) {\n add('', s.label, (i) => num(s.values[i]))\n add('t', `${s.label} Target`, (i) => num(s.targets![i]))\n } else {\n add('', s.label, (i) => num(s.values[i]))\n }\n })\n // A category's group, from the spans.\n const groupOf: string[] = []\n if (groups?.length) for (const g of groups) for (let k = 0; k < g.span; k += 1) groupOf.push(g.label)\n const rows = cats.map((cat, i) => {\n const row: Record<string, unknown> = {}\n if (groups?.length) row.group = groupOf[i] ?? ''\n if (edges && edges.length === cats.length + 1) {\n row.from = num(edges[i])\n row.to = num(edges[i + 1])\n } else row.category = cat\n for (const f of fields) row[f.field] = f.pick(i)\n return row\n })\n return { columns, rows }\n}\n```\n"
7975
+ "markdown": "# `@svgrid/grid` · `chart-table.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-table.ts`.\n\n### `type ChartTableColumn`\n\nOne column of a chart's table: what `SvGrid` needs to draw it.\n\n```ts\nexport type ChartTableColumn = {\n field: string\n header: string\n cellDataType?: 'number' | 'text' | 'date'\n format?: CellFormatConfig\n width?: number\n}\n```\n\n### `type ChartTable`\n\nA chart's data as a table: grid columns and plain row objects.\n\n```ts\nexport type ChartTable = {\n columns: ChartTableColumn[]\n rows: Array<Record<string, unknown>>\n}\n```\n\n### `function chartSpecToTable`\n\nThe rows and columns a chart spec amounts to. Never throws: a spec with\nnothing to tabulate comes back with no rows and no columns.\n\n```ts\nexport function chartSpecToTable(spec: ChartSpec): ChartTable\n```\n"
7905
7976
  },
7906
7977
  {
7907
7978
  "slug": "reference/auto/svgrid-grid-chart-trend",
7908
7979
  "path": "docs/reference/auto/svgrid-grid-chart-trend.md",
7909
7980
  "title": "@svgrid/grid · chart-trend.ts",
7910
7981
  "section": "API reference",
7911
- "markdown": "# `@svgrid/grid` · `chart-trend.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-trend.ts`.\n\n### `function linearTrend`\n\nOrdinary least-squares regression on (i, values[i]) pairs (i = x index).\n Returns the fitted value at each x index, or NaN where the source value\n was non-finite.\n\n```ts\nexport function linearTrend(values: number[]): number[] {\n let n = 0, sumX = 0, sumY = 0, sumXX = 0, sumXY = 0\n for (let i = 0; i < values.length; i += 1) {\n const y = values[i]!\n if (!Number.isFinite(y)) continue\n n += 1; sumX += i; sumY += y; sumXX += i * i; sumXY += i * y\n }\n if (n < 2) return values.map(() => NaN)\n const denom = n * sumXX - sumX * sumX\n if (denom === 0) return values.map(() => sumY / n)\n const slope = (n * sumXY - sumX * sumY) / denom\n const intercept = (sumY - slope * sumX) / n\n return values.map((_, i) => slope * i + intercept)\n}\n```\n\n### `function pearson`\n\nPearson's correlation coefficient of two equal-length samples, skipping\n pairs where either side is non-finite; 0 when fewer than two pairs remain\n or either side has no variance.\n\n```ts\nexport function pearson(xs: ReadonlyArray<number>, ys: ReadonlyArray<number>): number {\n let n = 0, sx = 0, sy = 0\n const len = Math.min(xs.length, ys.length)\n for (let i = 0; i < len; i += 1) if (Number.isFinite(xs[i]) && Number.isFinite(ys[i])) { n += 1; sx += xs[i]!; sy += ys[i]! }\n if (n < 2) return 0\n const mx = sx / n, my = sy / n\n let sxy = 0, sxx = 0, syy = 0\n for (let i = 0; i < len; i += 1) {\n if (!Number.isFinite(xs[i]) || !Number.isFinite(ys[i])) continue\n const dx = xs[i]! - mx, dy = ys[i]! - my\n sxy += dx * dy; sxx += dx * dx; syy += dy * dy\n }\n return sxx === 0 || syy === 0 ? 0 : sxy / Math.sqrt(sxx * syy)\n}\n```\n"
7982
+ "markdown": "# `@svgrid/grid` · `chart-trend.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-trend.ts`.\n\n### `function linearTrend`\n\nOrdinary least-squares regression on (i, values[i]) pairs (i = x index).\n Returns the fitted value at each x index, or NaN where the source value\n was non-finite.\n\n```ts\nexport function linearTrend(values: number[]): number[]\n```\n\n### `function pearson`\n\nPearson's correlation coefficient of two equal-length samples, skipping\n pairs where either side is non-finite; 0 when fewer than two pairs remain\n or either side has no variance.\n\n```ts\nexport function pearson(xs: ReadonlyArray<number>, ys: ReadonlyArray<number>): number\n```\n"
7912
7983
  },
7913
7984
  {
7914
7985
  "slug": "reference/auto/svgrid-grid-chart-types",
@@ -7922,98 +7993,98 @@ export const docs = [
7922
7993
  "path": "docs/reference/auto/svgrid-grid-chart-validate.md",
7923
7994
  "title": "@svgrid/grid · chart-validate.ts",
7924
7995
  "section": "API reference",
7925
- "markdown": "# `@svgrid/grid` · `chart-validate.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-validate.ts`.\n\n### `type ChartDiagnostic`\n\nOne finding of {@link validateChartSpec}.\n\n```ts\nexport type ChartDiagnostic = {\n /** A stable rule id, `chart/<rule>`. */\n code: string\n /** The field's path in the spec, like `series[1].values` or `yAxis.min`. */\n path: string\n message: string\n /** `error`: will not draw as intended. `warning`: ignored, or a likely slip. */\n severity: 'error' | 'warning'\n}\n```\n\n### `const CHART_TYPES`\n\nEvery `ChartType` the engine draws.\n\n```ts\nexport const CHART_TYPES: ReadonlyArray<ChartType> = [\n 'bar', 'line', 'area', 'pie', 'scatter', 'heatmap', 'waterfall', 'funnel', 'radar', 'calendar', 'gauge',\n 'treemap', 'sankey', 'candlestick', 'ohlc', 'boxplot', 'histogram', 'range-bar', 'range-area', 'lollipop',\n 'dumbbell', 'pareto', 'stream', 'sunburst', 'radial-bar', 'radial-column', 'nightingale', 'chord', 'bullet',\n]\n```\n\n### `const KNOWN_SPEC_KEYS`\n\nEvery top-level key a `ChartSpec` may carry.\n\n```ts\nexport const KNOWN_SPEC_KEYS: ReadonlyArray<keyof ChartSpec> = [\n 'type', 'categories', 'series', 'width', 'height', 'palette', 'categoryColors', 'valueFormat', 'locale',\n 'currency', 'categoryGroups', 'stacked', 'stacked100', 'orientation', 'innerRadius', 'referenceLines',\n 'xType', 'yAxisTitle', 'y2AxisTitle', 'xAxisTitle', 'yScale', 'y2Scale', 'xAxis', 'yAxis', 'y2Axis',\n 'title', 'subtitle', 'caption', 'referenceBands', 'nullAs', 'decimate', 'dataLabels', 'annotations',\n 'seriesLabels', 'responsive', 'style', 'drawings', 'lastPriceLine', 'patternFallback', 'calendarValues',\n 'calendarStart', 'calendarEnd', 'gaugeValue', 'gaugeMin', 'gaugeMax', 'gaugeTarget', 'gaugeRanges',\n 'gaugeUnit', 'treemap', 'sankeyNodes', 'sankeyLinks', 'waterfallTotals', 'waterfallColors', 'candleColors',\n 'candleStyle', 'funnelShape', 'stackOffset', 'binEdges', 'tree', 'bulletRanges', 'colorScale',\n]\n```\n\n### `const KNOWN_SERIES_KEYS`\n\nEvery key a `ChartSeries` may carry.\n\n```ts\nexport const KNOWN_SERIES_KEYS: ReadonlyArray<keyof ChartSeries> = [\n 'label', 'values', 'color', 'type', 'ohlc', 'volumes', 'boxes', 'errors', 'axis', 'points', 'rowIds',\n 'overlay', 'overlayColor', 'pattern', 'smooth', 'upperValues', 'lowerValues', 'marker', 'markers', 'colors',\n 'stack', 'strokeWidth', 'dash', 'opacity', 'visible', 'gradient', 'step', 'connectNulls', 'nullAs',\n 'lowValues', 'targets',\n]\n```\n\n### `function nearestKey`\n\nThe known key closest to `key`, when it is close enough to be a typo.\n\n```ts\nexport function nearestKey(key: string, known: ReadonlyArray<string>): string | null {\n let best: string | null = null\n let bestD = Infinity\n for (const k of known) {\n const d = distance(key.toLowerCase(), k.toLowerCase())\n if (d < bestD) { bestD = d; best = k }\n }\n return best !== null && bestD <= Math.max(1, Math.floor(key.length / 3)) ? best : null\n}\n```\n\n### `function warnChartSpec`\n\nLog every finding of a spec once per spec object, the way `SvChart` does in\ndevelopment, and return them. A spec already reported (by any chart) is\nskipped, so a spec shared by ten charts warns once.\n\n```ts\nexport function warnChartSpec(spec: unknown, log: (line: string) => void = (line) => console.warn(line)): ChartDiagnostic[] {\n if (typeof spec !== 'object' || spec === null || warnedSpecs.has(spec)) return []\n warnedSpecs.add(spec)\n const out = validateChartSpec(spec)\n for (const d of out) log(`[SvChart] ${d.path ? d.path + ': ' : ''}${d.message}`)\n return out\n}\n```\n\n### `function validateChartSpec`\n\nCheck a spec and return every finding, an empty array for a clean one. Never\nthrows: a spec that is not even an object comes back as one error.\n\n```ts\nexport function validateChartSpec(spec: unknown): ChartDiagnostic[] {\n const out: ChartDiagnostic[] = []\n const err = (code: string, path: string, message: string) => out.push({ code: `chart/${code}`, path, message, severity: 'error' })\n const warn = (code: string, path: string, message: string) => out.push({ code: `chart/${code}`, path, message, severity: 'warning' })\n if (!isObj(spec)) {\n err('not-an-object', '', 'a ChartSpec is an object with type, categories and series')\n return out\n }\n const s = spec as Record<string, unknown>\n\n // ---- Keys and type -------------------------------------------------------\n for (const k of Object.keys(s)) {\n if ((KNOWN_SPEC_KEYS as ReadonlyArray<string>).includes(k)) continue\n const near = nearestKey(k, KNOWN_SPEC_KEYS)\n warn('unknown-key', k, near ? `unknown field \"${k}\"; did you mean \"${near}\"?` : `unknown field \"${k}\" is ignored`)\n }\n const type = s.type\n if (typeof type !== 'string' || !(CHART_TYPES as ReadonlyArray<string>).includes(type)) {\n const near = typeof type === 'string' ? nearestKey(type, CHART_TYPES) : null\n err('unknown-type', 'type', near ? `unknown chart type \"${String(type)}\"; did you mean \"${near}\"?` : `unknown chart type \"${String(type)}\"`)\n }\n const categories = Array.isArray(s.categories) ? (s.categories as unknown[]) : null\n if (!categories) err('categories', 'categories', 'categories must be an array of labels')\n const n = categories?.length ?? 0\n const series = Array.isArray(s.series) ? (s.series as unknown[]) : null\n if (!series) err('series', 'series', 'series must be an array')\n\n // ---- Series ----------------------------------------------------------------\n const fixedLength = typeof type === 'string' && !FREE_LENGTH_TYPES.has(type)\n series?.forEach((sr, i) => {\n const p = `series[${i}]`\n if (!isObj(sr)) { err('series-shape', p, 'a series is an object with label and values'); return }\n for (const k of Object.keys(sr)) {\n if ((KNOWN_SERIES_KEYS as ReadonlyArray<string>).includes(k)) continue\n const near = nearestKey(k, KNOWN_SERIES_KEYS)\n warn('unknown-series-key', `${p}.${k}`, near ? `unknown series field \"${k}\"; did you mean \"${near}\"?` : `unknown series field \"${k}\" is ignored`)\n }\n if (typeof sr.label !== 'string') warn('series-label', `${p}.label`, 'a series wants a string label; the legend and tooltip name it')\n if (!Array.isArray(sr.values)) { err('series-values', `${p}.values`, 'values must be an array of numbers'); return }\n const values = sr.values as unknown[]\n if (fixedLength && categories && values.length !== n && !(sr.points && values.length === 0)) {\n err('series-length', `${p}.values`, `${values.length} values for ${n} categories; they run in parallel`)\n }\n for (const key of PER_CATEGORY) {\n if (key === 'values') continue\n const arr = sr[key]\n if (arr === undefined) continue\n if (!Array.isArray(arr)) { err('series-array', `${p}.${key}`, `${key} must be an array parallel to values`); continue }\n if (fixedLength && arr.length !== values.length) err('series-length', `${p}.${key}`, `${key} has ${arr.length} entries for ${values.length} values; they run in parallel`)\n }\n if (sr.type !== undefined && (typeof sr.type !== 'string' || !SERIES_TYPES.has(sr.type))) err('series-type', `${p}.type`, `unknown series type \"${String(sr.type)}\"`)\n if (sr.axis !== undefined && sr.axis !== 'left' && sr.axis !== 'right') err('series-axis', `${p}.axis`, `axis is 'left' or 'right', not \"${String(sr.axis)}\"`)\n if (sr.stack !== undefined) {\n const kind = (sr.type as string | undefined) ?? type\n if (kind !== 'bar' && kind !== 'area') warn('stack-kind', `${p}.stack`, 'stack groups apply to bar and area series; ignored here')\n }\n if (sr.overlay !== undefined && (typeof sr.overlay !== 'string' || !OVERLAY_RE.test(sr.overlay))) err('overlay', `${p}.overlay`, `unknown overlay \"${String(sr.overlay)}\"; expected linear, poly:N, exp, log, power, sma:N, ema:N, wma:N, bb:N:K or vwap`)\n if (Array.isArray(sr.ohlc)) {\n ;(sr.ohlc as unknown[]).forEach((b, j) => {\n if (b === null || b === undefined) return\n if (!isObj(b) || !isNum(b.o) || !isNum(b.h) || !isNum(b.l) || !isNum(b.c)) err('ohlc-shape', `${p}.ohlc[${j}]`, 'an OHLC bar is { o, h, l, c } or null')\n else if (b.l > b.h) err('ohlc-range', `${p}.ohlc[${j}]`, `low ${b.l} is above high ${b.h}`)\n })\n }\n if (Array.isArray(sr.boxes)) {\n ;(sr.boxes as unknown[]).forEach((b, j) => {\n if (b === null || b === undefined) return\n if (!isObj(b) || !isNum(b.min) || !isNum(b.q1) || !isNum(b.median) || !isNum(b.q3) || !isNum(b.max)) err('box-shape', `${p}.boxes[${j}]`, 'a box is { min, q1, median, q3, max } or null')\n else if (b.q1 > b.median || b.median > b.q3) err('box-order', `${p}.boxes[${j}]`, 'a box wants q1 <= median <= q3')\n })\n }\n if (Array.isArray(sr.points)) {\n ;(sr.points as unknown[]).forEach((pt, j) => {\n if (!isObj(pt) || !isNum(pt.x) || !isNum(pt.y)) err('point-shape', `${p}.points[${j}]`, 'a scatter point is { x, y, r?, label? }')\n })\n }\n })\n\n // ---- Axes ----------------------------------------------------------------\n for (const key of ['xAxis', 'yAxis', 'y2Axis'] as const) {\n const ax = s[key]\n if (ax === undefined) continue\n if (!isObj(ax)) { err('axis-shape', key, `${key} must be an object`); continue }\n if (isNum(ax.min) && isNum(ax.max) && ax.min >= ax.max) err('axis-range', `${key}.min`, `min ${ax.min} is not below max ${ax.max}`)\n if (ax.scale === 'log' && isNum(ax.min) && ax.min <= 0) err('axis-log-min', `${key}.min`, 'a log axis cannot start at or below zero')\n if (ax.scale === 'log' && key === 'xAxis' && ax.type !== undefined && ax.type !== 'number') warn('axis-log-x', `${key}.scale`, \"a log x axis needs type: 'number'\")\n if (ax.tickCount !== undefined && (!isNum(ax.tickCount) || ax.tickCount <= 0)) err('axis-ticks', `${key}.tickCount`, 'tickCount must be a positive number')\n if (ax.labelRotation !== undefined && ax.labelRotation !== 'auto' && !isNum(ax.labelRotation)) err('axis-rotation', `${key}.labelRotation`, \"labelRotation is a number of degrees or 'auto'\")\n if (ax.scale !== undefined && ax.scale !== 'linear' && ax.scale !== 'log') err('axis-scale', `${key}.scale`, `scale is 'linear' or 'log', not \"${String(ax.scale)}\"`)\n }\n\n // ---- Spec-level shapes -----------------------------------------------------\n if (s.stacked100 && typeof type === 'string' && type !== 'bar' && type !== 'area') warn('stacked100-kind', 'stacked100', 'stacked100 applies to bar and area charts; ignored here')\n if (s.innerRadius !== undefined && (!isNum(s.innerRadius) || s.innerRadius < 0 || s.innerRadius > 1)) err('inner-radius', 'innerRadius', 'innerRadius is a fraction 0..1 of the pie radius')\n if (Array.isArray(s.categoryGroups) && categories) {\n const span = (s.categoryGroups as Array<{ span?: unknown }>).reduce((a, g) => a + (isObj(g) && isNum(g.span) ? g.span : 0), 0)\n if (span !== n) err('category-groups', 'categoryGroups', `the group spans add up to ${span}, not the ${n} categories`)\n }\n if (Array.isArray(s.binEdges) && categories && (s.binEdges as unknown[]).length !== n + 1) err('bin-edges', 'binEdges', `binEdges wants ${n + 1} edges for ${n} bins`)\n if (Array.isArray(s.waterfallTotals) && categories && (s.waterfallTotals as unknown[]).length !== n) err('waterfall-totals', 'waterfallTotals', `waterfallTotals has ${(s.waterfallTotals as unknown[]).length} flags for ${n} categories`)\n if (Array.isArray(s.responsive)) {\n ;(s.responsive as unknown[]).forEach((r, i) => {\n const p = `responsive[${i}]`\n if (!isObj(r)) { err('responsive-shape', p, 'a rule is { maxWidth?, minWidth?, maxHeight?, spec?, legend? }'); return }\n if (!isNum(r.maxWidth) && !isNum(r.minWidth) && !isNum(r.maxHeight)) warn('responsive-size', p, 'a rule with no maxWidth, minWidth or maxHeight always applies')\n if (isObj(r.spec)) {\n for (const k of ['width', 'height', 'responsive']) if (k in r.spec) warn('responsive-size-key', `${p}.spec.${k}`, `${k} in a responsive rule is ignored; a rule cannot change the size`)\n }\n })\n }\n // Anchors on the category axis that name no category.\n if (categories && typeof type === 'string' && !FREE_LENGTH_TYPES.has(type)) {\n const known = new Set(categories.map(String))\n const isTimeOrNumber = (s.xType ?? (isObj(s.xAxis) ? s.xAxis.type : undefined)) as string | undefined\n const anchored = isTimeOrNumber === 'time' || isTimeOrNumber === 'number'\n const check = (list: unknown, path: string, valueOf: (item: Record<string, unknown>) => unknown) => {\n if (!Array.isArray(list) || anchored) return\n list.forEach((item, i) => {\n if (!isObj(item)) return\n const v = valueOf(item)\n if (typeof v === 'string' && !known.has(v)) warn('unknown-category', `${path}[${i}]`, `\"${v}\" is not one of the categories, so it has no place on the axis`)\n })\n }\n check(s.annotations, 'annotations', (a) => (isObj(a.at) ? a.at.category : undefined))\n check(Array.isArray(s.referenceLines) ? (s.referenceLines as unknown[]).filter((r) => isObj(r) && r.axis === 'x') : [], 'referenceLines', (r) => r.value)\n // On a time or number axis a drawing's x is a timestamp or a number the\n // axis places itself; the tools write one for every pointer position, so\n // matching those against the category list warned on every drawing.\n if (Array.isArray(s.drawings) && !anchored) {\n ;(s.drawings as unknown[]).forEach((d, i) => {\n if (!isObj(d) || !Array.isArray(d.points)) return\n ;(d.points as unknown[]).forEach((pt, j) => {\n if (isObj(pt) && typeof pt.x === 'string' && !known.has(pt.x)) warn('unknown-category', `drawings[${i}].points[${j}].x`, `\"${pt.x}\" is not one of the categories`)\n })\n })\n }\n }\n return out\n}\n```\n"
7996
+ "markdown": "# `@svgrid/grid` · `chart-validate.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-validate.ts`.\n\n### `type ChartDiagnostic`\n\nOne finding of {@link validateChartSpec}.\n\n```ts\nexport type ChartDiagnostic = {\n /** A stable rule id, `chart/<rule>`. */\n code: string\n /** The field's path in the spec, like `series[1].values` or `yAxis.min`. */\n path: string\n message: string\n /** `error`: will not draw as intended. `warning`: ignored, or a likely slip. */\n severity: 'error' | 'warning'\n}\n```\n\n### `const CHART_TYPES`\n\nEvery `ChartType` the engine draws.\n\n```ts\nexport const CHART_TYPES: ReadonlyArray<ChartType> = [\n 'bar', 'line', 'area', 'pie', 'scatter', 'heatmap', 'waterfall', 'funnel', 'radar', 'calendar', 'gauge',\n 'treemap', 'sankey', 'candlestick', 'ohlc', 'boxplot', 'histogram', 'range-bar', 'range-area', 'lollipop',\n 'dumbbell', 'pareto', 'stream', 'sunburst', 'radial-bar', 'radial-column', 'nightingale', 'chord', 'bullet',\n]\n```\n\n### `const KNOWN_SPEC_KEYS`\n\nEvery top-level key a `ChartSpec` may carry.\n\n```ts\nexport const KNOWN_SPEC_KEYS: ReadonlyArray<keyof ChartSpec> = [\n 'type', 'categories', 'series', 'width', 'height', 'palette', 'categoryColors', 'valueFormat', 'locale',\n 'currency', 'categoryGroups', 'stacked', 'stacked100', 'orientation', 'innerRadius', 'referenceLines',\n 'xType', 'yAxisTitle', 'y2AxisTitle', 'xAxisTitle', 'yScale', 'y2Scale', 'xAxis', 'yAxis', 'y2Axis',\n 'title', 'subtitle', 'caption', 'referenceBands', 'nullAs', 'decimate', 'dataLabels', 'annotations',\n 'seriesLabels', 'responsive', 'style', 'drawings', 'lastPriceLine', 'patternFallback', 'calendarValues',\n 'calendarStart', 'calendarEnd', 'gaugeValue', 'gaugeMin', 'gaugeMax', 'gaugeTarget', 'gaugeRanges',\n 'gaugeUnit', 'treemap', 'sankeyNodes', 'sankeyLinks', 'waterfallTotals', 'waterfallColors', 'candleColors',\n 'candleStyle', 'funnelShape', 'stackOffset', 'binEdges', 'tree', 'bulletRanges', 'colorScale',\n]\n```\n\n### `const KNOWN_SERIES_KEYS`\n\nEvery key a `ChartSeries` may carry.\n\n```ts\nexport const KNOWN_SERIES_KEYS: ReadonlyArray<keyof ChartSeries> = [\n 'label', 'values', 'color', 'type', 'ohlc', 'volumes', 'boxes', 'errors', 'axis', 'points', 'rowIds',\n 'overlay', 'overlayColor', 'pattern', 'smooth', 'upperValues', 'lowerValues', 'marker', 'markers', 'colors',\n 'stack', 'strokeWidth', 'dash', 'opacity', 'visible', 'gradient', 'step', 'connectNulls', 'nullAs',\n 'lowValues', 'targets',\n]\n```\n\n### `function nearestKey`\n\nThe known key closest to `key`, when it is close enough to be a typo.\n\n```ts\nexport function nearestKey(key: string, known: ReadonlyArray<string>): string | null\n```\n\n### `function warnChartSpec`\n\nLog every finding of a spec once per spec object, the way `SvChart` does in\ndevelopment, and return them. A spec already reported (by any chart) is\nskipped, so a spec shared by ten charts warns once.\n\n```ts\nexport function warnChartSpec(spec: unknown, log: (line: string) => void = (line) => console.warn(line)): ChartDiagnostic[]\n```\n\n### `function validateChartSpec`\n\nCheck a spec and return every finding, an empty array for a clean one. Never\nthrows: a spec that is not even an object comes back as one error.\n\n```ts\nexport function validateChartSpec(spec: unknown): ChartDiagnostic[]\n```\n"
7926
7997
  },
7927
7998
  {
7928
7999
  "slug": "reference/auto/svgrid-grid-chart-zoom",
7929
8000
  "path": "docs/reference/auto/svgrid-grid-chart-zoom.md",
7930
8001
  "title": "@svgrid/grid · chart-zoom.ts",
7931
8002
  "section": "API reference",
7932
- "markdown": "# `@svgrid/grid` · `chart-zoom.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-zoom.ts`.\n\n### `function wheelWindow`\n\nZoom the window in or out around an anchor category, keeping the anchor at\nthe same relative position. `factor < 1` zooms in, `> 1` out; a null window\nmeans the whole axis. Never narrower than 2 categories.\n\n```ts\nexport function wheelWindow(win: ChartZoomWindow | null, n: number, anchor: number, factor: number): ChartZoomWindow | null {\n if (n <= 2) return null\n const i0 = win ? win.i0 : 0\n const i1 = win ? win.i1 : n - 1\n const span = i1 - i0 + 1\n const next = Math.max(2, Math.min(n, Math.round(span * factor)))\n if (next === span) return win\n // Where the anchor sits inside the window, 0..1, so it stays put.\n const rel = span > 1 ? (Math.max(i0, Math.min(i1, anchor)) - i0) / (span - 1) : 0.5\n let a = Math.round(anchor - rel * (next - 1))\n a = Math.max(0, Math.min(n - next, a))\n return clampWindow(a, a + next - 1, n)\n}\n```\n\n### `function panWindow`\n\nSlide the window by `delta` categories, clamped to the axis.\n\n```ts\nexport function panWindow(win: ChartZoomWindow | null, n: number, delta: number): ChartZoomWindow | null {\n if (!win || !delta) return win\n const span = win.i1 - win.i0\n let a = win.i0 + Math.round(delta)\n a = Math.max(0, Math.min(n - 1 - span, a))\n return clampWindow(a, a + span, n)\n}\n```\n\n### `function pinchWindow`\n\nResize the window by a pinch: `scale > 1` spreads the fingers (zoom in),\naround the category under the pinch midpoint.\n\n```ts\nexport function pinchWindow(win: ChartZoomWindow | null, n: number, midpoint: number, scale: number): ChartZoomWindow | null {\n if (!Number.isFinite(scale) || scale <= 0) return win\n return wheelWindow(win, n, midpoint, 1 / scale)\n}\n```\n\n### `type ChartRangePreset`\n\nThe range presets a time axis offers.\n\n```ts\nexport type ChartRangePreset = '1W' | '1M' | '3M' | '6M' | 'YTD' | '1Y' | 'All' | { label: string; days?: number; from?: string; to?: string }\n```\n\n### `function presetWindow`\n\nThe window a preset selects on a time / ordinal-time axis whose categories\nparse as dates: the last N days up to the latest category, the year to\ndate, or an explicit from / to. `'All'` (and a preset nothing matches)\nreturns null, the whole axis. `now` defaults to the last category, which is\nwhat \"1M\" means on a chart that stops last quarter.\n\n```ts\nexport function presetWindow(categories: ReadonlyArray<string>, preset: ChartRangePreset, now?: number): ChartZoomWindow | null {\n const n = categories.length\n if (!n) return null\n const times = categories.map((c) => Date.parse(c))\n const last = [...times].reverse().find(Number.isFinite)\n if (last == null) return null\n const end = now ?? last\n const DAY = 86_400_000\n let from: number\n let to = end\n if (typeof preset === 'object') {\n if (preset.from) from = Date.parse(preset.from)\n else if (preset.days) from = end - preset.days * DAY\n else return null\n if (preset.to) to = Date.parse(preset.to)\n } else {\n switch (preset) {\n case '1W': from = end - 7 * DAY; break\n case '1M': from = shiftMonths(end, -1); break\n case '3M': from = shiftMonths(end, -3); break\n case '6M': from = shiftMonths(end, -6); break\n case '1Y': from = shiftMonths(end, -12); break\n case 'YTD': { const d = new Date(end); from = Date.UTC(d.getUTCFullYear(), 0, 1); break }\n default: return null\n }\n }\n if (!Number.isFinite(from) || !Number.isFinite(to)) return null\n let i0 = -1\n let i1 = -1\n for (let i = 0; i < n; i += 1) {\n const t = times[i]!\n if (!Number.isFinite(t)) continue\n if (t >= from && i0 < 0) i0 = i\n if (t <= to) i1 = i\n }\n if (i0 < 0 || i1 < 0 || i1 < i0) return null\n return clampWindow(i0, i1, n)\n}\n```\n\n### `function nearestIndexByTime`\n\nThe category whose date is nearest to `t`, for syncing a hover between two\ncharts whose categories differ. Categories that do not parse are skipped;\nreturns -1 when none do.\n\n```ts\nexport function nearestIndexByTime(categories: ReadonlyArray<string>, t: number): number {\n let best = -1\n let bestD = Infinity\n for (let i = 0; i < categories.length; i += 1) {\n const ct = Date.parse(categories[i]!)\n if (!Number.isFinite(ct)) continue\n const d = Math.abs(ct - t)\n if (d < bestD) { bestD = d; best = i }\n }\n return best\n}\n```\n"
8003
+ "markdown": "# `@svgrid/grid` · `chart-zoom.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart-zoom.ts`.\n\n### `function wheelWindow`\n\nZoom the window in or out around an anchor category, keeping the anchor at\nthe same relative position. `factor < 1` zooms in, `> 1` out; a null window\nmeans the whole axis. Never narrower than 2 categories.\n\n```ts\nexport function wheelWindow(win: ChartZoomWindow | null, n: number, anchor: number, factor: number): ChartZoomWindow | null\n```\n\n### `function panWindow`\n\nSlide the window by `delta` categories, clamped to the axis.\n\n```ts\nexport function panWindow(win: ChartZoomWindow | null, n: number, delta: number): ChartZoomWindow | null\n```\n\n### `function pinchWindow`\n\nResize the window by a pinch: `scale > 1` spreads the fingers (zoom in),\naround the category under the pinch midpoint.\n\n```ts\nexport function pinchWindow(win: ChartZoomWindow | null, n: number, midpoint: number, scale: number): ChartZoomWindow | null\n```\n\n### `type ChartRangePreset`\n\nThe range presets a time axis offers.\n\n```ts\nexport type ChartRangePreset = '1W' | '1M' | '3M' | '6M' | 'YTD' | '1Y' | 'All' | { label: string; days?: number; from?: string; to?: string }\n```\n\n### `function presetWindow`\n\nThe window a preset selects on a time / ordinal-time axis whose categories\nparse as dates: the last N days up to the latest category, the year to\ndate, or an explicit from / to. `'All'` (and a preset nothing matches)\nreturns null, the whole axis. `now` defaults to the last category, which is\nwhat \"1M\" means on a chart that stops last quarter.\n\n```ts\nexport function presetWindow(categories: ReadonlyArray<string>, preset: ChartRangePreset, now?: number): ChartZoomWindow | null\n```\n\n### `function nearestIndexByTime`\n\nThe category whose date is nearest to `t`, for syncing a hover between two\ncharts whose categories differ. Categories that do not parse are skipped;\nreturns -1 when none do.\n\n```ts\nexport function nearestIndexByTime(categories: ReadonlyArray<string>, t: number): number\n```\n"
7933
8004
  },
7934
8005
  {
7935
8006
  "slug": "reference/auto/svgrid-grid-chart",
7936
8007
  "path": "docs/reference/auto/svgrid-grid-chart.md",
7937
8008
  "title": "@svgrid/grid · chart.ts",
7938
8009
  "section": "API reference",
7939
- "markdown": "# `@svgrid/grid` · `chart.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart.ts`.\n\n### `function chartStyleVars`\n\nThe CSS custom properties `spec.style` sets on the chart's host, as one\ninline style string (empty when nothing is set). `background` becomes the\nchart's `--sg-bg` (exports read it as the page colour), `textColor` the\ntext tokens, `gridColor` the border token, `fontSize` a scale every label\nmultiplies (12px is 1), and `fontFamily` the host's font.\n\n```ts\nexport function chartStyleVars(style: ChartStyle | undefined): string {\n if (!style) return ''\n const out: string[] = []\n if (style.background) out.push(`--sg-chart-bg:${style.background}`, `--sg-bg:${style.background}`)\n if (style.textColor) out.push(`--sg-fg:${style.textColor}`, `--sg-muted:${style.textColor}`)\n if (style.gridColor) out.push(`--sg-border:${style.gridColor}`)\n if (style.fontSize && Number.isFinite(style.fontSize) && style.fontSize > 0) out.push(`--sg-chart-font-scale:${Math.round((style.fontSize / 12) * 1000) / 1000}`)\n if (style.fontFamily) out.push(`font-family:${style.fontFamily}`)\n return out.join(';')\n}\n```\n\n### `function matchResponsiveRules`\n\nThe responsive rules that apply at a rendered size, in spec order. Pure:\n`SvChart` uses it for the legend field, {@link resolveResponsive} for the\nspec patches.\n\n```ts\nexport function matchResponsiveRules(rules: ChartResponsiveRule[] | undefined, width: number, height: number): ChartResponsiveRule[] {\n if (!rules?.length) return []\n return rules.filter(\n (r) =>\n (r.maxWidth == null || width <= r.maxWidth) &&\n (r.minWidth == null || width >= r.minWidth) &&\n (r.maxHeight == null || height <= r.maxHeight),\n )\n}\n```\n\n### `function resolveResponsive`\n\nApply `spec.responsive` for a rendered size: every matching rule's `spec`\nis merged over the input in order (later wins), the three axis objects one\nlevel deep. Returns the input itself when nothing matches, so callers can\ncompare by identity. `width`, `height` and `responsive` in a rule are\nignored; the size is the caller's.\n\n```ts\nexport function resolveResponsive(spec: ChartSpec, width: number, height: number): ChartSpec {\n const hits = matchResponsiveRules(spec.responsive, width, height)\n if (!hits.length) return spec\n let out: ChartSpec = spec\n for (const rule of hits) {\n if (!rule.spec) continue\n const { width: _w, height: _h, responsive: _r, ...patch } = rule.spec\n const merged: ChartSpec = { ...out, ...patch }\n for (const k of ['xAxis', 'yAxis', 'y2Axis'] as const) {\n if (patch[k]) merged[k] = { ...(out[k] ?? {}), ...patch[k] }\n }\n out = merged\n }\n return out\n}\n```\n\n### `function buildChart`\n\nLay out a {@link ChartSpec} into renderable {@link ChartGeometry} - scales,\nticks, and the position of every bar, line, slice and dot. Pure: no DOM, so\nit runs during SSR and can be unit-tested directly.\n\n```ts\nexport function buildChart(input: ChartSpec, theme: 'light' | 'dark' = 'light'): ChartGeometry {\n const width = input.width ?? 520\n const height = input.height ?? 300\n // Size rules first, so every family sees the patched spec.\n const spec = resolveResponsive(input, width, height)\n // A pareto is a bar chart with a cumulative-share line on the right axis,\n // sorted by value. Build that spec and lay it out as the combo it is.\n if (spec.type === 'pareto') return buildChart(paretoSpec(spec), theme)\n const palette = spec.palette ?? DEFAULT_PALETTE\n\n const stacked = !!(spec.stacked || spec.stacked100)\n const series: ResolvedSeries[] = spec.series.map((s, i) => ({\n ...s,\n // A null is a gap unless the series (or the spec) says it is a zero. Done\n // here, once, so every family and every overlay sees the same numbers.\n values: (s.nullAs ?? spec.nullAs) === 'zero' ? s.values.map((v) => (Number.isFinite(v) ? v : 0)) : s.values,\n color: s.color ?? palette[i % palette.length]!,\n kind: kindOf(s, spec.type),\n axis: s.axis ?? 'left',\n }))\n const frame = chartFrame(spec, width, height)\n const axes = resolveAxes(spec)\n const legend: ChartLegendItem[] = series.map((s) => ({ label: s.label, color: s.color }))\n\n const empty: ChartGeometry = {\n type: spec.type,\n width,\n height,\n plot: { x: 0, y: 0, w: width, h: height },\n axes: null,\n frame,\n grid: { x: false, y: false },\n referenceBands: [],\n bars: [],\n candles: [],\n boxes: [],\n errorBars: [],\n stems: [],\n arcs: [],\n chordRibbons: [],\n bullets: [],\n drawings: [],\n seriesLabels: [],\n polarAxes: [],\n polarRings: [],\n lines: [],\n slices: [],\n yTicks: [],\n y2Ticks: [],\n hasRightAxis: false,\n xTicks: [],\n categoryGroupTicks: [],\n xLabelRotated: false,\n xLabelAngle: 0,\n legend,\n donut: null,\n referenceLines: [],\n scatterPoints: [],\n orientation: 'vertical',\n valueTicks: [],\n catTicks: [],\n referenceLinesV: [],\n overlays: [],\n annotations: [],\n heatmapCells: [],\n heatmapRowTicks: [],\n heatmapColTicks: [],\n heatmapLegend: [],\n funnelSegments: [],\n radarRings: [],\n radarAxes: [],\n radarSeries: [],\n radarCenter: null,\n treemapCells: [],\n calendarCells: [],\n calendarMonthTicks: [],\n calendarLegend: [],\n gauge: null,\n sankeyNodes: [],\n sankeyLinks: [],\n }\n\n const ctx: LayoutCtx = { spec, theme, width, height, palette, stacked, series, legend, empty, frame, axes }\n if (spec.type === 'waterfall') return layoutWaterfall(ctx)\n if (spec.type === 'funnel') return layoutFunnel(ctx)\n if (spec.type === 'radar') return layoutRadar(ctx)\n if (spec.type === 'calendar') return layoutCalendar(ctx)\n if (spec.type === 'gauge') return layoutGauge(ctx)\n if (spec.type === 'treemap') return layoutTreemap(ctx)\n if (spec.type === 'sankey') return layoutSankey(ctx)\n if (spec.type === 'heatmap') return layoutHeatmap(ctx)\n if (spec.type === 'pie') return layoutPie(ctx)\n if (spec.type === 'scatter') return layoutScatter(ctx)\n if (spec.type === 'sunburst') return layoutSunburst(ctx)\n if (spec.type === 'radial-bar') return layoutRadialBar(ctx)\n if (spec.type === 'radial-column' || spec.type === 'nightingale') return layoutRadialColumn(ctx)\n if (spec.type === 'chord') return layoutChord(ctx)\n if (spec.type === 'bullet') return layoutBullet(ctx)\n\n // ---- Horizontal bars ----------------------------------------------------\n // Categories run down the left, bars grow rightward. Bars-only (no combo).\n const horizontal =\n spec.orientation === 'horizontal' && spec.type !== 'histogram' && series.length > 0 && series.every((s) => s.kind === 'bar')\n if (horizontal) return layoutHorizontalBars(ctx)\n return layoutCartesian(ctx)\n}\n```\n\n### `function sliceChartWindow`\n\nNarrow a spec to the category window `[lo, hi]`, keeping every\ncategory-parallel array in step.\n\nThis is the zoom / brush slice. It lives here rather than in the renderer\nbecause getting it wrong is a MODEL bug, not a paint bug, and it was wrong:\nthe component used to slice `categories`, `values` and `rowIds` by hand and\nspread the rest of the series through untouched. `upperValues` and\n`lowerValues` therefore kept their full length, the equality guard on the\nconfidence band (see `buildChart`) stopped matching, and the band silently\ndisappeared the moment anyone zoomed.\n\nThe lesson generalises: every array here is indexed by category, so each one\nadded in future has to be sliced too. Keeping them in one function is what\nmakes that a single place to remember rather than a scattered convention.\n\n```ts\nexport function sliceChartWindow(spec: ChartSpec, lo: number, hi: number): ChartSpec {\n const from = Math.max(0, lo)\n const to = Math.min(spec.categories.length - 1, hi)\n if (to < from) return { ...spec, categories: [], series: spec.series.map((s) => ({ ...s, values: [] })) }\n // EVERY per-category array on a series has to be cut here, not just the\n // ones that existed when this function was written. A missed one does not\n // throw: the geometry keeps indexing the full-length array against the\n // sliced categories, so marks land at the wrong x or off the plot entirely.\n // `upperValues` / `lowerValues` were missed once and silently dropped the\n // confidence band on zoom; `ohlc` was missed the same way. The list of those\n // arrays now lives in one constant (PER_CATEGORY_SERIES_KEYS) shared with\n // decimation, and `pickCategories` is the one function that applies it.\n const indices: number[] = new Array(to - from + 1)\n for (let i = from; i <= to; i += 1) indices[i - from] = i\n return pickCategories(spec, indices)\n}\n```\n\n### `function rowsToChartSpec`\n\nAggregate flat rows into a chart spec. Group by a category field, reduce a\nvalue field per group. Three multi-series shapes:\n - `value: 'revenue'` -> one series\n - `value: ['revenue','cost']` -> one series per value field\n - `value: 'sales', series: 'region'` -> pivot: one series per distinct\n value of the `series` field\n\n```ts\nexport function rowsToChartSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n type: ChartType\n category: keyof T & string\n value: (keyof T & string) | Array<keyof T & string>\n /** Pivot dimension: one series per distinct value of this field. */\n series?: keyof T & string\n /** How each group collapses to one number. Default `'sum'`. See\n * {@link ChartReducer} for the full list (min, max, median, p90, ...). */\n reduce?: ChartReducer\n /**\n * Group a date category by calendar unit instead of by exact value:\n * `'month'` files every row of March under `2026-03-01`. Categories come\n * out as ISO dates in chronological order and the spec's x axis is set to\n * `'ordinal-time'`, so the ticks read as dates. Rows whose category does\n * not parse as a date are dropped.\n */\n bucket?: ChartTimeBucket\n seriesLabel?: string\n width?: number\n height?: number\n stacked?: boolean\n stacked100?: boolean\n palette?: string[]\n /** Order categories. Defaults to insertion order (or value-desc when topN,\n * or chronological when bucketed). */\n sort?: 'value-desc' | 'value-asc' | 'category' | 'none'\n /** Keep only the top N categories; bucket the rest into \"Other\". */\n topN?: number\n /** Label for the bucketed remainder. Default \"Other\". */\n otherLabel?: string\n /** Field carrying each row's stable id. When set, the resulting spec's\n * series carry `rowIds` arrays so click handlers can drill back to\n * the source rows. */\n idField?: keyof T & string\n },\n): ChartSpec {\n const reduce: ChartReducer = opts.reduce ?? 'sum'\n const wantSamples = reducerNeedsSamples(reduce)\n const valueFields = Array.isArray(opts.value) ? opts.value : [opts.value]\n // The three original reducers run on a sum and a count; the rest keep every\n // observation, which is what a median or a percentile needs.\n const reduceCell = (cell: Cell) =>\n wantSamples\n ? reduceValues(cell.samples, reduce)\n : reduce === 'count' ? cell.count : reduce === 'avg' ? (cell.count ? cell.sum / cell.count : 0) : cell.sum\n\n const categories: string[] = []\n const catIndex = new Map<string, number>()\n const ensureCat = (key: string) => {\n let idx = catIndex.get(key)\n if (idx === undefined) {\n idx = categories.length\n catIndex.set(key, idx)\n categories.push(key)\n }\n return idx\n }\n\n // Series keyed by name -> per-category {sum,count,rowIds}.\n type Cell = { sum: number; count: number; rowIds: Array<string | number>; samples: number[] }\n const seriesMap = new Map<string, Cell[]>()\n const ensureSeries = (name: string) => {\n let arr = seriesMap.get(name)\n if (!arr) {\n arr = []\n seriesMap.set(name, arr)\n }\n return arr\n }\n const note = (cell: Cell, num: number, rowId: string | number | undefined) => {\n cell.sum += num\n cell.count += 1\n if (wantSamples) cell.samples.push(num)\n if (rowId !== undefined) cell.rowIds.push(rowId)\n }\n const fresh = (): Cell => ({ sum: 0, count: 0, rowIds: [], samples: [] })\n\n const trackIds = opts.idField !== undefined\n for (const row of rows) {\n const raw = row[opts.category]\n const cat = opts.bucket ? bucketStart(raw as string | number | Date, opts.bucket) : String(raw ?? '')\n if (opts.bucket && !cat) continue\n const ci = ensureCat(cat)\n const rowId = trackIds ? (row[opts.idField as keyof T] as string | number) : undefined\n if (opts.series) {\n const sName = String(row[opts.series] ?? '')\n const arr = ensureSeries(sName)\n const num = Number(row[valueFields[0]!])\n const cell = (arr[ci] ??= fresh())\n if (Number.isFinite(num)) note(cell, num, rowId)\n } else {\n for (const vf of valueFields) {\n const arr = ensureSeries(vf)\n const num = Number(row[vf])\n const cell = (arr[ci] ??= fresh())\n if (Number.isFinite(num)) note(cell, num, rowId)\n }\n }\n }\n\n const entries = [...seriesMap.entries()].map(([name, arr]) => ({\n label: opts.series ? name : opts.seriesLabel && valueFields.length === 1 ? opts.seriesLabel : name,\n values: categories.map((_, i) => reduceCell(arr[i] ?? fresh())),\n rowIds: trackIds\n ? categories.map((_, i) => (arr[i]?.rowIds ?? []).slice())\n : undefined,\n }))\n\n // ---- Sort + top-N -----------------------------------------------------\n const totals = categories.map((_, i) =>\n entries.reduce((sum, e) => sum + (Number.isFinite(e.values[i]!) ? e.values[i]! : 0), 0),\n )\n const sort = opts.sort ?? (opts.topN ? 'value-desc' : opts.bucket ? 'category' : 'none')\n const order = categories.map((_, i) => i)\n if (sort === 'value-desc') order.sort((a, b) => totals[b]! - totals[a]!)\n else if (sort === 'value-asc') order.sort((a, b) => totals[a]! - totals[b]!)\n else if (sort === 'category') order.sort((a, b) => categories[a]!.localeCompare(categories[b]!))\n\n let finalCategories: string[]\n let finalSeries: ChartSeries[]\n if (opts.topN && order.length > opts.topN) {\n const other = opts.otherLabel ?? 'Other'\n // A real category may already be called \"Other\" (a survey's own bucket,\n // a browser share's long tail). Two categories with one name is a\n // duplicate key the renderer cannot draw, so the tail folds INTO that\n // category rather than beside it: it is kept whether or not it made the\n // top N, and the rest is added to it.\n const own = order.find((i) => categories[i] === other)\n const keep = order.slice(0, opts.topN).filter((i) => i !== own)\n const rest = order.filter((i) => !keep.includes(i))\n finalCategories = keep.map((i) => categories[i]!).concat(other)\n finalSeries = entries.map((e) => ({\n label: e.label,\n values: keep\n .map((i) => e.values[i]!)\n .concat(rest.reduce((sum, i) => sum + (Number.isFinite(e.values[i]!) ? e.values[i]! : 0), 0)),\n rowIds: e.rowIds\n ? keep.map((i) => e.rowIds![i]!).concat([rest.flatMap((i) => e.rowIds![i] ?? [])])\n : undefined,\n }))\n } else {\n finalCategories = order.map((i) => categories[i]!)\n finalSeries = entries.map((e) => ({\n label: e.label,\n values: order.map((i) => e.values[i]!),\n rowIds: e.rowIds ? order.map((i) => e.rowIds![i]!) : undefined,\n }))\n }\n\n return {\n type: opts.type,\n categories: finalCategories,\n series: finalSeries,\n width: opts.width,\n height: opts.height,\n stacked: opts.stacked,\n stacked100: opts.stacked100,\n palette: opts.palette,\n ...(opts.bucket ? { xType: 'ordinal-time' as const } : {}),\n }\n}\n```\n\n### `function paretoSpec`\n\nThe bar-plus-line spec a pareto chart draws: categories sorted by value,\nbars for the values, and a cumulative-share line on the right axis pinned to\n0..100 with a reference line at `threshold` (default 80, the \"vital few\").\n`buildChart` calls this for `type: 'pareto'`; call it yourself to get at the\nspec, or pass a ready spec whose first series is the values.\n\n```ts\nexport function paretoSpec(spec: ChartSpec, threshold = 80): ChartSpec {\n const src = spec.series[0]\n if (!src) return { ...spec, type: 'bar' }\n const order = spec.categories.map((_, i) => i).sort((a, b) => (src.values[b] ?? 0) - (src.values[a] ?? 0))\n const sorted = pickCategories(spec, order)\n const values = sorted.series[0]!.values.map((v) => (Number.isFinite(v) ? Math.max(0, v) : 0))\n const total = values.reduce((a, b) => a + b, 0) || 1\n let cum = 0\n const share = values.map((v) => {\n cum += v\n return Math.round((cum / total) * 1000) / 10\n })\n return {\n ...sorted,\n type: 'bar',\n series: [\n { ...sorted.series[0]!, type: 'bar' },\n { label: 'Cumulative %', values: share, type: 'line', axis: 'right', marker: 'circle', color: sorted.series[0]!.overlayColor ?? '#ef4444' },\n ],\n y2Axis: { min: 0, max: 100, tickInterval: 25, formatter: (v) => `${v}%`, ...(spec.y2Axis ?? {}) },\n referenceLines: [\n ...(spec.referenceLines ?? []),\n ...(threshold > 0 ? [{ value: threshold, axis: 'right' as const, label: `${threshold}%`, dashed: true }] : []),\n ],\n }\n}\n```\n\n### `function rowsToHistogramSpec`\n\nBin one numeric field of the rows into a histogram spec. The categories are\nthe bin midpoints on a numeric axis and `binEdges` labels the edges, so the\nbars touch and the axis reads `0, 10, 20` rather than `5, 15, 25`.\n`series` splits the sample into one histogram per distinct value.\n\n```ts\nexport function rowsToHistogramSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n value: keyof T & string\n series?: keyof T & string\n seriesLabel?: string\n bins?: number\n binWidth?: number\n method?: 'sturges' | 'fd' | 'sqrt'\n min?: number\n max?: number\n palette?: string[]\n width?: number\n height?: number\n },\n): ChartSpec {\n const all = rows.map((r) => Number(r[opts.value])).filter(Number.isFinite)\n // Bin the whole sample once so every split shares the same edges.\n const bins = binValues(all, { bins: opts.bins, binWidth: opts.binWidth, method: opts.method, min: opts.min, max: opts.max })\n const groups: Array<{ label: string; rows: ReadonlyArray<T> }> = opts.series\n ? [...new Set(rows.map((r) => String(r[opts.series!] ?? '')))].map((g) => ({ label: g, rows: rows.filter((r) => String(r[opts.series!] ?? '') === g) }))\n : [{ label: opts.seriesLabel ?? String(opts.value), rows }]\n const series: ChartSeries[] = groups.map((g) => {\n const counts = new Array<number>(bins.counts.length).fill(0)\n const lo = bins.edges[0] ?? 0\n for (const r of g.rows) {\n const n = Number(r[opts.value])\n if (!Number.isFinite(n) || !bins.width) continue\n let i = Math.floor((n - lo) / bins.width)\n if (i >= counts.length) i = counts.length - 1\n if (i < 0) i = 0\n counts[i] = (counts[i] ?? 0) + 1\n }\n return { label: g.label, values: counts }\n })\n return {\n type: 'histogram',\n categories: bins.categories,\n series,\n binEdges: bins.edges,\n xType: 'number',\n ...(opts.palette ? { palette: opts.palette } : {}),\n ...(opts.width ? { width: opts.width } : {}),\n ...(opts.height ? { height: opts.height } : {}),\n }\n}\n```\n\n### `function rowsToRangeSpec`\n\nA range (floating) bar or area spec from rows: one row per category with a\nlow field and a high field, e.g. a day's low and high temperature, or a\nsalary band. `series` splits into one range per distinct value.\n\n```ts\nexport function rowsToRangeSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n type?: 'range-bar' | 'range-area'\n category: keyof T & string\n low: keyof T & string\n high: keyof T & string\n series?: keyof T & string\n seriesLabel?: string\n palette?: string[]\n width?: number\n height?: number\n },\n): ChartSpec {\n const cats: string[] = []\n const seen = new Set<string>()\n for (const r of rows) {\n const c = String(r[opts.category] ?? '')\n if (!seen.has(c)) { seen.add(c); cats.push(c) }\n }\n const names = opts.series\n ? [...new Set(rows.map((r) => String(r[opts.series!] ?? '')))]\n : [opts.seriesLabel ?? `${String(opts.low)} to ${String(opts.high)}`]\n const series: ChartSeries[] = names.map((name) => {\n const lows = new Array<number>(cats.length).fill(Number.NaN)\n const highs = new Array<number>(cats.length).fill(Number.NaN)\n for (const r of rows) {\n if (opts.series && String(r[opts.series] ?? '') !== name) continue\n const i = cats.indexOf(String(r[opts.category] ?? ''))\n const lo = Number(r[opts.low])\n const hi = Number(r[opts.high])\n if (i < 0 || !Number.isFinite(lo) || !Number.isFinite(hi)) continue\n lows[i] = Math.min(lo, hi)\n highs[i] = Math.max(lo, hi)\n }\n return { label: name, values: highs, lowValues: lows }\n })\n return {\n type: opts.type ?? 'range-bar',\n categories: cats,\n series,\n ...(opts.palette ? { palette: opts.palette } : {}),\n ...(opts.width ? { width: opts.width } : {}),\n ...(opts.height ? { height: opts.height } : {}),\n }\n}\n```\n\n### `function specToTreemap`\n\nReshape an aggregated spec into a tree-map hierarchy.\n\nOne series gives a flat set of leaves. Several (a split-by) give two levels,\ncategory above series, which is the shape people expect from \"sales by\nregion, split by channel\".\n\n```ts\nexport function specToTreemap(spec: ChartSpec, rootName = 'Total'): TreeNode {\n const positive = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0)\n if (spec.series.length <= 1) {\n const s = spec.series[0]\n return {\n name: rootName,\n children: spec.categories\n .map((name, i) => ({ name, value: positive(s?.values[i]) }))\n .filter((n) => n.value > 0),\n }\n }\n return {\n name: rootName,\n children: spec.categories\n .map((name, i) => ({\n name,\n children: spec.series\n .map((s) => ({ name: s.label, value: positive(s.values[i]) }))\n .filter((n) => n.value > 0),\n }))\n .filter((n) => n.children.length > 0),\n }\n}\n```\n\n### `function specToCalendar`\n\nReshape an aggregated spec into calendar samples.\n\nCategories that do not parse as a date are dropped rather than rendered at\nepoch zero, which would put a stray cell in 1970 and rescale the whole year.\n\n```ts\nexport function specToCalendar(spec: ChartSpec): Array<{ date: string; value: number }> {\n const s = spec.series[0]\n const out: Array<{ date: string; value: number }> = []\n spec.categories.forEach((c, i) => {\n const t = Date.parse(c)\n if (!Number.isFinite(t)) return\n const v = s?.values[i]\n if (typeof v !== 'number' || !Number.isFinite(v)) return\n out.push({ date: new Date(t).toISOString().slice(0, 10), value: v })\n })\n return out\n}\n```\n\n### `function specToSankey`\n\nReshape a pivoted spec into sankey nodes and links.\n\nThe pivot `rowsToChartSpec` already performs is exactly an edge list read\nsideways: categories are sources, series are targets, and each cell is the\nflow between them. Zero cells and self-edges are dropped, the first because\na zero-width ribbon is not a flow and the second because the layout has no\nmeaningful place to put one.\n\n```ts\nexport function specToSankey(spec: ChartSpec): {\n nodes: Array<{ id: string; label?: string }>\n links: Array<{ source: string; target: string; value: number }>\n} {\n const links: Array<{ source: string; target: string; value: number }> = []\n const ids = new Set<string>()\n spec.categories.forEach((from, i) => {\n for (const s of spec.series) {\n const v = s.values[i]\n if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) continue\n // Sources and targets share a namespace, so a value appearing on both\n // sides would otherwise become one node with a cycle through it.\n const source = `from:${from}`\n const target = `to:${s.label}`\n if (source === target) continue\n ids.add(source)\n ids.add(target)\n links.push({ source, target, value: v })\n }\n })\n return {\n nodes: [...ids].map((id) => ({ id, label: id.slice(id.indexOf(':') + 1) })),\n links,\n }\n}\n```\n\n### `type ChartFormatState`\n\nWhat the grid panel's chart builder lets a reader change about the LOOK of\na chart, as plain data so it can be saved with the view and applied to the\nspec the panel derives on every data change. Every field is optional and\nadditive; an absent field leaves the derived spec alone. Series are keyed\nby label, so a per-series colour survives a re-sort of the categories.\n\n```ts\nexport type ChartFormatState = {\n title?: string\n subtitle?: string\n caption?: string\n /** Where the legend goes; `false` hides it. The panel reads this for the\n * component prop, it is not a spec field. */\n legend?: 'top' | 'bottom' | 'left' | 'right' | false\n xAxis?: { title?: string; gridLines?: boolean; labelRotation?: number | 'auto' }\n yAxis?: { min?: number | null; max?: number | null; title?: string; gridLines?: boolean; format?: ChartValueFormat }\n y2Axis?: { min?: number | null; max?: number | null; title?: string; gridLines?: boolean; format?: ChartValueFormat }\n /** Per-series overrides, keyed by series label. */\n series?: Record<string, {\n color?: string\n type?: 'bar' | 'line' | 'area'\n axis?: 'left' | 'right'\n marker?: ChartMarkerShape\n strokeWidth?: number\n dash?: string\n smooth?: boolean\n /** The stack group a bar or area joins; an empty string leaves the\n * group. See {@link ChartSeries.stack}. */\n stack?: string\n }>\n /** Where data labels sit; `null` hides them. */\n dataLabels?: 'inside' | 'outside' | 'top' | 'center' | null\n palette?: string[] | null\n /** Series names at the end of each line (`spec.seriesLabels`). */\n seriesLabels?: boolean\n /** The axis value pills on the crosshair. A component prop, like\n * `legend`: the panel reads it, the engine does not. */\n crosshairLabels?: boolean\n /** Below this rendered width in px the chart goes compact: no series or\n * data labels, vertical category labels, no legend. Appended to the\n * spec's own `responsive` rules as {@link CHART_RESPONSIVE_PRESETS}.compact. */\n compactBelow?: number | null\n /** Font, size and colours for the whole chart (`spec.style`), merged\n * over what the spec carries. */\n style?: ChartStyle\n}\n```\n\n### `const CHART_RESPONSIVE_PRESETS`\n\nResponsive rules the builder offers by name. `compact(maxWidth)` is the\none the Format tab writes through `compactBelow`: the labels that crowd a\nnarrow chart go, the category labels turn vertical, and the legend hides.\n\n```ts\nexport const CHART_RESPONSIVE_PRESETS = {\n compact: (maxWidth: number): ChartResponsiveRule => ({\n maxWidth,\n spec: { seriesLabels: false, dataLabels: { show: false }, xAxis: { labelRotation: 90 } },\n legend: false,\n }),\n} as const\n```\n\n### `function applyChartFormat`\n\nApply a {@link ChartFormatState} to a spec: a new spec with the titles,\naxis settings, palette and per-series styling merged in. Pure, so the\npanel can run it on every derived spec and a saved format keeps applying\nto fresh data. Unknown series labels are ignored.\n\n```ts\nexport function applyChartFormat(spec: ChartSpec, format: ChartFormatState | null | undefined): ChartSpec {\n if (!format) return spec\n const out: ChartSpec = { ...spec }\n if (format.title !== undefined) out.title = format.title || undefined\n if (format.subtitle !== undefined) out.subtitle = format.subtitle || undefined\n if (format.caption !== undefined) out.caption = format.caption || undefined\n if (format.palette) out.palette = format.palette\n if (format.seriesLabels !== undefined) out.seriesLabels = format.seriesLabels\n if (format.style) out.style = { ...spec.style, ...format.style }\n if (format.compactBelow != null && format.compactBelow > 0) {\n out.responsive = [...(spec.responsive ?? []), CHART_RESPONSIVE_PRESETS.compact(format.compactBelow)]\n }\n const axis = (base: ChartAxisConfig | undefined, f: NonNullable<ChartFormatState['yAxis']> | undefined): ChartAxisConfig | undefined => {\n if (!f) return base\n const next: ChartAxisConfig = { ...base }\n if (f.min !== undefined) { if (f.min === null) delete next.min; else next.min = f.min }\n if (f.max !== undefined) { if (f.max === null) delete next.max; else next.max = f.max }\n if (f.title !== undefined) next.title = f.title || undefined\n if (f.gridLines !== undefined) next.gridLines = f.gridLines\n if (f.format !== undefined) next.format = f.format\n return next\n }\n if (format.xAxis) {\n const next: ChartAxisConfig = { ...out.xAxis }\n if (format.xAxis.title !== undefined) next.title = format.xAxis.title || undefined\n if (format.xAxis.gridLines !== undefined) next.gridLines = format.xAxis.gridLines\n if (format.xAxis.labelRotation !== undefined) next.labelRotation = format.xAxis.labelRotation\n out.xAxis = next\n }\n if (format.yAxis) out.yAxis = axis(out.yAxis, format.yAxis)\n if (format.y2Axis) out.y2Axis = axis(out.y2Axis, format.y2Axis)\n if (format.series) {\n out.series = spec.series.map((s) => {\n const f = format.series![s.label]\n if (!f) return s\n const next: ChartSeries = { ...s }\n if (f.color) next.color = f.color\n if (f.type) next.type = f.type\n if (f.axis) next.axis = f.axis\n if (f.marker) next.marker = f.marker\n if (f.strokeWidth !== undefined) next.strokeWidth = f.strokeWidth\n if (f.dash !== undefined) next.dash = f.dash || undefined\n if (f.smooth !== undefined) next.smooth = f.smooth\n if (f.stack !== undefined) next.stack = f.stack || undefined\n return next\n })\n }\n return out\n}\n```\n\n### `function rowsToDirectSpec`\n\nThe chart types that read ROWS directly instead of a grouped grid, behind one\ncall. Returns `null` for every other type, which then goes through\n`rowsToChartSpec` and its reduce / sort / topN / \"Other\" pipeline.\n\nOne entry point rather than a branch per type in the caller, because the\ncaller is the grid controller and the controller is in the BASE bundle: every\ntype named there is bytes paid by grids that never chart. Here it is in the\nlazy chart chunk, next to the builders it dispatches to, and adding a fourth\ndirect type costs a grid nothing.\n\n```ts\nexport function rowsToDirectSpec<T extends Record<string, unknown>>(\n type: ChartType,\n rows: ReadonlyArray<T>,\n opts: {\n category?: string\n /** The measure. For scatter this is X. */\n value?: string\n /** Scatter's Y measure. */\n value2?: string\n series?: string\n reduce?: ChartReducer\n palette?: string[]\n /** Histogram: how many bins. Default: Sturges' rule. */\n bins?: number\n /** Candlestick / OHLC: the price columns, an optional volume, a calendar\n * bucket to roll the bars up to, and the candle style. `category` is\n * the date column. */\n ohlc?: { open: string; high: string; low: string; close: string; volume?: string; bucket?: ChartTimeBucket; candleStyle?: ChartSpec['candleStyle']; lastPriceLine?: boolean }\n },\n): ChartSpec | null {\n const cat = opts.category as (keyof T & string) | undefined\n const val = opts.value as (keyof T & string) | undefined\n const ser = opts.series as (keyof T & string) | undefined\n if (type === 'candlestick' || type === 'ohlc') {\n const o = opts.ohlc\n if (!cat || !o) return null\n const k = (f: string) => f as keyof T & string\n return rowsToOhlcSpec(rows, {\n date: cat, open: k(o.open), high: k(o.high), low: k(o.low), close: k(o.close),\n ...(o.volume ? { volume: k(o.volume) } : {}),\n ...(o.bucket ? { bucket: o.bucket } : {}),\n ...(o.candleStyle ? { candleStyle: o.candleStyle } : {}),\n ...(o.lastPriceLine ? { lastPriceLine: true } : {}),\n type,\n })\n }\n if (type === 'scatter') {\n const y = opts.value2 as (keyof T & string) | undefined\n if (!val || !y) return null\n return rowsToScatterSpec(rows, {\n x: val,\n y,\n ...(ser ? { series: ser } : {}),\n ...(opts.palette ? { palette: opts.palette } : {}),\n })\n }\n if (type === 'gauge') {\n if (!val) return null\n return rowsToGaugeSpec(rows, { value: val, ...(opts.reduce ? { reduce: opts.reduce } : {}) })\n }\n if (type === 'boxplot') {\n if (!cat || !val) return null\n const spec = rowsToBoxSpec(rows, {\n category: cat,\n value: val,\n ...(ser ? { series: ser } : {}),\n })\n if (opts.palette) spec.palette = opts.palette\n return spec\n }\n if (type === 'histogram') {\n if (!val) return null\n return rowsToHistogramSpec(rows, {\n value: val,\n ...(ser ? { series: ser } : {}),\n ...(opts.bins ? { bins: opts.bins } : {}),\n ...(opts.palette ? { palette: opts.palette } : {}),\n })\n }\n if (type === 'range-bar' || type === 'range-area' || type === 'dumbbell') {\n // Two measures: the first is the low end, the second the high end, each\n // reduced per category the way a bar would be.\n const hi = opts.value2 as (keyof T & string) | undefined\n if (!cat || !val || !hi) return null\n const lows = rowsToChartSpec(rows, { type: 'bar', category: cat, value: val, ...(ser ? { series: ser } : {}), reduce: opts.reduce ?? 'sum' })\n const highs = rowsToChartSpec(rows, { type: 'bar', category: cat, value: hi, ...(ser ? { series: ser } : {}), reduce: opts.reduce ?? 'sum' })\n return {\n type,\n categories: highs.categories,\n series: highs.series.map((s, i) => ({\n ...s,\n label: ser ? s.label : `${String(val)} to ${String(hi)}`,\n lowValues: lows.series[i]?.values.map((v, k) => Math.min(v, s.values[k] ?? v)) ?? [],\n values: s.values.map((v, k) => Math.max(v, lows.series[i]?.values[k] ?? v)),\n })),\n ...(opts.palette ? { palette: opts.palette } : {}),\n }\n }\n if (type === 'bullet') {\n if (!cat || !val) return null\n const measure = rowsToChartSpec(rows, { type: 'bar', category: cat, value: val, reduce: opts.reduce ?? 'sum' })\n const t = opts.value2 as (keyof T & string) | undefined\n const target = t ? rowsToChartSpec(rows, { type: 'bar', category: cat, value: t, reduce: opts.reduce ?? 'sum' }) : null\n return {\n type: 'bullet',\n categories: measure.categories,\n series: [{ ...measure.series[0]!, ...(target ? { targets: target.series[0]!.values } : {}) }],\n ...(opts.palette ? { palette: opts.palette } : {}),\n }\n }\n return null\n}\n```\n\n### `function rowsToBoxSpec`\n\nBuild a box plot spec straight from rows: group by a category, then reduce\neach group to a five-number summary.\n\nThis is the one aggregate the panel's `sum | avg | count` cannot express, and\nthat is the point of it. Every other chart answers \"how much\"; a box plot\nanswers \"how spread out\", which needs the whole sample per group rather than\none number, so it cannot go through `rowsToChartSpec`.\n\n`values` comes out as the medians, so tooltips, CSV and overlays work with no\nbox-specific code - the same contract `ohlc` follows.\n\n```ts\nexport function rowsToBoxSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n category: keyof T & string\n value: keyof T & string\n /** One box series per distinct value of this field, side by side. */\n series?: keyof T & string\n seriesLabel?: string\n /** Whisker length in IQRs. Default 1.5. */\n whisker?: number\n width?: number\n height?: number\n },\n): ChartSpec {\n const cats: string[] = []\n const seen = new Set<string>()\n for (const r of rows) {\n const c = String(r[opts.category] ?? '')\n if (!seen.has(c)) {\n seen.add(c)\n cats.push(c)\n }\n }\n const groupNames: string[] = []\n const groupSeen = new Set<string>()\n if (opts.series) {\n for (const r of rows) {\n const g = String(r[opts.series] ?? '')\n if (!groupSeen.has(g)) {\n groupSeen.add(g)\n groupNames.push(g)\n }\n }\n } else {\n groupNames.push(opts.seriesLabel ?? String(opts.value))\n }\n\n const series: ChartSeries[] = groupNames.map((g) => {\n const boxes: Array<BoxStats | null> = cats.map((c) => {\n const sample: number[] = []\n for (const r of rows) {\n if (String(r[opts.category] ?? '') !== c) continue\n if (opts.series && String(r[opts.series] ?? '') !== g) continue\n // `Number(null)` and `Number('')` are both 0, so coercing first would\n // fold every empty cell into the sample as a zero and drag the whole\n // box down. An absent observation is absent, not zero.\n const raw = r[opts.value]\n if (raw == null || raw === '') continue\n const n = Number(raw)\n if (Number.isFinite(n)) sample.push(n)\n }\n return boxStats(sample, opts.whisker)\n })\n return {\n label: g,\n // Medians, so a gap stays a gap rather than plotting as zero.\n values: boxes.map((b) => (b ? b.median : Number.NaN)),\n boxes,\n }\n })\n\n return {\n type: 'boxplot',\n categories: cats,\n series,\n ...(opts.width ? { width: opts.width } : {}),\n ...(opts.height ? { height: opts.height } : {}),\n }\n}\n```\n\n### `function rowsToScatterSpec`\n\nBuild a scatter / bubble spec straight from rows.\n\nUnlike the adapters above this cannot reuse `rowsToChartSpec`: a scatter\npoint is one row, not one group, so there is nothing to reduce. `series`\ncolours the points by a categorical field.\n\n```ts\nexport function rowsToScatterSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n x: keyof T & string\n y: keyof T & string\n /** Bubble radius field. Omit for a plain scatter. */\n r?: keyof T & string\n /** Group points into one series per distinct value. */\n series?: keyof T & string\n /** Per-point label, shown in the tooltip. */\n label?: keyof T & string\n palette?: string[]\n width?: number\n height?: number\n },\n): ChartSpec {\n const bySeries = new Map<string, ScatterPoint[]>()\n for (const row of rows) {\n const x = Number(row[opts.x])\n const y = Number(row[opts.y])\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue\n const key = opts.series ? String(row[opts.series] ?? '') : (opts.y as string)\n const pt: ScatterPoint = { x, y }\n if (opts.r) {\n const r = Number(row[opts.r])\n if (Number.isFinite(r)) pt.r = r\n }\n if (opts.label) pt.label = String(row[opts.label] ?? '')\n const list = bySeries.get(key)\n if (list) list.push(pt)\n else bySeries.set(key, [pt])\n }\n return {\n type: 'scatter',\n categories: [],\n series: [...bySeries].map(([label, points]) => ({ label, values: [], points })),\n palette: opts.palette,\n width: opts.width,\n height: opts.height,\n xAxisTitle: opts.x,\n yAxisTitle: opts.y,\n }\n}\n```\n\n### `function rowsToGaugeSpec`\n\nReduce rows to the single number a gauge shows.\n\nThere is no category axis here, which is why this cannot go through\n`rowsToChartSpec`. The dial ends on a nice round number rather than exactly\nthe value, so the needle never sits pinned at the far end of the arc.\n\n```ts\nexport function rowsToGaugeSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n value: keyof T & string\n reduce?: ChartReducer\n min?: number\n max?: number\n unit?: string\n target?: number\n width?: number\n height?: number\n },\n): ChartSpec {\n const samples: number[] = []\n for (const row of rows) {\n const v = Number(row[opts.value])\n if (Number.isFinite(v)) samples.push(v)\n }\n const reduced = reduceValues(samples, opts.reduce ?? 'sum')\n const value = Number.isFinite(reduced) ? reduced : 0\n const min = opts.min ?? Math.min(0, value)\n const max = opts.max ?? (value > min ? niceScale(min, value).max : min + 1)\n return {\n type: 'gauge',\n categories: [],\n series: [],\n gaugeValue: value,\n gaugeMin: min,\n gaugeMax: max,\n gaugeTarget: opts.target,\n gaugeUnit: opts.unit,\n width: opts.width,\n height: opts.height,\n }\n}\n```\n"
8010
+ "markdown": "# `@svgrid/grid` · `chart.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\chart.ts`.\n\n### `function chartStyleVars`\n\nThe CSS custom properties `spec.style` sets on the chart's host, as one\ninline style string (empty when nothing is set). `background` becomes the\nchart's `--sg-bg` (exports read it as the page colour), `textColor` the\ntext tokens, `gridColor` the border token, `fontSize` a scale every label\nmultiplies (12px is 1), and `fontFamily` the host's font.\n\n```ts\nexport function chartStyleVars(style: ChartStyle | undefined): string\n```\n\n### `function matchResponsiveRules`\n\nThe responsive rules that apply at a rendered size, in spec order. Pure:\n`SvChart` uses it for the legend field, {@link resolveResponsive} for the\nspec patches.\n\n```ts\nexport function matchResponsiveRules(rules: ChartResponsiveRule[] | undefined, width: number, height: number): ChartResponsiveRule[]\n```\n\n### `function resolveResponsive`\n\nApply `spec.responsive` for a rendered size: every matching rule's `spec`\nis merged over the input in order (later wins), the three axis objects one\nlevel deep. Returns the input itself when nothing matches, so callers can\ncompare by identity. `width`, `height` and `responsive` in a rule are\nignored; the size is the caller's.\n\n```ts\nexport function resolveResponsive(spec: ChartSpec, width: number, height: number): ChartSpec\n```\n\n### `function buildChart`\n\nLay out a {@link ChartSpec} into renderable {@link ChartGeometry} - scales,\nticks, and the position of every bar, line, slice and dot. Pure: no DOM, so\nit runs during SSR and can be unit-tested directly.\n\n```ts\nexport function buildChart(input: ChartSpec, theme: 'light' | 'dark' = 'light'): ChartGeometry\n```\n\n### `function sliceChartWindow`\n\nNarrow a spec to the category window `[lo, hi]`, keeping every\ncategory-parallel array in step.\n\nThis is the zoom / brush slice. It lives here rather than in the renderer\nbecause getting it wrong is a MODEL bug, not a paint bug, and it was wrong:\nthe component used to slice `categories`, `values` and `rowIds` by hand and\nspread the rest of the series through untouched. `upperValues` and\n`lowerValues` therefore kept their full length, the equality guard on the\nconfidence band (see `buildChart`) stopped matching, and the band silently\ndisappeared the moment anyone zoomed.\n\nThe lesson generalises: every array here is indexed by category, so each one\nadded in future has to be sliced too. Keeping them in one function is what\nmakes that a single place to remember rather than a scattered convention.\n\n```ts\nexport function sliceChartWindow(spec: ChartSpec, lo: number, hi: number): ChartSpec\n```\n\n### `function rowsToChartSpec`\n\nAggregate flat rows into a chart spec. Group by a category field, reduce a\nvalue field per group. Three multi-series shapes:\n - `value: 'revenue'` -> one series\n - `value: ['revenue','cost']` -> one series per value field\n - `value: 'sales', series: 'region'` -> pivot: one series per distinct\n value of the `series` field\n\n```ts\nexport function rowsToChartSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n type: ChartType\n category: keyof T & string\n value: (keyof T & string) | Array<keyof T & string>\n /** Pivot dimension: one series per distinct value of this field. */\n series?: keyof T & string\n /** How each group collapses to one number. Default `'sum'`. See\n * {@link ChartReducer} for the full list (min, max, median, p90, ...). */\n reduce?: ChartReducer\n /**\n * Group a date category by calendar unit instead of by exact value:\n * `'month'` files every row of March under `2026-03-01`. Categories come\n * out as ISO dates in chronological order and the spec's x axis is set to\n * `'ordinal-time'`, so the ticks read as dates. Rows whose category does\n * not parse as a date are dropped.\n */\n bucket?: ChartTimeBucket\n seriesLabel?: string\n width?: number\n height?: number\n stacked?: boolean\n stacked100?: boolean\n palette?: string[]\n /** Order categories. Defaults to insertion order (or value-desc when topN,\n * or chronological when bucketed). */\n sort?: 'value-desc' | 'value-asc' | 'category' | 'none'\n /** Keep only the top N categories; bucket the rest into \"Other\". */\n topN?: number\n /** Label for the bucketed remainder. Default \"Other\". */\n otherLabel?: string\n /** Field carrying each row's stable id. When set, the resulting spec's\n * series carry `rowIds` arrays so click handlers can drill back to\n * the source rows. */\n idField?: keyof T & string\n },\n): ChartSpec\n```\n\n### `function paretoSpec`\n\nThe bar-plus-line spec a pareto chart draws: categories sorted by value,\nbars for the values, and a cumulative-share line on the right axis pinned to\n0..100 with a reference line at `threshold` (default 80, the \"vital few\").\n`buildChart` calls this for `type: 'pareto'`; call it yourself to get at the\nspec, or pass a ready spec whose first series is the values.\n\n```ts\nexport function paretoSpec(spec: ChartSpec, threshold = 80): ChartSpec\n```\n\n### `function rowsToHistogramSpec`\n\nBin one numeric field of the rows into a histogram spec. The categories are\nthe bin midpoints on a numeric axis and `binEdges` labels the edges, so the\nbars touch and the axis reads `0, 10, 20` rather than `5, 15, 25`.\n`series` splits the sample into one histogram per distinct value.\n\n```ts\nexport function rowsToHistogramSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n value: keyof T & string\n series?: keyof T & string\n seriesLabel?: string\n bins?: number\n binWidth?: number\n method?: 'sturges' | 'fd' | 'sqrt'\n min?: number\n max?: number\n palette?: string[]\n width?: number\n height?: number\n },\n): ChartSpec\n```\n\n### `function rowsToRangeSpec`\n\nA range (floating) bar or area spec from rows: one row per category with a\nlow field and a high field, e.g. a day's low and high temperature, or a\nsalary band. `series` splits into one range per distinct value.\n\n```ts\nexport function rowsToRangeSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n type?: 'range-bar' | 'range-area'\n category: keyof T & string\n low: keyof T & string\n high: keyof T & string\n series?: keyof T & string\n seriesLabel?: string\n palette?: string[]\n width?: number\n height?: number\n },\n): ChartSpec\n```\n\n### `function specToTreemap`\n\nReshape an aggregated spec into a tree-map hierarchy.\n\nOne series gives a flat set of leaves. Several (a split-by) give two levels,\ncategory above series, which is the shape people expect from \"sales by\nregion, split by channel\".\n\n```ts\nexport function specToTreemap(spec: ChartSpec, rootName = 'Total'): TreeNode\n```\n\n### `function specToCalendar`\n\nReshape an aggregated spec into calendar samples.\n\nCategories that do not parse as a date are dropped rather than rendered at\nepoch zero, which would put a stray cell in 1970 and rescale the whole year.\n\n```ts\nexport function specToCalendar(spec: ChartSpec): Array<{ date: string; value: number }>\n```\n\n### `function specToSankey`\n\nReshape a pivoted spec into sankey nodes and links.\n\nThe pivot `rowsToChartSpec` already performs is exactly an edge list read\nsideways: categories are sources, series are targets, and each cell is the\nflow between them. Zero cells and self-edges are dropped, the first because\na zero-width ribbon is not a flow and the second because the layout has no\nmeaningful place to put one.\n\n```ts\nexport function specToSankey(spec: ChartSpec): {\n nodes: Array<{ id: string; label?: string }>\n links: Array<{ source: string; target: string; value: number }>\n}\n```\n\n### `type ChartFormatState`\n\nWhat the grid panel's chart builder lets a reader change about the LOOK of\na chart, as plain data so it can be saved with the view and applied to the\nspec the panel derives on every data change. Every field is optional and\nadditive; an absent field leaves the derived spec alone. Series are keyed\nby label, so a per-series colour survives a re-sort of the categories.\n\n```ts\nexport type ChartFormatState = {\n title?: string\n subtitle?: string\n caption?: string\n /** Where the legend goes; `false` hides it. The panel reads this for the\n * component prop, it is not a spec field. */\n legend?: 'top' | 'bottom' | 'left' | 'right' | false\n xAxis?: { title?: string; gridLines?: boolean; labelRotation?: number | 'auto' }\n yAxis?: { min?: number | null; max?: number | null; title?: string; gridLines?: boolean; format?: ChartValueFormat }\n y2Axis?: { min?: number | null; max?: number | null; title?: string; gridLines?: boolean; format?: ChartValueFormat }\n /** Per-series overrides, keyed by series label. */\n series?: Record<string, {\n color?: string\n type?: 'bar' | 'line' | 'area'\n axis?: 'left' | 'right'\n marker?: ChartMarkerShape\n strokeWidth?: number\n dash?: string\n smooth?: boolean\n /** The stack group a bar or area joins; an empty string leaves the\n * group. See {@link ChartSeries.stack}. */\n stack?: string\n }>\n /** Where data labels sit; `null` hides them. */\n dataLabels?: 'inside' | 'outside' | 'top' | 'center' | null\n palette?: string[] | null\n /** Series names at the end of each line (`spec.seriesLabels`). */\n seriesLabels?: boolean\n /** The axis value pills on the crosshair. A component prop, like\n * `legend`: the panel reads it, the engine does not. */\n crosshairLabels?: boolean\n /** Below this rendered width in px the chart goes compact: no series or\n * data labels, vertical category labels, no legend. Appended to the\n * spec's own `responsive` rules as {@link CHART_RESPONSIVE_PRESETS}.compact. */\n compactBelow?: number | null\n /** Font, size and colours for the whole chart (`spec.style`), merged\n * over what the spec carries. */\n style?: ChartStyle\n}\n```\n\n### `const CHART_RESPONSIVE_PRESETS`\n\nResponsive rules the builder offers by name. `compact(maxWidth)` is the\none the Format tab writes through `compactBelow`: the labels that crowd a\nnarrow chart go, the category labels turn vertical, and the legend hides.\n\n```ts\nexport const CHART_RESPONSIVE_PRESETS = {\n compact: (maxWidth: number): ChartResponsiveRule => ({\n maxWidth,\n spec: { seriesLabels: false, dataLabels: { show: false }, xAxis: { labelRotation: 90 } },\n legend: false,\n }),\n} as const\n```\n\n### `function applyChartFormat`\n\nApply a {@link ChartFormatState} to a spec: a new spec with the titles,\naxis settings, palette and per-series styling merged in. Pure, so the\npanel can run it on every derived spec and a saved format keeps applying\nto fresh data. Unknown series labels are ignored.\n\n```ts\nexport function applyChartFormat(spec: ChartSpec, format: ChartFormatState | null | undefined): ChartSpec\n```\n\n### `function rowsToDirectSpec`\n\nThe chart types that read ROWS directly instead of a grouped grid, behind one\ncall. Returns `null` for every other type, which then goes through\n`rowsToChartSpec` and its reduce / sort / topN / \"Other\" pipeline.\n\nOne entry point rather than a branch per type in the caller, because the\ncaller is the grid controller and the controller is in the BASE bundle: every\ntype named there is bytes paid by grids that never chart. Here it is in the\nlazy chart chunk, next to the builders it dispatches to, and adding a fourth\ndirect type costs a grid nothing.\n\n```ts\nexport function rowsToDirectSpec<T extends Record<string, unknown>>(\n type: ChartType,\n rows: ReadonlyArray<T>,\n opts: {\n category?: string\n /** The measure. For scatter this is X. */\n value?: string\n /** Scatter's Y measure. */\n value2?: string\n series?: string\n reduce?: ChartReducer\n palette?: string[]\n /** Histogram: how many bins. Default: Sturges' rule. */\n bins?: number\n /** Candlestick / OHLC: the price columns, an optional volume, a calendar\n * bucket to roll the bars up to, and the candle style. `category` is\n * the date column. */\n ohlc?: { open: string; high: string; low: string; close: string; volume?: string; bucket?: ChartTimeBucket; candleStyle?: ChartSpec['candleStyle']; lastPriceLine?: boolean }\n },\n): ChartSpec | null\n```\n\n### `function rowsToBoxSpec`\n\nBuild a box plot spec straight from rows: group by a category, then reduce\neach group to a five-number summary.\n\nThis is the one aggregate the panel's `sum | avg | count` cannot express, and\nthat is the point of it. Every other chart answers \"how much\"; a box plot\nanswers \"how spread out\", which needs the whole sample per group rather than\none number, so it cannot go through `rowsToChartSpec`.\n\n`values` comes out as the medians, so tooltips, CSV and overlays work with no\nbox-specific code - the same contract `ohlc` follows.\n\n```ts\nexport function rowsToBoxSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n category: keyof T & string\n value: keyof T & string\n /** One box series per distinct value of this field, side by side. */\n series?: keyof T & string\n seriesLabel?: string\n /** Whisker length in IQRs. Default 1.5. */\n whisker?: number\n width?: number\n height?: number\n },\n): ChartSpec\n```\n\n### `function rowsToScatterSpec`\n\nBuild a scatter / bubble spec straight from rows.\n\nUnlike the adapters above this cannot reuse `rowsToChartSpec`: a scatter\npoint is one row, not one group, so there is nothing to reduce. `series`\ncolours the points by a categorical field.\n\n```ts\nexport function rowsToScatterSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n x: keyof T & string\n y: keyof T & string\n /** Bubble radius field. Omit for a plain scatter. */\n r?: keyof T & string\n /** Group points into one series per distinct value. */\n series?: keyof T & string\n /** Per-point label, shown in the tooltip. */\n label?: keyof T & string\n palette?: string[]\n width?: number\n height?: number\n },\n): ChartSpec\n```\n\n### `function rowsToGaugeSpec`\n\nReduce rows to the single number a gauge shows.\n\nThere is no category axis here, which is why this cannot go through\n`rowsToChartSpec`. The dial ends on a nice round number rather than exactly\nthe value, so the needle never sits pinned at the far end of the arc.\n\n```ts\nexport function rowsToGaugeSpec<T extends Record<string, unknown>>(\n rows: ReadonlyArray<T>,\n opts: {\n value: keyof T & string\n reduce?: ChartReducer\n min?: number\n max?: number\n unit?: string\n target?: number\n width?: number\n height?: number\n },\n): ChartSpec\n```\n"
7940
8011
  },
7941
8012
  {
7942
8013
  "slug": "reference/auto/svgrid-grid-core",
7943
8014
  "path": "docs/reference/auto/svgrid-grid-core.md",
7944
8015
  "title": "@svgrid/grid · core.ts",
7945
8016
  "section": "API reference",
7946
- "markdown": "# `@svgrid/grid` · `core.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\core.ts`.\n\n### `type RowData`\n\nThe constraint every row type satisfies: an object keyed by string. Your own\nrow type (`type Person = { name: string }`) is what flows through the generics\nbelow; this is only the lower bound they are declared against.\n\n```ts\nexport type RowData = Record<string, unknown>\n```\n\n### `type Updater`\n\nA new value, or a function that derives it from the previous one - the shape\nevery `set*` on the grid accepts, so callers can update state without first\nreading it.\n\n api.setSorting([{ id: 'name', desc: false }])\n api.setSorting((prev) => [...prev, { id: 'age', desc: true }])\n\n```ts\nexport type Updater<T> = T | ((prev: T) => T)\n```\n\n### `type SortingState`\n\nActive sort clauses, outermost first. `desc: false` is ascending.\n\n```ts\nexport type SortingState = Array<{ id: string; desc: boolean }>\n```\n\n### `type ColumnFilter`\n\nOne column's filter: the column `id`, the `value` being matched, and\noptionally which comparison to use. `fn` defaults to the column's own type -\nsee {@link filterFns} for the available names.\n\n```ts\nexport type ColumnFilter = { id: string; value: unknown; fn?: keyof typeof filterFns }\n```\n\n### `type ColumnFiltersState`\n\nEvery active column filter. A column with no entry here is unfiltered.\n\n```ts\nexport type ColumnFiltersState = Array<ColumnFilter>\n```\n\n### `type PaginationState`\n\nCurrent page position. `pageIndex` is 0-based, so page 1 is index 0.\n\n```ts\nexport type PaginationState = { pageIndex: number; pageSize: number }\n```\n\n### `type GroupingState`\n\nColumn ids the rows are grouped by, outermost first.\n\n```ts\nexport type GroupingState = Array<string>\n```\n\n### `type ExpandedState`\n\nWhich rows are expanded, keyed by row id. Absent means collapsed.\n\n```ts\nexport type ExpandedState = Record<string, boolean>\n```\n\n### `type RowSelectionState`\n\nWhich rows are selected, keyed by row id. Absent means unselected.\n\n```ts\nexport type RowSelectionState = Record<string, boolean>\n```\n\n### `type ActiveCellState`\n\nWhere keyboard focus sits. The indices address the *displayed* grid (after\nsorting, filtering and paging), not the source data.\n\n```ts\nexport type ActiveCellState = {\n rowIndex: number\n colIndex: number\n cellId: string | null\n}\n```\n\n### `type TableFeatures`\n\nThe set of features a grid has registered, as built by {@link tableFeatures}.\nDeliberately open: a feature is identified by its key, so the type carries\nwhich ones are on without enumerating them.\n\n```ts\nexport type TableFeatures = Record<string, unknown>\n```\n\n### `type CellData`\n\nA cell's value. Unconstrained - a column can hold anything.\n\n```ts\nexport type CellData = unknown\n```\n\n### `type HeaderContext`\n\nWhat a column's `header` render function receives.\n\n```ts\nexport type HeaderContext<TData extends RowData> = {\n header: Header<TData>\n column: Column<TData>\n table: SvGrid<TData>\n}\n```\n\n### `type CellContext`\n\nWhat a column's `cell` render function receives. `getValue()` applies the\ncolumn's accessor (`field` or `fieldFn`); `row.original` is the raw object.\n\n```ts\nexport type CellContext<TData extends RowData> = {\n cell: Cell<TData>\n row: Row<TData>\n column: Column<TData>\n table: SvGrid<TData>\n getValue: () => unknown\n}\n```\n\n### `type CellSpanParams`\n\nParams passed to a column's `colSpan(...)` / `rowSpan(...)` callbacks.\n\n```ts\nexport type CellSpanParams<TData extends RowData = RowData> = {\n /** The row's underlying data object. */\n data: TData\n /** Display-row index in the current (filtered/sorted) row set. */\n rowIndex: number\n /** The column's id. */\n columnId: string\n /** The cell's base value for this column. */\n value: unknown\n}\n```\n\n### `type EditorOptionSource`\n\nThe raw option list a column's `editorOptions` can supply.\n\n```ts\nexport type EditorOptionSource = ReadonlyArray<\n string | number | { value: string | number; label?: string; color?: string }\n```\n\n### `type ValueParserParams`\n\nParams passed to a column's `valueParser(...)` on edit commit.\n\n```ts\nexport type ValueParserParams<TData extends RowData = RowData> = {\n /** The value after built-in per-`editorType` coercion. */\n newValue: unknown\n /** The cell's previous value. */\n oldValue: unknown\n /** The raw string the editor produced (pre-coercion). */\n rawInput: string\n /** The row's underlying data object. */\n data: TData\n /** The column's id. */\n columnId: string\n}\n```\n\n### `type EditorContext`\n\nContext passed to a custom `cellEditor` snippet/component. Three write\nhelpers cover the lifecycle:\n\n - `update(next)` - stage `next` as the draft, keep the editor open.\n Use this for live-preview controls (sliders,\n color pickers) so the user can keep adjusting.\n - `commit(next?)` - write the value AND close the editor. The\n argument is optional; when omitted, the most\n recently `update()`d value is saved. Use this\n for \"done\" gestures (Enter, picking an option).\n - `cancel()` - discard the draft and close the editor.\n\n```ts\nexport type EditorContext<TData extends RowData> = CellContext<TData> & {\n value: unknown\n update: (next: unknown) => void\n commit: (next?: unknown) => void\n cancel: () => void\n}\n```\n\n### `type CellFormatConfig`\n\nDeclarative cell formatting, applied through `Intl` - number, currency,\npercent, date and datetime. Prefer this over a `formatter` function: it is\nlocale-aware, and export and the clipboard reuse the same configuration.\n\n```ts\nexport type CellFormatConfig =\n | {\n type: 'number'\n locales?: string | Array<string>\n options?: Intl.NumberFormatOptions\n }\n | {\n type: 'currency'\n /** ISO 4217 (default USD) */\n currency?: string\n locales?: string | Array<string>\n options?: Omit<Intl.NumberFormatOptions, 'style' | 'currency'>\n }\n | {\n type: 'percent'\n locales?: string | Array<string>\n options?: Omit<Intl.NumberFormatOptions, 'style'>\n /**\n * If true, numeric cell values are 0–100 (e.g. 42 → 42%) instead of Intl’s 0–1 fraction (0.42 → 42%).\n * Default false.\n */\n valueIsPercentPoints?: boolean\n }\n | {\n type: 'date' | 'datetime'\n locales?: string | Array<string>\n /**\n * Shortcut patterns merged with `options`:\n * `'d'` short numeric date, `'D'` long date, `'y-m-d'` yyyy/mm/dd-style,\n * `'short'`|`'medium'`|`'long'` use dateStyle/timeStyle presets.\n */\n pattern?: string\n options?: Intl.DateTimeFormatOptions\n }\n```\n\n### `type CellFormatter`\n\nA column's custom display function, for anything {@link CellFormatConfig}\ncannot express. Returns a string - to render markup, use `cell` instead.\n\n```ts\nexport type CellFormatter<TData extends RowData> = (context: {\n value: unknown\n row: Row<TData>\n column: Column<TData>\n table: SvGrid<TData>\n}) => string\n```\n\n### `type ColumnDefTemplate`\n\nA header or cell slot: a literal string, or a function returning renderable content.\n\n```ts\nexport type ColumnDefTemplate<TContext> = string | ((context: TContext) => unknown)\n```\n\n### `type GroupAggregator`\n\nHow a column's value is aggregated for a group row when `columnGrouping`\nis active. Built-in reducers cover the common cases; pass a function for\nanything custom (weighted average, median, percentile, distinct count).\nThe function receives the finite numeric values AND the raw leaf rows.\n\n```ts\nexport type GroupAggregator<TData = any> =\n | 'sum'\n | 'avg'\n | 'min'\n | 'max'\n | 'count'\n | 'countDistinct'\n | 'extent'\n | 'first'\n | ((values: number[], rows: Array<TData>) => unknown)\n```\n\n### `function applyGroupAggregate`\n\nApply a group aggregator over a bucket's leaf rows for one column.\n\n```ts\nexport function applyGroupAggregate<TData extends RowData>(\n agg: GroupAggregator<TData>,\n columnId: string,\n rows: ReadonlyArray<Row<TData>>,\n): unknown {\n // One pass, no intermediate arrays.\n //\n // This used to build a `raw` array, then a coerced one, then a filtered one -\n // three allocations per aggregated column PER GROUP - before reducing. On a\n // 100k-row grid grouped two levels deep, aggregation was about two thirds of\n // the total grouping cost (213ms with three aggregators against 81ms with\n // none), and each additional aggregated column added roughly 80ms.\n //\n // `count` first: it never needs to look at a value at all.\n if (agg === 'count') return rows.length\n\n if (agg === 'first') {\n return rows.length ? rows[0]!.getCellValueByColumnId(columnId) : undefined\n }\n\n if (agg === 'countDistinct') {\n const seen = new Set<string>()\n for (const row of rows) seen.add(String(row.getCellValueByColumnId(columnId) ?? ''))\n return seen.size\n }\n\n if (typeof agg === 'function') {\n // Custom aggregators keep their contract: the finite numbers, then the\n // original row objects. Note `Number(null)` is 0 and therefore finite, so\n // nulls DO reach the callback as zeros - long-standing behaviour.\n const nums: number[] = []\n for (const row of rows) {\n const n = Number(row.getCellValueByColumnId(columnId))\n if (Number.isFinite(n)) nums.push(n)\n }\n return agg(nums, rows.map((r) => r.original))\n }\n\n // sum / avg / min / max / extent share one accumulation pass.\n let count = 0\n let sum = 0\n let min = Infinity\n let max = -Infinity\n for (const row of rows) {\n const n = Number(row.getCellValueByColumnId(columnId))\n if (!Number.isFinite(n)) continue\n count++\n // Left-to-right, matching the previous `reduce`, so float rounding is\n // bit-identical rather than merely close.\n sum += n\n // Math.min/max on scalars rather than `<`, which differs on -0, and rather\n // than the old `Math.min(...nums)` - spreading a whole group throws\n // RangeError once the bucket is big enough to exhaust the argument stack.\n min = Math.min(min, n)\n max = Math.max(max, n)\n }\n if (!count) return undefined\n switch (agg) {\n case 'sum':\n return sum\n case 'avg':\n return sum / count\n case 'min':\n return min\n case 'max':\n return max\n case 'extent':\n return `${min} – ${max}`\n default:\n return undefined\n }\n}\n```\n\n### `type ColumnDef`\n\nA column definition.\n\n`TFeatures` is a phantom parameter - it is threaded through nested\n`columns` groups but no member depends on it, so `{}`, `TableFeatures` and\n`typeof features` are all interchangeable here. It is deliberately left\nWITHOUT a default: `ColumnDef<Row>` would otherwise bind `Row` to this slot\nand silently type your data as `RowData`, losing every field-name check.\nPrefer {@link GridColumns} / {@link GridColumnDef} for the common case.\n\n```ts\nexport type ColumnDef<TFeatures extends TableFeatures, TData extends RowData> = {\n id?: string\n field?: keyof TData & string\n fieldFn?: (row: TData) => unknown\n header?: ColumnDefTemplate<HeaderContext<TData>>\n footer?: ColumnDefTemplate<HeaderContext<TData>>\n cell?: ColumnDefTemplate<CellContext<TData>>\n /**\n * A field type registered by `@svgrid/enterprise/fields` (`'attachment'`,\n * `'rating'`, `'url'`, ...). With the module enabled the cell is drawn by\n * that type; a column's own `cell` still wins. Without it the column draws\n * as an ordinary one.\n */\n fieldType?: string\n /** Properties of `fieldType` (options, precision, max files, ...). */\n fieldProps?: Record<string, unknown>\n columns?: Array<ColumnDef<TFeatures, TData>>\n /**\n * Declarative cell spanning (merged cells). Return how many COLUMNS this\n * cell spans to the right (1 = no span). Value-driven. Feed\n * `spansToMerges(rows, columns)` into `spreadsheetLayout` to apply - it uses\n * the same real `colspan`/`rowspan` merge engine (no separate code path).\n */\n colSpan?: (params: CellSpanParams<TData>) => number\n /**\n * Declarative cell spanning (merged cells). Return how many ROWS this cell\n * spans downward (1 = no span). See `colSpan` for how to apply.\n */\n rowSpan?: (params: CellSpanParams<TData>) => number\n /**\n * What the column's values are. It decides sorting, filter operators and\n * alignment, whatever edits the cell: `editorType` only picks the editor,\n * so a number column can be typed in a text box or a custom editor and\n * still sort, filter and align as numbers.\n * 'text' → left-aligned, text filters (text editor by default)\n * 'number' → right-aligned, numeric sort and filters (number editor)\n * 'boolean' → centered, true / false filter (checkbox editor)\n * 'date' → Date values, right-aligned, date sort and filters (date\n * editor, `{ type: 'date' }` format)\n * 'dateString' → ISO date STRINGS (e.g. '2026-06-27'), as a date\n * Anything you set explicitly (`editorType`, `align`, `format`) still wins.\n * Without it, a built-in `editorType` (`number`, `date`, `datetime`,\n * `checkbox`) implies the type, as before; grid-level `inferColumnTypes`\n * infers it from the first data row for columns with neither.\n */\n cellDataType?: 'text' | 'number' | 'boolean' | 'date' | 'dateString'\n /**\n * Hide this column when the grid's `responsive` mode is on and the grid is\n * narrower than this many pixels - drop low-priority columns on small\n * screens. No effect unless the grid has `responsive` set.\n */\n hideBelow?: number\n /**\n * For a column INSIDE a collapsible column group: `'open'` shows this column\n * only while the group is expanded, `'closed'` only while collapsed. Omit to\n * always show it. Setting it on any direct child gives the parent group a\n * collapse toggle. Pair with `openByDefault` on the group.\n */\n columnGroupShow?: 'open' | 'closed'\n /**\n * For a GROUP column (one with `columns: [...]`): start the group expanded.\n * Defaults to `false` (collapsed), the conventional default - so only the always-on\n * and `columnGroupShow: 'closed'` children show until the user expands it.\n */\n openByDefault?: boolean\n editorType?:\n | 'text'\n | 'number'\n | 'date' // rich SvCalendar popover (opt out with 'date-native')\n | 'datetime' // rich SvDateTimePicker (opt out with 'datetime-native')\n | 'time' // rich SvTimePicker dial (opt out with 'time-native')\n | 'date-native' // plain <input type=\"date\">\n | 'datetime-native' // plain <input type=\"datetime-local\">\n | 'time-native' // plain <input type=\"time\"> - HH:MM or HH:MM:SS\n | 'password' // native <input type=\"password\"> with masked rendering\n | 'checkbox'\n | 'list'\n | 'chips'\n | 'select' // custom dropdown - single value, no typeahead\n | 'rich-select' // custom dropdown with a typeahead search input\n | 'autocomplete' // free-text input with a live-filtered suggestion list (accepts any value)\n | 'textarea' // multi-line editor; Tab or Ctrl+Enter commits, plain Enter inserts a newline\n | 'color' // native <input type=\"color\"> swatch\n | 'rating' // 5-star rating control\n // Any other string names a CUSTOM editor registered via `registerCellEditor`\n // (or `registerBuiltinEditors`). `(string & {})` keeps the literals above\n // autocompleting while allowing arbitrary custom type names.\n | (string & {})\n /**\n * Custom in-cell editor. Receives the cell context PLUS a `commit(value)`\n * and `cancel()` helper. Use when none of the built-in `editorType`s fit;\n * the snippet's outer element is mounted inside the editing cell and\n * inherits keyboard handling (Esc cancels, Enter commits unless your\n * snippet preventDefaults it).\n *\n * Coexists with `editorType`: when both are set, `cellEditor` wins and\n * `editorType` is treated as a hint for parsing the saved value.\n */\n cellEditor?: ColumnDefTemplate<EditorContext<TData>>\n /**\n * The text format of the date / datetime editor's box, in date-format\n * tokens (`'MMMM d, yyyy'`, `'MM/dd/yyyy h:mm tt'`), so an edit shows the\n * date the way the cell does. Default `'yyyy-MM-dd'`, with time\n * `'yyyy-MM-dd HH:mm'`.\n */\n editorFormatString?: string\n /**\n * Per-column tooltip. String shows as a native `title=`; `(ctx) => string`\n * runs per cell so the tooltip can reflect the value. Returning an empty\n * string skips the tooltip.\n */\n tooltip?: string | ((ctx: CellContext<TData>) => string | null | undefined)\n /**\n * Declarative per-cell validation. Runs for EVERY\n * rendered cell - including values already present in `data` on load, not\n * just on edit - so bad data is flagged immediately. Invalid cells get the\n * `sv-grid-cell-invalid` class (red highlight) and the returned message as\n * their tooltip.\n *\n * Return value:\n * - `null` / `undefined` / `true` → valid (no highlight)\n * - `false` → invalid, no message\n * - a non-empty `string` → invalid, string is the tooltip\n *\n * On its own `validate` flags: the value keeps rendering as-is and an\n * edit that fails it still lands. Set `rejectInvalid` to refuse such an\n * edit instead.\n */\n validate?: (params: {\n value: unknown\n row: TData\n rowIndex: number\n column: Column<TData>\n }) => string | boolean | null | undefined\n /**\n * Refuse an edit that `validate` flags. When true, a committed value that\n * makes `validate` return `false` or a message is not written: the cell\n * keeps its old value, no history step is recorded and\n * `onCellValueChange` does not fire. The value is checked after\n * `valueParser` has run, so the rule sees what would be stored. Applies to\n * the inline editor, a commit to a selection and a full-row edit; paste\n * does not go through the editor and is not checked.\n */\n rejectInvalid?: boolean\n /**\n * Gate editing per column or per cell.\n *\n * - `true` (or omitted): the column is fully editable.\n * - `false`: the column is read-only - double-click, type-to-edit,\n * fill-handle drag, Delete, and clipboard paste all skip it.\n * - `(ctx) => boolean`: evaluated for each cell, so you can lock\n * individual rows (e.g. by role, status, ownership). Returning\n * `false` opts the cell out of every editing path, identical to\n * setting `editable: false` on the whole column for that row.\n *\n * The grid-wide `enableInlineEditing` prop still wins when set to\n * `false`.\n */\n editable?: boolean | ((context: CellContext<TData>) => boolean)\n /**\n * Transform the committed edit value before it is written to the row.\n * Runs after the built-in per-`editorType` coercion, so `newValue` is\n * already type-parsed; return the final value to store (e.g. round a\n * number, uppercase a code, look up an id). A `valueParser` hook.\n */\n valueParser?: (params: ValueParserParams<TData>) => unknown\n /**\n * Briefly flash / highlight this column's cell when its value changes\n * (streaming feeds, edits, server pushes). `true` uses the default flash;\n * pass `{ className }` to apply your own animation class instead.\n */\n cellFlash?: boolean | { className?: string }\n /**\n * When `false`, this column never shows a sort indicator and clicking\n * its header is a no-op - `api.setSort(thisColumn, ...)` is also\n * ignored. Defaults to `true` (the column participates in sorting as\n * long as `rowSortingFeature` is registered).\n */\n sortable?: boolean\n /**\n * When `false`, this column never shows a filter funnel / menu and\n * `api.setFilter(thisColumn, ...)` is ignored. Defaults to `true` (the\n * column is filterable as long as `columnFilteringFeature` is\n * registered).\n */\n filterable?: boolean\n /**\n * Options for `editorType: 'list' | 'chips'`. Either bare values (the\n * string is both value and label) or `{ value, label }` objects.\n * For `chips` this is optional - when omitted, the chips editor becomes\n * free-form (user types and presses Enter to commit a chip).\n *\n * Pass a function `(row) => options` for row-dependent (cascading)\n * options - e.g. City options that depend on Country in the same row.\n *\n * Either form may return a **Promise**, for options that come from the\n * server. While it resolves, the editor shows a loading state and the cell\n * renders its raw value.\n *\n * Results are cached so reopening an editor does not refetch: a static source\n * per column, a per-row source per row AND per that row's data - so a cascade\n * reloads by itself when the cell it depends on is edited. Call\n * `api.refreshEditorOptions(columnId?)` when the list changes server-side.\n */\n editorOptions?:\n | EditorOptionSource\n | Promise<EditorOptionSource>\n | ((row: TData) => EditorOptionSource | Promise<EditorOptionSource>)\n /** When true, list/chips allow multiple selections. Cell value becomes an array. */\n editorMultiple?: boolean\n /**\n * The text editor accepts line breaks: Alt+Enter inserts one and the\n * editor grows a line per break, while Enter still commits. What a\n * spreadsheet cell with wrapped text wants; `editorType: 'textarea'` is\n * the other shape, where Enter itself is the line break.\n */\n editorMultiline?: boolean\n /** Separator used when joining array values for the readonly cell display. Defaults to ', '. */\n editorSeparator?: string\n format?: CellFormatConfig\n formatter?: CellFormatter<TData>\n /**\n * The number this column sorts a value by, in place of the value: a status\n * option's position in its list, say, so \"To do\" comes before \"Done\".\n * Blanks and anything not a number sort first, as in a number column.\n */\n sortValue?: (value: unknown) => number | null | undefined\n /**\n * Aggregate this column's values into the group row when grouping is\n * active. `'sum' | 'avg' | 'min' | 'max' | 'count' | 'countDistinct' |\n * 'extent' | 'first'`, or a custom `(values, rows) => unknown`. The result\n * is formatted with this column's `format` and shown in the group header.\n */\n aggregate?: GroupAggregator<TData>\n /**\n * What this column contributes to the grid's footer summary row (the one\n * turned on with `summary` / `enableRowSummaries`). Takes the same\n * aggregators as {@link aggregate}, and the result is formatted with this\n * column's `format`.\n *\n * Without it the footer falls back to its default: the sum of a numeric\n * column, `Count: N` otherwise. Set `false` to leave the cell blank, which is\n * usually what an actions or checkbox column wants.\n *\n * { field: 'amount', summary: 'avg' }\n * { id: 'actions', summary: false }\n */\n summary?: GroupAggregator<TData> | false\n /**\n * Render the cell as an in-cell sparkline chart. The cell value should be\n * an array of numbers (or a comma/space separated string). Mutually\n * exclusive with a custom `cell` renderer (a `cell` wins if both are set).\n *\n * { sparkline: { type: 'line' } } // default line\n * { sparkline: { type: 'bar', color: '#16a34a' } }\n * { sparkline: { type: 'winloss' } } // sign-only up/down\n *\n * See `SparklineConfig` for the full option set (type, color,\n * negativeColor, width, height, fixed min/max).\n */\n sparkline?: SparklineConfig\n /** Initial column width in pixels. Falls back to the grid's `columnWidth` prop. */\n width?: number\n /**\n * Whether the user may resize this column. Only consulted when the grid has\n * `columnResize` on - it narrows that, it does not enable anything.\n *\n * `false` removes the column's drag handle entirely, so pointer drag, the\n * keyboard arrows and double-click-to-autosize are all gone with it, and the\n * column menu drops its Autosize item. Use it for the columns whose width is\n * part of the layout rather than a preference: a row-number gutter, a\n * checkbox column, a fixed icon column.\n *\n * Programmatic sizing is unaffected - `api.autosizeColumn()`,\n * `api.setColumnWidth()` and `fitColumns` all still apply, the same way they\n * do when `columnResize` is off. This governs the user affordance only.\n */\n resizable?: boolean\n /**\n * Initial visibility. Set `false` to start the column hidden while still\n * listing it in the Choose Columns UI for the user to re-enable. Applied\n * once at mount; after that `api.setColumnVisible` / user toggles win.\n * On a group column, `false` hides the whole group's leaf columns.\n */\n visible?: boolean\n /**\n * Horizontal alignment for header and body cells. When omitted, the\n * default is inferred from `editorType`:\n * - `'number' | 'date' | 'datetime'` → `'right'`\n * - `'checkbox'` → `'center'`\n * - everything else → `'left'`\n */\n align?: 'left' | 'center' | 'right'\n /**\n * Per-cell conditional CSS. Two shapes:\n *\n * - **String** (or array of strings): class name(s) added to the\n * cell's `<td>` for every row in this column.\n * - **Function**: invoked per cell with the same `CellContext` shape\n * the `cell` renderer receives. Return a string, an array of\n * strings, or an object mapping class names to booleans.\n *\n * Use it for status tinting, conditional bold, \"negative number\"\n * coloring - anything that's a function of the row's value. Cells\n * still receive their format / cell renderer; the class just\n * augments the rendered `<td>`.\n */\n cellClass?:\n | string\n | ReadonlyArray<string>\n | ((ctx: CellContext<TData>) => string | ReadonlyArray<string> | Record<string, boolean> | undefined | null)\n}\n```\n\n### `type GridColumnDef`\n\nA column definition keyed only by your row type - the ergonomic form of\n{@link ColumnDef}, whose first parameter is a phantom feature bag that is\nalmost always `{}`.\n\n```ts\nconst columns: GridColumns<Person> = [{ field: 'firstName', header: 'Name' }]\n```\n\nInterchangeable with `ColumnDef<{}, TData>` and `ColumnDef<typeof features,\nTData>` in both directions, so it mixes freely with existing code.\n\n```ts\nexport type GridColumnDef<TData extends RowData = RowData> = ColumnDef<TableFeatures, TData>\n```\n\n### `type GridColumns`\n\nAn array of {@link GridColumnDef} - what you pass to `<SvGrid columns={...}>`.\n\n```ts\nexport type GridColumns<TData extends RowData = RowData> = Array<GridColumnDef<TData>>\n```\n\n### `type Column`\n\nA resolved column: your {@link ColumnDef} plus everything the grid computed\nfrom it - its id, its depth under any group header, and the sort handlers a\nheader needs. This is what you receive in render contexts; the `ColumnDef`\nis what you wrote.\n\n```ts\nexport type Column<TData extends RowData> = {\n id: string\n columnDef: ColumnDef<any, TData>\n depth: number\n parentId?: string\n getCanSort: () => boolean\n getCanFilter: () => boolean\n getIsSorted: () => false | 'asc' | 'desc'\n getToggleSortingHandler: () => () => void\n}\n```\n\n### `type Header`\n\nOne header cell. `colSpan` is how many leaf columns it covers, and\n`isPlaceholder` marks the empty cells that pad a group-header row so the\nlevels line up.\n\n```ts\nexport type Header<TData extends RowData> = {\n id: string\n isPlaceholder: boolean\n colSpan: number\n column: Column<TData>\n getContext: () => HeaderContext<TData>\n}\n```\n\n### `type HeaderGroup`\n\nOne row of header cells. A grid with grouped columns has several, outermost first.\n\n```ts\nexport type HeaderGroup<TData extends RowData> = {\n id: string\n headers: Array<Header<TData>>\n}\n```\n\n### `type Cell`\n\nOne cell: the intersection of a {@link Row} and a {@link Column}.\n\n```ts\nexport type Cell<TData extends RowData> = {\n id: string\n row: Row<TData>\n column: Column<TData>\n getValue: () => unknown\n getContext: () => CellContext<TData>\n}\n```\n\n### `type Row`\n\nA row in the display model. `original` is your untouched data object;\neverything else is grid-computed. `index` is the position in the displayed\nset, so it shifts as sorting and filtering change - key on `id`, not index.\n\nGroup rows and tree parents carry `subRows`; a plain data row does not.\n\n```ts\nexport type Row<TData extends RowData> = {\n id: string\n index: number\n original: TData\n depth: number\n subRows?: Array<Row<TData>>\n /** Total leaf (data) rows under this group row. Undefined for data rows. */\n leafCount?: number\n getCanExpand: () => boolean\n getIsExpanded: () => boolean\n toggleExpanded: () => void\n getIsSelected: () => boolean\n toggleSelected: () => void\n getAllCells: () => Array<Cell<TData>>\n getCellValueByColumnId: (columnId: string) => unknown\n}\n```\n\n### `type RowModel`\n\nThe output of the row pipeline: the rows to display, in order.\n\n```ts\nexport type RowModel<TData extends RowData> = {\n rows: Array<Row<TData>>\n}\n```\n\n### `type Store`\n\nThe minimal reactive store behind the headless core - read `state`, write\nthrough `setState`, and `subscribe` for changes. Deliberately framework\nfree, which is what lets the core run under plain Node.\n\nIn Svelte you rarely touch this: `subscribeGrid` wraps it with fine-grained\nselectors so a component only re-runs for the slice it read.\n\n```ts\nexport type Store<T> = {\n readonly state: T\n setState: (updater: (prev: T) => T) => void\n subscribe: (listener: () => void) => () => void\n}\n```\n\n### `const rowSortingFeature`\n\nClick-to-sort. Injected by the `sortable` shortcut.\n\nThis and the five features below are opaque markers: pass the ones you want\nto {@link tableFeatures} and the grid wires up the matching row model. With\n`<SvGrid>` you rarely name them - the boolean shortcuts (`sortable`,\n`filterable`, `pageable`, `groupable`) inject them for you. Reach for them\ndirectly when driving the headless core, or when you want a feature on\nwithout its UI.\n\nThe names match TanStack Table v9, so a features object written for it works\nhere unchanged.\n\n```ts\nexport const rowSortingFeature = { key: 'rowSortingFeature' }\n```\n\n### `const columnFilteringFeature`\n\nPer-column filtering. Injected by the `filterable` shortcut.\n\n```ts\nexport const columnFilteringFeature = { key: 'columnFilteringFeature' }\n```\n\n### `const rowPaginationFeature`\n\nPaging of the row model. Injected by the `pageable` shortcut.\n\n```ts\nexport const rowPaginationFeature = { key: 'rowPaginationFeature' }\n```\n\n### `const columnGroupingFeature`\n\nRow grouping with aggregation. Injected by the `groupable` shortcut.\n\n```ts\nexport const columnGroupingFeature = { key: 'columnGroupingFeature' }\n```\n\n### `const rowSelectionFeature`\n\nRow selection state (the checkbox column reads it).\n\n```ts\nexport const rowSelectionFeature = { key: 'rowSelectionFeature' }\n```\n\n### `const rowExpandingFeature`\n\nExpand / collapse, for tree rows and master-detail.\n\n```ts\nexport const rowExpandingFeature = { key: 'rowExpandingFeature' }\n```\n\n### `function tableFeatures`\n\nDeclare which features a grid uses. Identity at runtime - its whole job is to\ncapture the exact set in the type, so `ColumnDef<typeof features, Row>` knows\nwhat is registered and anything you did not register is tree-shaken out.\n\n```ts\nconst features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n```\n\nSame call signature as TanStack Table v9, so a features object written for it\ntransfers unchanged.\n\n```ts\nexport function tableFeatures<T extends TableFeatures>(features: T): T {\n return features\n}\n```\n\n### `const sortFns`\n\nBuilt-in comparators, chosen per column by its data type. `auto` compares as\ntext; set a column's type or supply your own comparator to override.\n\n```ts\nexport const sortFns = {\n auto: (a: unknown, b: unknown) => compareAutoValues(a, b),\n number: (a: unknown, b: unknown) => compareNumericKeys(numberSortKey(a), numberSortKey(b)),\n date: (a: unknown, b: unknown) => compareNumericKeys(dateSortKey(a), dateSortKey(b)),\n}\n```\n\n### `const filterFns`\n\nBuilt-in match functions, named by {@link ColumnFilter}'s `fn`.\n`includesString` is case-insensitive substring; `equals` is strict identity.\n\n```ts\nexport const filterFns = {\n includesString: (value: unknown, query: string) =>\n String(value).toLowerCase().includes(query.toLowerCase()),\n equals: (value: unknown, query: unknown) => value === query,\n}\n```\n\n### `type BaseRowCtx`\n\nEverything a base row needs that is the same for every row in the table.\n\nOne object per table, referenced by every row, instead of one closure scope\nper row. See {@link BASE_ROW_METHODS}.\n\n```ts\nexport type BaseRowCtx<TData extends RowData> = {\n grid: SvGrid<TData>\n store: { state: Record<string, any> }\n columns: Array<Column<TData>>\n columnCount: number\n columnIndexById: Map<string, number>\n}\n```\n\n### `const ROW_VALUES`\n\nA base row's cached cell values. @internal\n\n```ts\nexport const ROW_VALUES = Symbol('svgrid.row.values')\n```\n\n### `const ROW_CELLS`\n\nA base row's cached cells. @internal\n\n```ts\nexport const ROW_CELLS = Symbol('svgrid.row.cells')\n```\n\n### `const ROW_FILTER_POS`\n\nThe row's index in the last full filter's output (see ROW_FILTER_GEN). @internal\n\n```ts\nexport const ROW_FILTER_POS = Symbol('svgrid.row.filterPos')\n```\n\n### `function denseRows`\n\nThe rows as a plain dense array. For a lazyRows() list, makes the rows not\nmade yet and returns its backing array - the same row objects, without the\nProxy in front. Anything that reads every row (a sort, a filter) should go\nthrough this first: a trap per read, over several passes of a million rows,\ncost more than building the rows did.\n\n```ts\nexport function denseRows<T>(rows: T[]): T[] {\n const fill = (rows as unknown as Record<symbol, (() => T[]) | undefined>)[LAZY_FILL]\n return fill ? fill() : rows\n}\n```\n\n### `type WindowedRowModel`\n\nThe row model for windowed data (windowed-data.ts), or null when `data` is\nan ordinary array. It lives in windowed-row-model.ts and is installed by the\nfirst createWindowedData() call, so a grid that is never handed windowed\ndata does not bundle it: this file imports nothing from either module.\n\n```ts\nexport type WindowedRowModel<TData extends RowData> = (data: unknown, columns: Array<Column<TData>>) => RowModel<TData> | null\n```\n\n### `type WindowedRowModelInstall`\n\nHow windowed-row-model.ts builds its row model from the base row helpers. @internal\n\n```ts\nexport type WindowedRowModelInstall =<TData extends RowData>(ctx: {\n rowCtxFor: (columns: Array<Column<TData>>) => BaseRowCtx<TData>\n getRowId: () => ((row: TData, index: number) => string) | undefined\n}) => WindowedRowModel<TData>\n```\n\n### `function registerWindowedRowModel`\n\nInternal: windowed-row-model.ts installs itself here.\n\n```ts\nexport function registerWindowedRowModel(install: WindowedRowModelInstall): void {\n installWindowedRowModel = install\n}\n```\n\n### `type BaseRowState`\n\nA base row's private fields, on top of the public {@link Row} surface.\n\n```ts\nexport type BaseRowState<TData extends RowData> = Row<TData> & {\n [ROW_CTX]: BaseRowCtx<TData>\n [ROW_VALUES]: Array<unknown> | null\n [ROW_CELLS]: Array<Cell<TData>> | null\n [ROW_FILTER_GEN]: number\n [ROW_FILTER_POS]: number\n [ROW_SORT_DROPPED]: number\n [ROW_SORT_KEY]: unknown\n}\n```\n\n### `const BASE_ROW_METHODS`\n\nThe methods every base row carries, defined ONCE and assigned by reference.\n\nRows used to be built as object literals whose methods were closures, which\nmeant a 100k-row grid allocated 700k closures and a closure scope per row\nbefore painting anything. Measured at 100k x 9: 13.8 ms and 56.5 MB to build,\nagainst 2.0 ms and 14.5 MB for this shape - the single largest cost in\nmounting a large grid.\n\nThey read their row through `this` rather than a captured variable, which is\nwhy they can be shared. Note they are assigned as OWN properties rather than\nput on a prototype: `Row` is public, several row models legitimately do\n`{ ...row, depth }`, and a spread copies own properties but not a prototype.\nA class here would silently strip every method off a cloned row.\n\n```ts\nexport const BASE_ROW_METHODS = {\n getCanExpand(this: BaseRowState<RowData>) {\n return false\n },\n getIsExpanded(this: BaseRowState<RowData>) {\n return Boolean((this[ROW_CTX].store.state.expanded ?? {})[this.id])\n },\n toggleExpanded(this: BaseRowState<RowData>) {\n const id = this.id\n this[ROW_CTX].grid.setExpanded((prev) => ({ ...prev, [id]: !prev[id] }))\n },\n getIsSelected(this: BaseRowState<RowData>) {\n return Boolean((this[ROW_CTX].store.state.rowSelection ?? {})[this.id])\n },\n toggleSelected(this: BaseRowState<RowData>) {\n const id = this.id\n this[ROW_CTX].grid.setRowSelection((prev) => ({ ...prev, [id]: !prev[id] }))\n },\n getAllCells(this: BaseRowState<RowData>) {\n return this[ROW_CELLS] ?? buildBaseRowCells(this)\n },\n getCellValueByColumnId(this: BaseRowState<RowData>, columnId: string) {\n const idx = this[ROW_CTX].columnIndexById.get(columnId)\n if (idx === undefined) return undefined\n if (!this[ROW_VALUES]) this[ROW_VALUES] = baseRowValues(this)\n return this[ROW_VALUES][idx]\n },\n}\n```\n\n### `type RowModelFactory`\n\nOne stage of the row pipeline: takes the rows produced so far and returns the\nnext set. Stages compose in the order given to `_rowModels`, so filtering\nbefore sorting sorts only what survived the filter.\n\n```ts\nexport type RowModelFactory<TData extends RowData> = (args: {\n table: SvGrid<TData>\n rows: Array<Row<TData>>\n}) => Array<Row<TData>>\n```\n\n### `function createCoreRowModel`\n\nThe identity stage that starts every pipeline. Always required, even when no\nother stage is: it is what turns your data into rows.\n\n```ts\nexport function createCoreRowModel<TData extends RowData>(): RowModelFactory<TData> {\n return ({ rows }) => rows\n}\n```\n\n### `function createFilteredRowModel`\n\nDrops rows that fail the active {@link ColumnFiltersState}. Pairs with\n`columnFilteringFeature`; without it there are no filters to apply.\n\n```ts\nexport function createFilteredRowModel<TData extends RowData>(): RowModelFactory<TData> {\n /**\n * The last full filter, so a tick can repair it. When `getRowModel`\n * reports which rows were replaced (`replacedRowsOf`) and the filter state\n * and columns are the same objects as last time, each replacement is tested\n * on its own: a row that stays in keeps its slot, a row that stays out\n * stays out, and a row whose membership flips sends the whole thing back\n * through the full pass, because an insertion has to land in data order.\n * Positions come from stamps on the rows (ROW_FILTER_GEN / ROW_FILTER_POS)\n * written by the full pass; no map is built.\n */\n let cache: { input: Array<Row<TData>>; output: Array<Row<TData>>; filters: ColumnFiltersState; columns: Array<Column<TData>>; gen: number } | null = null\n let generation = 0\n\n return ({ table, rows }) => {\n const filters: ColumnFiltersState = table.getState().columnFilters ?? []\n if (!filters.length) {\n cache = null\n return rows\n }\n const columns = table.getAllColumns()\n\n // Resolve each filter's match function once, outside the row loop.\n const compiled = filters.map((filter) => ({\n id: filter.id,\n value: filter.value,\n fn: filter.fn ? filterFns[filter.fn] : filterFns.includesString,\n }))\n const passes = (row: Row<TData>) => {\n for (let i = 0; i < compiled.length; i++) {\n const filter = compiled[i]!\n // `getCellValueByColumnId` rather than `getAllCells().find(...)`.\n // Both read the same lazily-built `cachedValues` array, but the latter\n // also builds and caches the row's whole `Cell[]` - one object per\n // column - purely to reach one field. On a 100k-row grid that is\n // 100,000 cell arrays the filter never looks at again, and it defeats\n // the laziness the row factory exists to provide.\n if (!filter.fn(row.getCellValueByColumnId(filter.id), filter.value as any)) return false\n }\n return true\n }\n\n if (cache && cache.filters === filters && cache.columns === columns) {\n if (cache.input === rows) return cache.output\n const replaced = replacedRowsOf(table)\n if (replaced && rows.length === cache.input.length) {\n let out: Array<Row<TData>> | null = null\n let ok = true\n for (let i = 0; i < rows.length && ok; i++) {\n const prev = cache.input[i]! as BaseRowState<TData>\n const next = rows[i]! as BaseRowState<TData>\n if (next === prev) continue\n if (replaced.get(prev) !== next) { ok = false; break }\n const wasIn = prev[ROW_FILTER_GEN] === cache.gen\n const isIn = passes(next)\n if (wasIn !== isIn) { ok = false; break }\n if (!isIn) continue\n out ??= cache.output.slice()\n const pos = prev[ROW_FILTER_POS]\n out[pos] = next\n next[ROW_FILTER_GEN] = cache.gen\n next[ROW_FILTER_POS] = pos\n }\n if (ok) {\n const output = out ?? cache.output\n cache = { ...cache, input: rows, output }\n return output\n }\n }\n }\n\n const gen = ++generation\n const output: Array<Row<TData>> = []\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i]! as BaseRowState<TData>\n if (!passes(row)) continue\n row[ROW_FILTER_GEN] = gen\n row[ROW_FILTER_POS] = output.length\n output.push(row)\n }\n cache = { input: rows, output, filters, columns, gen }\n return output\n }\n}\n```\n\n### `function createPaginatedRowModel`\n\nNarrows the rows to the current page. Put it LAST: anything after it would\nonly ever see one page of data.\n\n```ts\nexport function createPaginatedRowModel<TData extends RowData>(): RowModelFactory<TData> {\n return ({ table, rows }) => {\n const pagination = table.getState().pagination ?? { pageIndex: 0, pageSize: rows.length || 10 }\n const start = pagination.pageIndex * pagination.pageSize\n return rows.slice(start, start + pagination.pageSize)\n }\n}\n```\n\n### `function createGroupedRowModel`\n\nBuckets rows by the active {@link GroupingState} and inserts a group row\nahead of each bucket, carrying that bucket's aggregates.\n\n```ts\nexport function createGroupedRowModel<TData extends RowData>(): RowModelFactory<TData> {\n return ({ table, rows }) => {\n const grouping: GroupingState = table.getState().grouping ?? []\n if (!grouping.length) return rows\n const columns = table.getAllColumns()\n\n // Recursively bucket rows by each grouping column in turn. At every level a\n // group row is built that stands in for its children - a non-group column\n // resolves to the value shared by every leaf row, or to undefined when the\n // leaves disagree.\n function buildGroups(\n input: Array<Row<TData>>,\n levelIndex: number,\n depth: number,\n idPrefix: string,\n /** Grouping columns already fixed by an ancestor bucket, and their raw\n * values - `undefined` where that bucket mixed several. */\n fixedValues: ReadonlyMap<string, unknown>,\n ): Array<Row<TData>> {\n if (levelIndex >= grouping.length) {\n // Leaves: actual data rows, with their nesting depth recorded.\n return input.map((row) => ({ ...row, depth }))\n }\n const groupKey = grouping[levelIndex]\n if (!groupKey) return input\n\n // Buckets carry the RAW grouping value alongside the rows, plus whether\n // the bucket saw more than one distinct raw value. Both are needed to let\n // deeper levels skip re-scanning this column: buckets are keyed by\n // `String(value ?? '')`, so `null`, `undefined` and `''` collapse into one\n // bucket, and a scan of such a bucket would report disagreement. Tracking\n // it here costs one comparison per row and keeps the shortcut honest.\n type Bucket = { rows: Array<Row<TData>>; raw: unknown; mixed: boolean }\n const buckets = new Map<string, Bucket>()\n for (const row of input) {\n const value = row.getCellValueByColumnId(groupKey)\n const key = String(value ?? '')\n const bucket = buckets.get(key)\n if (bucket) {\n bucket.rows.push(row)\n if (!bucket.mixed && bucket.raw !== value) bucket.mixed = true\n } else {\n buckets.set(key, { rows: [row], raw: value, mixed: false })\n }\n }\n\n const groupRows: Array<Row<TData>> = []\n let index = 0\n buckets.forEach((bucket, key) => {\n const children = bucket.rows\n const id = `${idPrefix}_${groupKey}_${key}`\n // Record this column as fixed for deeper levels ONLY when the bucket is\n // homogeneous. If all rows here share a raw value, so does every subset\n // of them, which is what makes the shortcut sound.\n //\n // A MIXED bucket must not be recorded at all - not even as \"undefined\".\n // `null`, `undefined` and `''` share a bucket key, so a mixed bucket can\n // still split into homogeneous children one level down, and those\n // children have a real shared value that a scan would find. Marking the\n // column resolved here would hand them the parent's disagreement.\n const nextFixed = bucket.mixed ? fixedValues : new Map(fixedValues).set(groupKey, bucket.raw)\n const subRows = buildGroups(children, levelIndex + 1, depth + 1, id, nextFixed)\n const isDeepest = levelIndex + 1 >= grouping.length\n const leafCount = isDeepest\n ? subRows.length\n : subRows.reduce((sum, sub) => sum + (sub.leafCount ?? 0), 0)\n\n // Every grouping column ABOVE this level is already resolved: bucketing\n // by it is what made it constant, so scanning the children to rediscover\n // it is pure waste. Only the current level's key short-circuited before,\n // so a second-level group walked all of its children to re-derive the\n // first level's value - about 100,000 reads on the 100k x 9 two-level\n // case, for an answer already in hand.\n //\n // The current level still returns the stringified bucket key rather than\n // the raw value, because that is what it has always returned and the\n // group row's display depends on it.\n const resolveColumnValue = (columnId: string): unknown => {\n if (columnId === groupKey) return key\n if (fixedValues.has(columnId)) return fixedValues.get(columnId)\n let resolved: unknown\n let hasResolved = false\n for (const child of children) {\n const childValue = child.getCellValueByColumnId(columnId)\n if (!hasResolved) {\n resolved = childValue\n hasResolved = true\n } else if (childValue !== resolved) {\n return undefined\n }\n }\n return resolved\n }\n\n const groupOriginal: Record<string, unknown> = {}\n columns.forEach((column) => {\n const field = column.columnDef.field\n if (!field) return\n const agg = column.columnDef.aggregate\n groupOriginal[field] = agg\n ? applyGroupAggregate(agg, column.id, children)\n : resolveColumnValue(column.id)\n })\n\n const groupRow: Row<TData> = {\n id,\n index: index++,\n original: groupOriginal as TData,\n depth,\n subRows,\n leafCount,\n getCanExpand: () => true,\n getIsExpanded: () => Boolean((table.getState().expanded ?? {})[id]),\n toggleExpanded: () => {\n table.setExpanded((prev) => ({ ...prev, [id]: !prev[id] }))\n },\n getIsSelected: () => Boolean((table.getState().rowSelection ?? {})[id]),\n toggleSelected: () => {\n table.setRowSelection((prev) => ({ ...prev, [id]: !prev[id] }))\n },\n getAllCells: () => [],\n // Prefer the precomputed group value (which carries aggregates)\n // and fall back to the shared-value resolver for columns without\n // a field.\n getCellValueByColumnId: (columnId: string) => {\n const col = columns.find((c) => c.id === columnId)\n const field = col?.columnDef.field\n if (field && field in groupOriginal) return groupOriginal[field]\n return resolveColumnValue(columnId)\n },\n }\n groupRows.push(groupRow)\n })\n return groupRows\n }\n\n return buildGroups(rows, 0, 0, 'group', new Map())\n }\n}\n```\n\n### `type TreeRowModelOptions`\n\nHow to read a hierarchy out of FLAT rows: each row names its parent, and the\ngrid reconstructs the tree. Rows whose parent id matches nothing become roots\nrather than disappearing.\n\nFor nested source data (`children: [...]`), flatten it first with\n{@link flattenTreeData}.\n\n```ts\nexport type TreeRowModelOptions = {\n /** Field holding each row's parent id. Rows with no parent are roots. */\n parentField: string\n /** Field holding the row's own id. Defaults to `'id'`. */\n idField?: string\n}\n```\n\n### `function createTreeRowModel`\n\nClient-side tree data: nest the grid's own flat rows into a parent/child\nhierarchy that `createExpandedRowModel` then walks.\n\nThis works on the rows the grid already built rather than on raw data, so\ntree rows keep their cells, editing, selection and formatting - they are real\ndata rows that happen to have children, not synthetic banners like grouping's.\nThat is also why the model is parent-id based: nested source arrays never\nbecome rows (the grid only builds rows for `data`), so nested input is\nflattened first with {@link flattenTreeData}. One code path, no duplicated\nrow construction.\n\nRows are tagged `__treeRow` so `isGroupRow` does not mistake an expandable\ndata row for a full-width group banner.\n\n```ts\nexport function createTreeRowModel<TData extends RowData>(\n options: TreeRowModelOptions,\n): RowModelFactory<TData> {\n const { parentField, idField = 'id' } = options\n return ({ table, rows }) => {\n if (!rows.length) return rows\n const keyOf = (row: Row<TData>) => (row.original as any)?.[idField]\n const parentOf = (row: Row<TData>) => (row.original as any)?.[parentField]\n\n const present = new Set<unknown>()\n for (const row of rows) present.add(keyOf(row))\n\n const childrenByParent = new Map<unknown, Array<Row<TData>>>()\n const roots: Array<Row<TData>> = []\n for (const row of rows) {\n const parent = parentOf(row)\n // A row whose parent is absent (filtered out, or never existed) becomes a\n // root rather than disappearing - silently dropping rows is worse than a\n // shallower tree. Self-parenting is treated the same way.\n if (parent == null || parent === keyOf(row) || !present.has(parent)) {\n roots.push(row)\n continue\n }\n const list = childrenByParent.get(parent) ?? []\n list.push(row)\n childrenByParent.set(parent, list)\n }\n\n // Guards a cycle in the parent chain from recursing forever.\n const seen = new Set<unknown>()\n const build = (row: Row<TData>, depth: number): Row<TData> => {\n const key = keyOf(row)\n const id = row.id\n if (seen.has(key)) {\n return { ...row, depth, subRows: [], getCanExpand: () => false } as Row<TData>\n }\n seen.add(key)\n const subRows = (childrenByParent.get(key) ?? []).map((child) => build(child, depth + 1))\n return {\n ...row,\n depth,\n subRows,\n leafCount: subRows.reduce((n, sub) => n + 1 + (sub.leafCount ?? 0), 0),\n __treeRow: true,\n getCanExpand: () => subRows.length > 0,\n getIsExpanded: () => Boolean((table.getState().expanded ?? {})[id]),\n toggleExpanded: () => {\n table.setExpanded((prev) => ({ ...prev, [id]: !prev[id] }))\n },\n } as Row<TData>\n }\n\n return roots.map((root) => build(root, 0))\n }\n}\n```\n\n### `type FlattenTreeOptions`\n\nHow to flatten NESTED source data into the parent-id shape tree rows need.\n`parentField` is written onto each row, so point `treeData.parentField` at\nthe same name afterwards.\n\n```ts\nexport type FlattenTreeOptions = {\n /** Field holding an array of child objects. */\n childrenField: string\n /** Field holding each object's id. Defaults to `'id'`. */\n idField?: string\n /** Field to WRITE the resolved parent id onto. Defaults to `'__parentId'`. */\n parentField?: string\n}\n```\n\n### `function flattenTreeData`\n\nFlatten nested tree data into the flat parent-id shape `createTreeRowModel`\nconsumes, stamping each child with its parent's id.\n\nChildren are emitted directly after their parent so the natural order already\nmatches the rendered tree. The `childrenField` array is left on the objects\n(harmless, and callers often still want it); only the parent link is added.\n\n```ts\nexport function flattenTreeData<T extends RowData>(\n data: ReadonlyArray<T>,\n options: FlattenTreeOptions,\n): T[] {\n const { childrenField, idField = 'id', parentField = '__parentId' } = options\n const out: T[] = []\n const walk = (nodes: ReadonlyArray<T>, parentId: unknown) => {\n for (const node of nodes) {\n const flat = { ...node, [parentField]: parentId } as T\n out.push(flat)\n const kids = (node as any)[childrenField]\n if (Array.isArray(kids) && kids.length) walk(kids as ReadonlyArray<T>, (node as any)[idField])\n }\n }\n walk(data, null)\n return out\n}\n```\n\n### `function createExpandedRowModel`\n\nHides the descendants of collapsed rows. Needed for grouping, tree data and\nmaster-detail alike - all three are the same expand/collapse mechanism.\n\n```ts\nexport function createExpandedRowModel<TData extends RowData>(): RowModelFactory<TData> {\n return ({ table, rows }) => {\n const expanded: ExpandedState = table.getState().expanded ?? {}\n // Nothing expanded means every collapsed row hides its children and the\n // output is the input, element for element. Returning it as is keeps the\n // array identity the stages downstream and the render window key on, and\n // skips a 100k-element copy per data change on a flat grid.\n let anyExpanded = false\n for (const id in expanded) {\n if (expanded[id]) { anyExpanded = true; break }\n }\n if (!anyExpanded) return rows\n const flattened: Array<Row<TData>> = []\n const visit = (row: Row<TData>) => {\n flattened.push(row)\n if (row.subRows?.length && expanded[row.id]) {\n for (const sub of row.subRows) visit(sub)\n }\n }\n for (const row of rows) visit(row)\n return flattened\n }\n}\n```\n\n### `function replacedRowsOf`\n\nThe rows `getRowModel` replaced in the rebuild this pipeline run follows, or null.\n\n```ts\nexport function replacedRowsOf(table: SvGrid<any>): ReadonlyMap<Row<any>, Row<any>> | null {\n return replacedRowsByGrid.get(table) ?? null\n}\n```\n\n### `function createSortedRowModel`\n\nThe sorting stage of the row pipeline: orders the rows by the grid's\n`sorting` state with the built-in comparators (or the `localSortFns` map\nhanded in), stable, equal keys keeping their data order. A tick that\nreplaces a few rows out of many is repaired incrementally rather than\nre-sorted (see the note inside). Registered by `rowSortingFeature`; an app\nonly calls this to install its own comparator set.\n\n```ts\nexport function createSortedRowModel<TData extends RowData>(\n localSortFns: typeof sortFns = sortFns,\n): RowModelFactory<TData> {\n /**\n * What the last full sort produced, kept so a tick can repair it.\n *\n * A live feed replaces a few hundred row objects out of a hundred thousand\n * and hands the grid a new array. Re-sorting all of it costs the same as\n * the first sort did (115-149 ms in the browser for 100k rows, see\n * docs/help/benchmarks.md); the order it would produce differs from the\n * previous one only where the replaced rows land. So the previous output\n * is kept, with its sort keys aligned to it, and when `getRowModel` says\n * which rows were replaced (see `replacedRowsOf`) the stage drops those,\n * sorts the replacements among themselves and merges them back in one\n * linear pass: O(n + k log k) instead of O(n log n) key builds and\n * comparisons.\n *\n * The repair is only attempted when everything else is the same object as\n * last time - the sorting state, the columns, and every input row except\n * the replaced ones - and it produces exactly what the full sort would:\n * equal keys fall back to the data index, which is the order a stable sort\n * over data-ordered input keeps.\n */\n let cache: {\n input: Array<Row<TData>>\n output: Array<Row<TData>>\n sorting: SortingState\n columns: Array<Column<TData>>\n clauses: Array<SortClause>\n } | null = null\n\n type SortClause = {\n desc: boolean\n compare: (a: any, b: any) => number\n /** The key for one row, or `MISSING_KEY` when it cannot be produced incrementally. */\n keyOf: (row: Row<TData>) => any\n }\n const MISSING_KEY = Symbol('svgrid.sort.missing-key')\n\n function fullSort(rows: Array<Row<TData>>, sorting: SortingState, allColumns: Array<Column<TData>>) {\n // Resolve every clause ONCE, before sorting.\n //\n // This used to live inside the comparator, so `getAllColumns().find(...)`\n // ran per comparison per clause: a single-clause sort of 100k rows made\n // 1,528,947 array scans, and a three-clause sort made 3,933,751 (measured;\n // `pnpm bench --case=sort-1col`). The comparator is called O(n log n)\n // times, so anything inside it that is not O(1) sets the cost of the sort.\n const clauses: Array<{\n keys: Array<any>\n desc: boolean\n compare: (a: any, b: any) => number\n keyOf: (row: Row<TData>) => any\n /** Set when every key is an integer rank in [0, rankCount): the text rank path. */\n rankCount?: number\n }> = []\n\n for (const clause of sorting) {\n const column = allColumns.find((col) => col.id === clause.id)\n if (!column) continue\n // By the column's data type, not by what edits it: a number column\n // edited in a text box still sorts as numbers.\n const dataType = columnDataType(column.columnDef)\n const comparator =\n dataType === 'number'\n ? localSortFns.number\n : isDateDataType(dataType)\n ? localSortFns.date\n : localSortFns.auto\n\n // Precompute one sort key per row, so the comparator reads an array slot\n // instead of walking the row's column index on every comparison. For the\n // three built-in comparators the key is also cheaper to compare than the\n // raw value: a timestamp rather than two `new Date()` allocations, a\n // number rather than two `Number()` coercions, a collator rather than a\n // fresh one per `localeCompare` call.\n //\n // The identity checks against `sortFns` matter: `localSortFns` is a\n // public parameter, so a caller can substitute their own comparators.\n // When they have, we fall through to calling their function with the raw\n // values - still hoisted, just not specialised.\n const columnId = column.id\n const n = rows.length\n let keys: Array<any> = new Array(n)\n let compare: (a: any, b: any) => number\n let keyOf: (row: Row<TData>) => any\n let autoMode: 'number' | 'mixed' | 'text' | undefined\n let rankCount: number | undefined\n\n const sortValue = column.columnDef.sortValue\n if (typeof sortValue === 'function') {\n keyOf = (row) => numberSortKey(sortValue(row.getCellValueByColumnId(columnId)))\n for (let i = 0; i < n; i++) keys[i] = keyOf(rows[i]!)\n compare = compareNumericKeys\n } else if (comparator === sortFns.number) {\n keyOf = (row) => numberSortKey(row.getCellValueByColumnId(columnId))\n for (let i = 0; i < n; i++) keys[i] = keyOf(rows[i]!)\n compare = compareNumericKeys\n } else if (comparator === sortFns.date) {\n keyOf = (row) => dateSortKey(row.getCellValueByColumnId(columnId))\n for (let i = 0; i < n; i++) keys[i] = keyOf(rows[i]!)\n compare = compareNumericKeys\n } else if (comparator === sortFns.auto && (autoMode = autoSortMode(rows, columnId)) === 'number') {\n // A column with no declared type whose values are all numbers. Sorting\n // it as text put 10 before 2 (#104).\n keyOf = (row) => {\n const value = row.getCellValueByColumnId(columnId)\n // A text value arriving in a tick changes the mode; only a full sort\n // can place it.\n return typeof value === 'number' || isBlankSortValue(value)\n ? numberSortKey(value)\n : MISSING_KEY\n }\n for (let i = 0; i < n; i++) keys[i] = keyOf(rows[i]!)\n compare = compareNumericKeys\n } else if (autoMode === 'mixed') {\n // Numbers and text in one column. Rare, so no key tricks: the raw\n // values through the pairwise comparator, which orders by kind first.\n keyOf = (row) => row.getCellValueByColumnId(columnId)\n for (let i = 0; i < n; i++) keys[i] = keyOf(rows[i]!)\n compare = compareAutoValues\n } else if (comparator === sortFns.auto) {\n const strings: string[] = new Array(n)\n // Decide whether ranking is worth attempting BEFORE paying for it.\n //\n // Building the distinct set and then discarding it costs about 9 ms on\n // a 100k-row column where nearly every value is unique, and ranking\n // saves about 19 ms where they repeat - so guessing wrong in either\n // direction is measurable. A small stride sample answers it for well\n // under a millisecond.\n //\n // Strided rather than the first N rows: data arrives sorted or\n // clustered often enough that a prefix is a bad estimator of the whole\n // column. Reading every k-th row is no more expensive and does not care\n // how the rows are arranged.\n const rankLimit = n >> 1\n // Each distinct value's id (its insertion order), when ranking.\n let idOf: Map<string, number> | null = null\n if (n > 0) {\n // Ranking pays when the column has at most n/2 distinct values. A\n // small sample cannot see that by asking whether half of it repeats:\n // 1M rows of 80k values, each one 12 times over, gave 256 samples\n // with almost no repeats, so ranking was skipped and the sort made\n // 20M collator calls (1.75 s; ranked, it is a fraction of that).\n // Count the repeats in a larger sample instead. S samples from u\n // equally common values repeat about S^2 / 2u times, so u <= n/2\n // shows as at least S^2 / n repeats. Up to SAMPLE rows the whole\n // column is the sample and the test is exact.\n const SAMPLE = 2048\n const sampleTarget = Math.min(n, SAMPLE)\n const stride = Math.max(1, Math.floor(n / sampleTarget))\n const sample = new Set<string>()\n let sampled = 0\n for (let i = 0; i < n; i += stride) {\n sample.add(autoTextKey(rows[i]!.getCellValueByColumnId(columnId)))\n sampled++\n }\n const repeats = sampled - sample.size\n const worthRanking = stride === 1 ? sample.size <= rankLimit : repeats * n >= sampled * sampled\n if (worthRanking) idOf = new Map()\n }\n\n // One hash per row: the value's id is looked up (or assigned) as the\n // row is read, and the rank lookup further down is an array read by\n // id. It used to add every value to a Set and then look every value up\n // again in a rank Map, two hashes per row.\n const ids: Int32Array | null = idOf ? new Int32Array(n) : null\n for (let i = 0; i < n; i++) {\n const s = autoTextKey(rows[i]!.getCellValueByColumnId(columnId))\n strings[i] = s\n if (idOf) {\n let id = idOf.get(s)\n if (id === undefined) {\n id = idOf.size\n idOf.set(s, id)\n if (idOf.size > rankLimit) {\n idOf = null\n continue\n }\n }\n ids![i] = id\n }\n }\n\n // Collation is by far the most expensive comparison we do - a CPU\n // profile of a 100k text sort put 65% of the whole operation inside the\n // collator. But a column's DISTINCT values are usually far fewer than\n // its rows (statuses, regions, categories, owners), so rank the\n // distinct values once and sort by rank afterwards. That turns\n // O(n log n) collator calls into O(u log u), where u is the number of\n // distinct values, and the resulting order is identical because rank is\n // a monotone relabelling of the collated order - equal strings share a\n // rank, so ties still fall through to the stable sort exactly as before.\n //\n // Guarded on the uniqueness ratio: when nearly every value is distinct\n // the ranking pass cannot save any collator calls and would just add an\n // O(n) Map build, so that case keeps comparing directly.\n if (idOf) {\n // Map keys come back in insertion order, which is id order.\n const values = Array.from(idOf.keys())\n const byRank = values.map((_, id) => id).sort((a, b) => compareCollatedKeys(values[a]!, values[b]!))\n const rankById = new Int32Array(values.length)\n for (let r = 0; r < byRank.length; r++) rankById[byRank[r]!] = r\n for (let i = 0; i < n; i++) keys[i] = rankById[ids![i]!]!\n const rankIds = idOf\n rankCount = values.length\n compare = compareNumericKeys\n // A replacement whose text is not among the ranked values has no\n // rank; the repair path treats that as \"sort everything again\".\n keyOf = (row) => {\n const value = row.getCellValueByColumnId(columnId)\n // A number arriving in a tick makes the column mixed; resort fully.\n if (typeof value === 'number') return MISSING_KEY\n const id = rankIds.get(autoTextKey(value))\n return id === undefined ? MISSING_KEY : rankById[id]!\n }\n } else {\n keys = strings\n compare = compareCollatedKeys\n keyOf = (row) => {\n const value = row.getCellValueByColumnId(columnId)\n return typeof value === 'number' ? MISSING_KEY : autoTextKey(value)\n }\n }\n } else {\n keyOf = (row) => row.getCellValueByColumnId(columnId)\n for (let i = 0; i < n; i++) keys[i] = keyOf(rows[i]!)\n compare = comparator\n }\n\n clauses.push({ keys, desc: clause.desc, compare, keyOf, rankCount })\n }\n\n if (!clauses.length) return null\n\n // Sort an index array, then materialise. `Array.prototype.sort` is stable,\n // so equal keys keep their original relative order exactly as the previous\n // `[...rows].sort(...)` did.\n // An index array the comparator sorts in place, or a typed array from\n // countingOrder / radixOrder for a large one-column numeric sort.\n let order: ArrayLike<number> = new Array<number>(rows.length)\n for (let i = 0; i < order.length; i++) (order as number[])[i] = i\n\n // Single-clause sorts get a specialised comparator.\n //\n // Most sorts are one column, and that path runs O(n log n) times - 1.66\n // million comparisons for 100k rows. The general loop pays a clause-array\n // index, three property loads and an indirect call on every one of them,\n // none of which vary once the clause list is fixed. Hoisting them into a\n // closure and, for the numeric comparator, inlining the subtraction removes\n // the call entirely.\n //\n // `keys[ib] - keys[ia]` for descending is exactly `-(keys[ia] - keys[ib])`\n // as far as sorting is concerned: both are NaN for unorderable values,\n // which the spec coerces to 0, and they differ only in producing 0 versus\n // -0 for equal keys, which sorts identically.\n if (clauses.length === 1) {\n const { keys, compare, desc, rankCount } = clauses[0]!\n if (rankCount !== undefined && rows.length >= STABLE_NUMERIC_SORT_MIN) {\n order = countingOrder(keys as number[], rankCount, desc)\n } else if (compare === compareNumericKeys && rows.length >= STABLE_NUMERIC_SORT_MIN) {\n order = radixOrder(keys as number[], desc)\n } else if (compare === compareNumericKeys) {\n ;(order as number[]).sort(\n desc\n ? function compareOneNumericDesc(ia, ib) { return keys[ib] - keys[ia] }\n : function compareOneNumericAsc(ia, ib) { return keys[ia] - keys[ib] },\n )\n } else {\n ;(order as number[]).sort(\n desc\n ? function compareOneDesc(ia, ib) { return -compare(keys[ia], keys[ib]) }\n : function compareOneAsc(ia, ib) { return compare(keys[ia], keys[ib]) },\n )\n }\n } else {\n ;(order as number[]).sort(function compareRowsByClauses(ia, ib) {\n for (let k = 0; k < clauses.length; k++) {\n const clause = clauses[k]!\n const result = clause.compare(clause.keys[ia], clause.keys[ib])\n if (result !== 0) return clause.desc ? -result : result\n }\n return 0\n })\n }\n\n const sorted = new Array<Row<TData>>(rows.length)\n for (let i = 0; i < order.length; i++) sorted[i] = rows[order[i]!]!\n // Each row keeps its key(s), so a later tick can place a replacement\n // among the kept rows without reading any of them again. One property\n // write per row; an array per row only when there are several clauses.\n if (clauses.length === 1) {\n const keys = clauses[0]!.keys\n for (let i = 0; i < rows.length; i++) (rows[i] as any)[ROW_SORT_KEY] = keys[i]\n } else {\n for (let i = 0; i < rows.length; i++) {\n const per = new Array(clauses.length)\n for (let k = 0; k < clauses.length; k++) per[k] = clauses[k]!.keys[i]\n ;(rows[i] as any)[ROW_SORT_KEY] = per\n }\n }\n return { sorted, clauses: clauses.map(({ desc, compare, keyOf }) => ({ desc, compare, keyOf })) }\n }\n\n /**\n * The previous output with the replaced rows swapped for their\n * replacements, in sorted position. Null when the input is not the cached\n * input plus replacements, or a replacement has no incremental key.\n *\n * Every row carries the key(s) the last full sort computed for it\n * (ROW_SORT_KEY: the key itself for one clause, an array for several), so\n * the merge moves row references and nothing else. At 100k rows the loop\n * that also copied an aligned key array cost 3.7 ms; this one is the\n * reference copy alone.\n */\n function repair(rows: Array<Row<TData>>, replaced: ReadonlyMap<Row<any>, Row<any>>) {\n const c = cache!\n if (rows.length !== c.input.length) return null\n // Which rows of THIS stage's input changed. The map may name rows a\n // stage upstream filtered out; only the ones that reach here matter.\n const dropGen = ++sortDropGeneration\n const added: Array<Row<TData>> = []\n for (let i = 0; i < rows.length; i++) {\n const prev = c.input[i]!\n const next = rows[i]!\n if (next === prev) continue\n if (replaced.get(prev) !== next) return null\n ;(prev as any)[ROW_SORT_DROPPED] = dropGen\n added.push(next)\n }\n if (!added.length) return c.output\n\n const clauses = c.clauses\n const single = clauses.length === 1\n for (let j = 0; j < added.length; j++) {\n const row = added[j]! as any\n if (single) {\n const key = clauses[0]!.keyOf(row)\n if (key === MISSING_KEY) return null\n row[ROW_SORT_KEY] = key\n } else {\n const keys = new Array(clauses.length)\n for (let k = 0; k < clauses.length; k++) {\n const key = clauses[k]!.keyOf(row)\n if (key === MISSING_KEY) return null\n keys[k] = key\n }\n row[ROW_SORT_KEY] = keys\n }\n }\n\n // Keys first, then the data index: the tie-break a stable sort over\n // data-ordered input applies, so the merge lands where a full sort would.\n const prevOut = c.output\n const compareRows = single\n ? (() => {\n const { compare, desc } = clauses[0]!\n return (a: Row<TData>, b: Row<TData>) => {\n const r = compare((a as any)[ROW_SORT_KEY], (b as any)[ROW_SORT_KEY])\n if (r !== 0) return desc ? -r : r\n return a.index - b.index\n }\n })()\n : (a: Row<TData>, b: Row<TData>) => {\n const ka = (a as any)[ROW_SORT_KEY]\n const kb = (b as any)[ROW_SORT_KEY]\n for (let k = 0; k < clauses.length; k++) {\n const clause = clauses[k]!\n const r = clause.compare(ka[k], kb[k])\n if (r !== 0) return clause.desc ? -r : r\n }\n return a.index - b.index\n }\n\n // Sort the replacements among themselves (k log k)...\n added.sort(compareRows)\n\n // ...find where each one goes in the previous output by binary search\n // (k log n comparisons, against the dropped rows too - they are skipped\n // below, which does not move an insertion point)...\n const n = prevOut.length\n const insertAt = new Array<number>(added.length)\n let lo = 0\n for (let j = 0; j < added.length; j++) {\n // Monotone: the replacements are sorted, so each search starts where\n // the previous one landed.\n const row = added[j]!\n let hi = n\n while (lo < hi) {\n const mid = (lo + hi) >>> 1\n if (compareRows(row, prevOut[mid]!) < 0) hi = mid\n else lo = mid + 1\n }\n insertAt[j] = lo\n }\n\n // ...then one linear pass that only moves references.\n const out = new Array<Row<TData>>(rows.length)\n let w = 0\n let j = 0\n let nextInsert = insertAt[0] ?? -1\n for (let i = 0; i < n; i++) {\n while (nextInsert === i) {\n out[w++] = added[j++]!\n nextInsert = j < added.length ? insertAt[j]! : -1\n }\n const prev = prevOut[i]!\n if ((prev as any)[ROW_SORT_DROPPED] === dropGen) continue\n out[w++] = prev\n }\n while (j < added.length) out[w++] = added[j++]!\n return out\n }\n\n return function sortedRowModelStage({ table, rows }) {\n const sorting = table.getState().sorting ?? []\n if (!sorting.length) {\n cache = null\n return rows\n }\n const columns = table.getAllColumns()\n\n if (cache && cache.sorting === sorting && cache.columns === columns) {\n if (cache.input === rows) return cache.output\n const replaced = replacedRowsOf(table)\n if (replaced) {\n const repaired = repair(rows, replaced)\n if (repaired) {\n cache = { ...cache, input: rows, output: repaired }\n return repaired\n }\n }\n }\n\n const full = fullSort(rows, sorting, columns)\n if (!full) {\n cache = null\n return rows\n }\n cache = { input: rows, output: full.sorted, sorting, columns, clauses: full.clauses }\n return full.sorted\n }\n}\n```\n\n### `type SvGridOptions`\n\nEverything {@link createSvGridCore} accepts: the data and columns, the\nfeatures and row models that make up the pipeline, and an `on*Change`\ncallback per piece of state for controlled use.\n\n`<SvGrid>` builds this for you from its props - you only construct it\ndirectly when driving the headless core.\n\n```ts\nexport type SvGridOptions<TFeatures extends TableFeatures, TData extends RowData> = {\n _features: TFeatures\n _rowModels?: {\n coreRowModel?: RowModelFactory<TData>\n filteredRowModel?: RowModelFactory<TData>\n sortedRowModel?: RowModelFactory<TData>\n paginatedRowModel?: RowModelFactory<TData>\n groupedRowModel?: RowModelFactory<TData>\n expandedRowModel?: RowModelFactory<TData>\n }\n columns: Array<ColumnDef<TFeatures, TData>>\n data: ReadonlyArray<TData>\n /**\n * Optional row-id resolver. When set, the value it returns becomes\n * `row.id` (and therefore the selection / expansion / edit key). When\n * omitted, ids fall back to the row's array index as a string. Use a\n * stable id (database PK, UUID, etc.) so selection survives reorders.\n */\n getRowId?: (row: TData, index: number) => string\n state?: Partial<Record<string, any>>\n onSortingChange?: (updater: Updater<SortingState>) => void\n onColumnFiltersChange?: (updater: Updater<ColumnFiltersState>) => void\n onPaginationChange?: (updater: Updater<PaginationState>) => void\n onGroupingChange?: (updater: Updater<GroupingState>) => void\n onExpandedChange?: (updater: Updater<ExpandedState>) => void\n onRowSelectionChange?: (updater: Updater<RowSelectionState>) => void\n onActiveCellChange?: (updater: Updater<ActiveCellState>) => void\n}\n```\n\n### `type SvGrid`\n\nThe headless grid instance: the state stores plus the read methods a renderer\nneeds (`getHeaderGroups()`, `getRowModel()`, the `set*` writers).\n\nFramework free by design - `<SvGrid>` is one renderer over this, and you can\nwrite another. See the \"Why headless?\" guide.\n\n```ts\nexport type SvGrid<TData extends RowData> = {\n store: Store<Record<string, any>>\n optionsStore: Store<Record<string, any>>\n state: Record<string, any>\n getState: () => Record<string, any>\n setOptions: (updater: Updater<Record<string, any>>) => void\n setColumnFilters: (updater: Updater<ColumnFiltersState>) => void\n setPagination: (updater: Updater<PaginationState>) => void\n setGrouping: (updater: Updater<GroupingState>) => void\n setExpanded: (updater: Updater<ExpandedState>) => void\n setRowSelection: (updater: Updater<RowSelectionState>) => void\n setActiveCell: (updater: Updater<ActiveCellState>) => void\n moveActiveCell: (next: { rowDelta?: number; colDelta?: number }) => void\n getAllColumns: () => Array<Column<TData>>\n getHeaderGroups: () => Array<HeaderGroup<TData>>\n getFooterGroups: () => Array<HeaderGroup<TData>>\n getRowModel: () => RowModel<TData>\n}\n```\n\n### `function createSvGridCore`\n\nBuild a headless grid: state, the row pipeline, and the read methods, with no\nDOM and no Svelte. This is the engine `<SvGrid>` renders.\n\nMost callers want `createSvGrid` (the runes-aware wrapper) or the component\nitself; reach for this when you are writing your own renderer or running the\npipeline outside a browser.\n\n```ts\nexport function createSvGridCore<TFeatures extends TableFeatures, TData extends RowData>(\n options: SvGridOptions<TFeatures, TData>,\n): SvGrid<TData> {\n const internalState: Record<string, any> = {\n sorting: [],\n columnFilters: [],\n pagination: { pageIndex: 0, pageSize: options.data.length || 10 },\n grouping: [],\n expanded: {},\n rowSelection: {},\n activeCell: { rowIndex: 0, colIndex: 0, cellId: null },\n ...(options.state ?? {}),\n }\n const store = createStore(internalState)\n const optionsStore = createStore(options as Record<string, any>)\n let cachedColumnsInput: Array<ColumnDef<TFeatures, TData>> | null = null\n let cachedColumns: Array<Column<TData>> = []\n let cachedHeaderGroups: Array<HeaderGroup<TData>> = []\n let cachedBaseRowsInput: ReadonlyArray<TData> | null = null\n let cachedBaseRowsColumns: Array<Column<TData>> | null = null\n let cachedBaseRows: Array<Row<TData>> = []\n /** Old row -> new row for the rebuild the next pipeline run follows; see `replacedRowsOf`. */\n let replacedRows: Map<Row<TData>, Row<TData>> | null = null\n let cachedRowCtx: BaseRowCtx<TData> | null = null\n /** This grid's windowed-data row model, made on first use from the installed hook. */\n let windowedRowModel: WindowedRowModel<TData> | null = null\n\n /** The shared row context for `columns`, reused while they are the same. */\n function rowCtxFor(columns: Array<Column<TData>>): BaseRowCtx<TData> {\n if (cachedRowCtx && cachedRowCtx.columns === columns) return cachedRowCtx\n const columnIndexById = new Map<string, number>()\n for (let i = 0; i < columns.length; i++) columnIndexById.set(columns[i]!.id, i)\n cachedRowCtx = {\n grid: grid as SvGrid<TData>,\n store,\n columns,\n columnCount: columns.length,\n columnIndexById,\n }\n return cachedRowCtx\n }\n\n let cachedRowModel: RowModel<TData> | null = null\n let cachedRowModelBaseRows: Array<Row<TData>> | null = null\n let cachedPipeline = options._rowModels\n let cachedSlices: {\n sorting: SortingState | undefined\n columnFilters: ColumnFiltersState | undefined\n pagination: PaginationState | undefined\n grouping: GroupingState | undefined\n expanded: ExpandedState | undefined\n } | null = null\n\n const grid = {\n store,\n optionsStore,\n get state() {\n return store.state\n },\n getState() {\n return store.state\n },\n setOptions(updater: Updater<Record<string, any>>) {\n optionsStore.setState((prev) =>\n typeof updater === 'function' ? (updater as any)(prev) : updater,\n )\n },\n setColumnFilters(updater: Updater<ColumnFiltersState>) {\n store.setState((prev) => ({\n ...prev,\n columnFilters:\n typeof updater === 'function' ? (updater as any)(prev.columnFilters ?? []) : updater,\n }))\n options.onColumnFiltersChange?.(updater)\n },\n setPagination(updater: Updater<PaginationState>) {\n store.setState((prev) => ({\n ...prev,\n pagination:\n typeof updater === 'function'\n ? (updater as any)(prev.pagination ?? { pageIndex: 0, pageSize: 10 })\n : updater,\n }))\n options.onPaginationChange?.(updater)\n },\n setGrouping(updater: Updater<GroupingState>) {\n store.setState((prev) => ({\n ...prev,\n grouping: typeof updater === 'function' ? (updater as any)(prev.grouping ?? []) : updater,\n }))\n options.onGroupingChange?.(updater)\n },\n setExpanded(updater: Updater<ExpandedState>) {\n store.setState((prev) => ({\n ...prev,\n expanded: typeof updater === 'function' ? (updater as any)(prev.expanded ?? {}) : updater,\n }))\n options.onExpandedChange?.(updater)\n },\n setRowSelection(updater: Updater<RowSelectionState>) {\n store.setState((prev) => ({\n ...prev,\n rowSelection:\n typeof updater === 'function' ? (updater as any)(prev.rowSelection ?? {}) : updater,\n }))\n options.onRowSelectionChange?.(updater)\n },\n setActiveCell(updater: Updater<ActiveCellState>) {\n store.setState((prev) => {\n const previous: ActiveCellState = prev.activeCell ?? {\n rowIndex: 0,\n colIndex: 0,\n cellId: null,\n }\n const nextActive =\n typeof updater === 'function' ? updater(previous) : updater\n return {\n ...prev,\n activeCell: nextActive,\n }\n })\n options.onActiveCellChange?.(updater)\n },\n moveActiveCell(next: { rowDelta?: number; colDelta?: number }) {\n const rows = grid.getRowModel().rows\n const columns = grid.getAllColumns()\n const maxRow = Math.max(rows.length - 1, 0)\n const maxCol = Math.max(columns.length - 1, 0)\n const current: ActiveCellState = grid.getState().activeCell ?? {\n rowIndex: 0,\n colIndex: 0,\n cellId: null,\n }\n\n const rowIndex = Math.min(\n Math.max(current.rowIndex + (next.rowDelta ?? 0), 0),\n maxRow,\n )\n const colIndex = Math.min(\n Math.max(current.colIndex + (next.colDelta ?? 0), 0),\n maxCol,\n )\n const columnId = columns[colIndex]?.id ?? 'col_0'\n grid.setActiveCell({\n rowIndex,\n colIndex,\n cellId: `${rowIndex}_${columnId}`,\n })\n },\n getAllColumns() {\n // Cache hit: referentially identical columns array.\n if (cachedColumnsInput === options.columns && cachedColumns.length) {\n return cachedColumns\n }\n // Soft cache hit: consumers commonly recreate the columns array\n // inline on every render (e.g. `columns={[...]}`). If the new\n // array has the same length AND each entry has the same `field` /\n // `id` / `header` (the visibility-affecting structure of a\n // column), trust the previous build. Mutable inner fields like\n // `cell` and `editorOptions` are still picked up on the next real\n // render that bumps an actual data dep - they're read at cell-\n // render time, not at this top-level cache.\n if (\n cachedColumnsInput &&\n options.columns.length === cachedColumnsInput.length &&\n cachedColumns.length === options.columns.length &&\n options.columns.every((c, i) => {\n const prev = cachedColumnsInput![i]!\n return (\n c.field === prev.field &&\n c.id === prev.id &&\n c.header === prev.header &&\n c.editorType === prev.editorType &&\n // A field's options and format live in fieldProps; a reused\n // column would keep drawing the old ones.\n c.fieldType === prev.fieldType &&\n c.fieldProps === prev.fieldProps\n )\n })\n ) {\n // Update the stored input reference so the strict check hits\n // next time, but reuse the built column model.\n cachedColumnsInput = options.columns\n return cachedColumns\n }\n\n cachedColumnsInput = options.columns\n cachedHeaderGroups = []\n const build = (\n defs: Array<ColumnDef<TFeatures, TData>>,\n depth: number,\n parentId?: string,\n ): Array<Column<TData>> => {\n const leaves: Array<Column<TData>> = []\n defs.forEach((columnDef, index) => {\n const id = resolveColumnId(columnDef, parentId, depth, index)\n if (columnDef.columns?.length) {\n leaves.push(...build(columnDef.columns, depth + 1, id))\n return\n }\n leaves.push({\n id,\n depth,\n parentId,\n columnDef,\n getCanSort: () =>\n Boolean((options._features as any).rowSortingFeature) &&\n columnDef.sortable !== false,\n getCanFilter: () =>\n Boolean((options._features as any).columnFilteringFeature) &&\n columnDef.filterable !== false,\n getIsSorted: () => {\n const entry = store.state.sorting?.find((s: any) => s.id === id)\n if (!entry) return false\n return entry.desc ? 'desc' : 'asc'\n },\n getToggleSortingHandler: () => () => {\n const clauses: SortingState = store.state.sorting ?? []\n const current = clauses.find((s: any) => s.id === id)\n const nextClause: SortingState = !current\n ? [...clauses, { id, desc: false }]\n : current.desc\n ? clauses.filter((s) => s.id !== id)\n : clauses.map((s) => (s.id === id ? { ...s, desc: true } : s))\n store.setState((prev) => ({ ...prev, sorting: nextClause }))\n options.onSortingChange?.(nextClause)\n },\n })\n })\n return leaves\n }\n cachedColumns = build(options.columns, 0)\n return cachedColumns\n },\n getHeaderGroups() {\n if (cachedHeaderGroups.length) return cachedHeaderGroups\n const headers = grid.getAllColumns().map((column) => {\n const header: Header<TData> = {\n id: column.id,\n isPlaceholder: false,\n colSpan: 1,\n column,\n getContext: () => ({ header, column, table: grid }),\n }\n return header\n })\n cachedHeaderGroups = [{ id: 'header_group_0', headers }]\n return cachedHeaderGroups\n },\n getFooterGroups() {\n return grid.getHeaderGroups()\n },\n getRowModel() {\n const columns = grid.getAllColumns()\n // Read once. `options.data` is a getter when <SvGrid> drives the engine\n // (a $state.raw signal), and the rebuild below touched it twice per row:\n // 200k tracked reads per 100k-row tick, 11 ms of a 65 ms tick.\n const data = options.data\n if (installWindowedRowModel) {\n windowedRowModel ??= installWindowedRowModel<TData>({ rowCtxFor, getRowId: () => options.getRowId })\n const model = windowedRowModel(data, columns)\n if (model) return model\n }\n if (cachedBaseRowsInput !== data || cachedBaseRowsColumns !== columns) {\n // Same columns as last time: the shared context still describes them,\n // and a row whose data object sits at the same index can keep its\n // row object. A row model that streams blocks hands the grid a new\n // array of 60k entries per block where 100 changed; building 60k\n // fresh row objects each time was most of the cost of a block\n // landing. The reused row drops its memoised values and cells, since\n // an app may have changed the object in place before passing a new\n // array - that is the case the old rebuild covered by accident.\n // A lazy row list (lazyRows below) is read through its backing array,\n // so reusing rows never makes the ones nobody looked at.\n const previous = cachedBaseRowsColumns === columns && cachedRowCtx ? (lazyRowsBacking(cachedBaseRows) ?? cachedBaseRows) : null\n const previousInput = cachedBaseRowsInput\n // Same length as last time: a replacement, not an add or remove, so\n // each new row stands in for the old row at its index and the stages\n // can repair rather than recompute. Anything else is structural.\n replacedRows = previous && previous.length === data.length ? new Map() : null\n cachedBaseRowsInput = data\n cachedBaseRowsColumns = columns\n // O(1) column-id → index lookup so getCellValueByColumnId doesn't do\n // a linear `findIndex` on every cell read (was O(rows × cells × cols)).\n let rowCtx: BaseRowCtx<TData>\n if (previous && cachedRowCtx) {\n rowCtx = cachedRowCtx\n } else {\n const columnIndexById = new Map<string, number>()\n for (let i = 0; i < columns.length; i++) columnIndexById.set(columns[i]!.id, i)\n // One shared context for every row in this table, so a row carries a\n // pointer rather than a closure scope. See BASE_ROW_METHODS.\n rowCtx = {\n grid: grid as SvGrid<TData>,\n store,\n columns,\n columnCount: columns.length,\n columnIndexById,\n }\n cachedRowCtx = rowCtx\n }\n\n const getRowId = options.getRowId\n const m = BASE_ROW_METHODS as unknown as {\n getCanExpand: Row<TData>['getCanExpand']\n getIsExpanded: Row<TData>['getIsExpanded']\n toggleExpanded: Row<TData>['toggleExpanded']\n getIsSelected: Row<TData>['getIsSelected']\n toggleSelected: Row<TData>['toggleSelected']\n getAllCells: Row<TData>['getAllCells']\n getCellValueByColumnId: Row<TData>['getCellValueByColumnId']\n }\n // `_values` and `_cells` stay null until something reads them - a\n // 100k-row grid showing twenty rows must not materialise every row's\n // values or cell objects to paint.\n const makeRow = (index: number): BaseRowState<TData> => {\n const original = data[index]!\n return {\n id: getRowId ? getRowId(original, index) : String(index),\n index,\n original,\n depth: 0,\n [ROW_CTX]: rowCtx,\n [ROW_VALUES]: null,\n [ROW_CELLS]: null,\n [ROW_FILTER_GEN]: 0,\n [ROW_FILTER_POS]: -1,\n [ROW_SORT_DROPPED]: 0,\n [ROW_SORT_KEY]: undefined,\n getCanExpand: m.getCanExpand,\n getIsExpanded: m.getIsExpanded,\n toggleExpanded: m.toggleExpanded,\n getIsSelected: m.getIsSelected,\n toggleSelected: m.toggleSelected,\n getAllCells: m.getAllCells,\n getCellValueByColumnId: m.getCellValueByColumnId,\n }\n }\n if (!previous) {\n // A first build has nothing to reuse or repair: make each row the\n // first time something reads it. A grid that only shows the first\n // screen makes ~40 row objects, not 100k; a sort or a filter reads\n // every row and makes them then. Building them all up front was\n // most of a 100k-row mount (~24 ms, plus the garbage).\n cachedBaseRows = lazyRows(data.length, makeRow)\n } else cachedBaseRows = new Array(data.length)\n for (let index = 0; previous && index < data.length; index++) {\n const original = data[index]!\n const kept = previous[index] as BaseRowState<TData> | undefined\n if (kept && kept.original === original) {\n // Read before writing: a row nobody rendered (a million off-screen\n // placeholders under a row model) has nothing memoised, and a\n // store per row was a measurable share of each block landing.\n if (kept[ROW_VALUES] !== null) kept[ROW_VALUES] = null\n if (kept[ROW_CELLS] !== null) kept[ROW_CELLS] = null\n cachedBaseRows[index] = kept\n continue\n }\n // Past a quarter of the rows the merge stops being cheaper than a\n // sort with the ranking pass; let the stages do the full work.\n if (replacedRows && replacedRows.size * 4 >= data.length) replacedRows = null\n const row = makeRow(index)\n // The previous list was lazy and never made this row, but its data\n // object is the same one: hand the old list this row too, so a\n // caller still holding it gets the same object for the same data,\n // as when every row was built up front.\n if (kept === undefined && previousInput?.[index] === original) previous[index] = row\n cachedBaseRows[index] = row\n if (replacedRows && kept) replacedRows.set(kept, row)\n }\n // A new array with every object the same is the documented way to\n // say \"I changed rows in place, re-read them\" (docs/help/cells/\n // view-refresh.md). Nothing was replaced, so there is nothing to\n // repair around: the stages recompute from the current values. A\n // repair assumes the rows it keeps are unchanged in value as well as\n // identity, which is the immutable-update contract a tick follows.\n if (replacedRows && replacedRows.size === 0) replacedRows = null\n }\n\n // Only the slices a pipeline stage actually READS belong in this key.\n //\n // `rowSelection` used to be here, which meant ticking one checkbox on a\n // 100k-row grid re-filtered and re-sorted the entire dataset to rebuild a\n // row array that was identical by construction. Nothing reads it: the two\n // consumers are `getIsSelected` closures (on data rows and on group rows)\n // that read `store.state` when called, so they observe a selection change\n // without the model being rebuilt.\n //\n // `_rowModels` is a closed set of six named slots, so no consumer stage\n // can be inserted that might read selection. A caller CAN supply a custom\n // function for one of those slots; if one ever needs a slice that is not\n // listed here, add it here rather than reinstating all of them.\n const currentSlices = {\n sorting: store.state.sorting,\n columnFilters: store.state.columnFilters,\n pagination: store.state.pagination,\n grouping: store.state.grouping,\n expanded: store.state.expanded,\n }\n if (\n cachedRowModel &&\n cachedRowModelBaseRows === cachedBaseRows &&\n cachedPipeline === options._rowModels &&\n cachedSlices?.sorting === currentSlices.sorting &&\n cachedSlices?.columnFilters === currentSlices.columnFilters &&\n cachedSlices?.pagination === currentSlices.pagination &&\n cachedSlices?.grouping === currentSlices.grouping &&\n cachedSlices?.expanded === currentSlices.expanded\n ) {\n return cachedRowModel\n }\n\n // A stage with work to do reads every row; give it the dense array.\n const anyStageActive =\n (currentSlices.sorting?.length ?? 0) > 0 ||\n (currentSlices.columnFilters?.length ?? 0) > 0 ||\n (currentSlices.grouping?.length ?? 0) > 0 ||\n (currentSlices.expanded as unknown) === true ||\n Object.keys(currentSlices.expanded ?? {}).length > 0\n let rows: Array<Row<TData>> = anyStageActive ? denseRows(cachedBaseRows) : cachedBaseRows\n\n const pipeline = options._rowModels ?? {}\n const ordered: Array<RowModelFactory<TData> | undefined> = [\n pipeline.coreRowModel,\n pipeline.filteredRowModel,\n pipeline.sortedRowModel,\n pipeline.groupedRowModel,\n pipeline.expandedRowModel,\n pipeline.paginatedRowModel,\n ]\n // The stages read the replacements through `replacedRowsOf` while the\n // run lasts; a stage that runs outside one sees null.\n replacedRowsByGrid.set(grid, replacedRows)\n try {\n ordered.forEach((fn) => {\n if (fn) rows = fn({ table: grid, rows })\n })\n } finally {\n replacedRowsByGrid.set(grid, null)\n replacedRows = null\n }\n cachedPipeline = options._rowModels\n cachedSlices = currentSlices\n cachedRowModelBaseRows = cachedBaseRows\n cachedRowModel = { rows }\n return cachedRowModel\n },\n } as InternalGrid<TData>\n\n return grid\n}\n```\n\n### `function isFunction`\n\nNarrowing helper for the many options that accept a value or a function.\n\n```ts\nexport function isFunction(value: unknown): value is (...args: Array<any>) => any {\n return typeof value === 'function'\n}\n```\n"
8017
+ "markdown": "# `@svgrid/grid` · `core.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\core.ts`.\n\n### `type RowData`\n\nThe constraint every row type satisfies: an object keyed by string. Your own\nrow type (`type Person = { name: string }`) is what flows through the generics\nbelow; this is only the lower bound they are declared against.\n\n```ts\nexport type RowData = Record<string, unknown>\n```\n\n### `type Updater`\n\nA new value, or a function that derives it from the previous one - the shape\nevery `set*` on the grid accepts, so callers can update state without first\nreading it.\n\n api.setSorting([{ id: 'name', desc: false }])\n api.setSorting((prev) => [...prev, { id: 'age', desc: true }])\n\n```ts\nexport type Updater<T> = T | ((prev: T) => T)\n```\n\n### `type SortingState`\n\nActive sort clauses, outermost first. `desc: false` is ascending.\n\n```ts\nexport type SortingState = Array<{ id: string; desc: boolean }>\n```\n\n### `type ColumnFilter`\n\nOne column's filter: the column `id`, the `value` being matched, and\noptionally which comparison to use. `fn` defaults to the column's own type -\nsee {@link filterFns} for the available names.\n\n```ts\nexport type ColumnFilter = { id: string; value: unknown; fn?: keyof typeof filterFns }\n```\n\n### `type ColumnFiltersState`\n\nEvery active column filter. A column with no entry here is unfiltered.\n\n```ts\nexport type ColumnFiltersState = Array<ColumnFilter>\n```\n\n### `type PaginationState`\n\nCurrent page position. `pageIndex` is 0-based, so page 1 is index 0.\n\n```ts\nexport type PaginationState = { pageIndex: number; pageSize: number }\n```\n\n### `type GroupingState`\n\nColumn ids the rows are grouped by, outermost first.\n\n```ts\nexport type GroupingState = Array<string>\n```\n\n### `type ExpandedState`\n\nWhich rows are expanded, keyed by row id. Absent means collapsed.\n\n```ts\nexport type ExpandedState = Record<string, boolean>\n```\n\n### `type RowSelectionState`\n\nWhich rows are selected, keyed by row id. Absent means unselected.\n\n```ts\nexport type RowSelectionState = Record<string, boolean>\n```\n\n### `type ActiveCellState`\n\nWhere keyboard focus sits. The indices address the *displayed* grid (after\nsorting, filtering and paging), not the source data.\n\n```ts\nexport type ActiveCellState = {\n rowIndex: number\n colIndex: number\n cellId: string | null\n}\n```\n\n### `type TableFeatures`\n\nThe set of features a grid has registered, as built by {@link tableFeatures}.\nDeliberately open: a feature is identified by its key, so the type carries\nwhich ones are on without enumerating them.\n\n```ts\nexport type TableFeatures = Record<string, unknown>\n```\n\n### `type CellData`\n\nA cell's value. Unconstrained - a column can hold anything.\n\n```ts\nexport type CellData = unknown\n```\n\n### `type HeaderContext`\n\nWhat a column's `header` render function receives.\n\n```ts\nexport type HeaderContext<TData extends RowData> = {\n header: Header<TData>\n column: Column<TData>\n table: SvGrid<TData>\n}\n```\n\n### `type CellContext`\n\nWhat a column's `cell` render function receives. `getValue()` applies the\ncolumn's accessor (`field` or `fieldFn`); `row.original` is the raw object.\n\n```ts\nexport type CellContext<TData extends RowData> = {\n cell: Cell<TData>\n row: Row<TData>\n column: Column<TData>\n table: SvGrid<TData>\n getValue: () => unknown\n}\n```\n\n### `type CellSpanParams`\n\nParams passed to a column's `colSpan(...)` / `rowSpan(...)` callbacks.\n\n```ts\nexport type CellSpanParams<TData extends RowData = RowData> = {\n /** The row's underlying data object. */\n data: TData\n /** Display-row index in the current (filtered/sorted) row set. */\n rowIndex: number\n /** The column's id. */\n columnId: string\n /** The cell's base value for this column. */\n value: unknown\n}\n```\n\n### `type EditorOptionSource`\n\nThe raw option list a column's `editorOptions` can supply.\n\n```ts\nexport type EditorOptionSource = ReadonlyArray<\n string | number | { value: string | number; label?: string; color?: string }\n```\n\n### `type ValueParserParams`\n\nParams passed to a column's `valueParser(...)` on edit commit.\n\n```ts\nexport type ValueParserParams<TData extends RowData = RowData> = {\n /** The value after built-in per-`editorType` coercion. */\n newValue: unknown\n /** The cell's previous value. */\n oldValue: unknown\n /** The raw string the editor produced (pre-coercion). */\n rawInput: string\n /** The row's underlying data object. */\n data: TData\n /** The column's id. */\n columnId: string\n}\n```\n\n### `type EditorContext`\n\nContext passed to a custom `cellEditor` snippet/component. Three write\nhelpers cover the lifecycle:\n\n - `update(next)` - stage `next` as the draft, keep the editor open.\n Use this for live-preview controls (sliders,\n color pickers) so the user can keep adjusting.\n - `commit(next?)` - write the value AND close the editor. The\n argument is optional; when omitted, the most\n recently `update()`d value is saved. Use this\n for \"done\" gestures (Enter, picking an option).\n - `cancel()` - discard the draft and close the editor.\n\n```ts\nexport type EditorContext<TData extends RowData> = CellContext<TData> & {\n value: unknown\n update: (next: unknown) => void\n commit: (next?: unknown) => void\n cancel: () => void\n}\n```\n\n### `type CustomFilterContext`\n\nWhat a custom filter control receives, in the filter menu and in the\nfloating filter row. The grid owns the model; the control reads `model`\nand writes it back through `setModel`.\n\n```ts\nexport type CustomFilterContext<TData extends RowData, TModel = any> = {\n column: Column<TData>\n /** The column's current model, or `undefined` when none is set. */\n model: TModel | undefined\n /** Replace the model. `null` or `undefined` clears the filter. */\n setModel: (next: TModel | null | undefined) => void\n /**\n * Which surface is rendering the control: the filter menu, the floating\n * filter row, or the tool panel's Filters tab.\n */\n surface: 'menu' | 'floating' | 'panel'\n /**\n * The column's distinct values under every OTHER column's filter, the\n * same list the menu's Values checklist shows. Computed on call, so a\n * control that never asks pays nothing.\n */\n values: () => Array<string>\n /** Close the filter menu. Does nothing on the other surfaces. */\n close: () => void\n}\n```\n\n### `type CustomColumnFilter`\n\nA column filter whose state is your own model rather than an operator and\na value: a range slider's `[min, max]`, a tag picker's `string[]`, a\n\"last N days\" count.\n\nThe model lives in the grid (`api.setCustomFilter`, `getState().customFilters`)\nand is ANDed with the column's operator condition and its Values checklist,\nthe same as those two are with each other. Keep it JSON-serializable if you\nsave views.\n\n customFilter: {\n predicate: ([min, max]: [number, number]) => (value) =>\n Number(value) >= min && Number(value) <= max,\n menu: priceRange, // a Snippet<[CustomFilterContext]>\n floating: priceRange,\n }\n\n```ts\nexport type CustomColumnFilter<TData extends RowData, TModel = any> = {\n /**\n * Build the row test for a model. Runs once per filter change, not once\n * per row, so parse dates or build sets here. The returned function gets\n * the column's value and the row's data.\n */\n predicate: (model: TModel) => (value: unknown, row: TData) => boolean\n /**\n * Whether a model narrows anything. An inactive model is kept (the control\n * still shows it) but filters nothing and lights no funnel. Default: not\n * `null` / `undefined` / `''` / an empty array.\n */\n isActive?: (model: TModel) => boolean\n /**\n * The control in the filter menu and the tool panel's Filters tab, in\n * place of the operator condition. A Svelte snippet taking a\n * {@link CustomFilterContext}. Falls back to `floating` when omitted.\n */\n menu?: (context: CustomFilterContext<TData, TModel>) => unknown\n /**\n * The control in the floating filter row, in place of the operator button\n * and input. Falls back to `menu` when omitted.\n */\n floating?: (context: CustomFilterContext<TData, TModel>) => unknown\n /** Keep the Values checklist under the custom control in the menu. Default `true`. */\n showValues?: boolean\n}\n```\n\n### `type CellFormatConfig`\n\nDeclarative cell formatting, applied through `Intl` - number, currency,\npercent, date and datetime. Prefer this over a `formatter` function: it is\nlocale-aware, and export and the clipboard reuse the same configuration.\n\n```ts\nexport type CellFormatConfig =\n | {\n type: 'number'\n locales?: string | Array<string>\n options?: Intl.NumberFormatOptions\n }\n | {\n type: 'currency'\n /** ISO 4217 (default USD) */\n currency?: string\n locales?: string | Array<string>\n options?: Omit<Intl.NumberFormatOptions, 'style' | 'currency'>\n }\n | {\n type: 'percent'\n locales?: string | Array<string>\n options?: Omit<Intl.NumberFormatOptions, 'style'>\n /**\n * If true, numeric cell values are 0–100 (e.g. 42 → 42%) instead of Intl’s 0–1 fraction (0.42 → 42%).\n * Default false.\n */\n valueIsPercentPoints?: boolean\n }\n | {\n type: 'date' | 'datetime'\n locales?: string | Array<string>\n /**\n * Shortcut patterns merged with `options`:\n * `'d'` short numeric date, `'D'` long date, `'y-m-d'` yyyy/mm/dd-style,\n * `'short'`|`'medium'`|`'long'` use dateStyle/timeStyle presets.\n */\n pattern?: string\n options?: Intl.DateTimeFormatOptions\n }\n```\n\n### `type CellFormatter`\n\nA column's custom display function, for anything {@link CellFormatConfig}\ncannot express. Returns a string - to render markup, use `cell` instead.\n\n```ts\nexport type CellFormatter<TData extends RowData> = (context: {\n value: unknown\n row: Row<TData>\n column: Column<TData>\n table: SvGrid<TData>\n}) => string\n```\n\n### `type ColumnDefTemplate`\n\nA header or cell slot: a literal string, or a function returning renderable content.\n\n```ts\nexport type ColumnDefTemplate<TContext> = string | ((context: TContext) => unknown)\n```\n\n### `type GroupAggregator`\n\nHow a column's value is aggregated for a group row when `columnGrouping`\nis active. Built-in reducers cover the common cases; pass a function for\nanything custom (weighted average, median, percentile, distinct count).\nThe function receives the finite numeric values AND the raw leaf rows.\n\n```ts\nexport type GroupAggregator<TData = any> =\n | 'sum'\n | 'avg'\n | 'min'\n | 'max'\n | 'count'\n | 'countDistinct'\n | 'extent'\n | 'first'\n | ((values: number[], rows: Array<TData>) => unknown)\n```\n\n### `function applyGroupAggregate`\n\nApply a group aggregator over a bucket's leaf rows for one column.\n\n```ts\nexport function applyGroupAggregate<TData extends RowData>(\n agg: GroupAggregator<TData>,\n columnId: string,\n rows: ReadonlyArray<Row<TData>>,\n): unknown\n```\n\n### `type ColumnDef`\n\nA column definition.\n\n`TFeatures` is a phantom parameter - it is threaded through nested\n`columns` groups but no member depends on it, so `{}`, `TableFeatures` and\n`typeof features` are all interchangeable here. It is deliberately left\nWITHOUT a default: `ColumnDef<Row>` would otherwise bind `Row` to this slot\nand silently type your data as `RowData`, losing every field-name check.\nPrefer {@link GridColumns} / {@link GridColumnDef} for the common case.\n\n```ts\nexport type ColumnDef<TFeatures extends TableFeatures, TData extends RowData> = {\n id?: string\n field?: keyof TData & string\n fieldFn?: (row: TData) => unknown\n header?: ColumnDefTemplate<HeaderContext<TData>>\n footer?: ColumnDefTemplate<HeaderContext<TData>>\n cell?: ColumnDefTemplate<CellContext<TData>>\n /**\n * A field type registered by `@svgrid/enterprise/fields` (`'attachment'`,\n * `'rating'`, `'url'`, ...). With the module enabled the cell is drawn by\n * that type; a column's own `cell` still wins. Without it the column draws\n * as an ordinary one.\n */\n fieldType?: string\n /** Properties of `fieldType` (options, precision, max files, ...). */\n fieldProps?: Record<string, unknown>\n columns?: Array<ColumnDef<TFeatures, TData>>\n /**\n * Declarative cell spanning (merged cells). Return how many COLUMNS this\n * cell spans to the right (1 = no span). Value-driven. Feed\n * `spansToMerges(rows, columns)` into `spreadsheetLayout` to apply - it uses\n * the same real `colspan`/`rowspan` merge engine (no separate code path).\n */\n colSpan?: (params: CellSpanParams<TData>) => number\n /**\n * Declarative cell spanning (merged cells). Return how many ROWS this cell\n * spans downward (1 = no span). See `colSpan` for how to apply.\n */\n rowSpan?: (params: CellSpanParams<TData>) => number\n /**\n * What the column's values are. It decides sorting, filter operators and\n * alignment, whatever edits the cell: `editorType` only picks the editor,\n * so a number column can be typed in a text box or a custom editor and\n * still sort, filter and align as numbers.\n * 'text' → left-aligned, text filters (text editor by default)\n * 'number' → right-aligned, numeric sort and filters (number editor)\n * 'boolean' → centered, true / false filter (checkbox editor)\n * 'date' → Date values, right-aligned, date sort and filters (date\n * editor, `{ type: 'date' }` format)\n * 'dateString' → ISO date STRINGS (e.g. '2026-06-27'), as a date\n * Anything you set explicitly (`editorType`, `align`, `format`) still wins.\n * Without it, a built-in `editorType` (`number`, `date`, `datetime`,\n * `checkbox`) implies the type, as before; grid-level `inferColumnTypes`\n * infers it from the first data row for columns with neither.\n */\n cellDataType?: 'text' | 'number' | 'boolean' | 'date' | 'dateString'\n /**\n * Hide this column when the grid's `responsive` mode is on and the grid is\n * narrower than this many pixels - drop low-priority columns on small\n * screens. No effect unless the grid has `responsive` set.\n */\n hideBelow?: number\n /**\n * For a column INSIDE a collapsible column group: `'open'` shows this column\n * only while the group is expanded, `'closed'` only while collapsed. Omit to\n * always show it. Setting it on any direct child gives the parent group a\n * collapse toggle. Pair with `openByDefault` on the group.\n */\n columnGroupShow?: 'open' | 'closed'\n /**\n * For a GROUP column (one with `columns: [...]`): start the group expanded.\n * Defaults to `false` (collapsed), the conventional default - so only the always-on\n * and `columnGroupShow: 'closed'` children show until the user expands it.\n */\n openByDefault?: boolean\n editorType?:\n | 'text'\n | 'number'\n | 'date' // rich SvCalendar popover (opt out with 'date-native')\n | 'datetime' // rich SvDateTimePicker (opt out with 'datetime-native')\n | 'time' // rich SvTimePicker dial (opt out with 'time-native')\n | 'date-native' // plain <input type=\"date\">\n | 'datetime-native' // plain <input type=\"datetime-local\">\n | 'time-native' // plain <input type=\"time\"> - HH:MM or HH:MM:SS\n | 'password' // native <input type=\"password\"> with masked rendering\n | 'checkbox'\n | 'list'\n | 'chips'\n | 'select' // custom dropdown - single value, no typeahead\n | 'rich-select' // custom dropdown with a typeahead search input\n | 'autocomplete' // free-text input with a live-filtered suggestion list (accepts any value)\n | 'textarea' // multi-line editor; Tab or Ctrl+Enter commits, plain Enter inserts a newline\n | 'color' // native <input type=\"color\"> swatch\n | 'rating' // 5-star rating control\n // Any other string names a CUSTOM editor registered via `registerCellEditor`\n // (or `registerBuiltinEditors`). `(string & {})` keeps the literals above\n // autocompleting while allowing arbitrary custom type names.\n | (string & {})\n /**\n * Custom in-cell editor. Receives the cell context PLUS a `commit(value)`\n * and `cancel()` helper. Use when none of the built-in `editorType`s fit;\n * the snippet's outer element is mounted inside the editing cell and\n * inherits keyboard handling (Esc cancels, Enter commits unless your\n * snippet preventDefaults it).\n *\n * Coexists with `editorType`: when both are set, `cellEditor` wins and\n * `editorType` is treated as a hint for parsing the saved value.\n */\n cellEditor?: ColumnDefTemplate<EditorContext<TData>>\n /**\n * The text format of the date / datetime editor's box, in date-format\n * tokens (`'MMMM d, yyyy'`, `'MM/dd/yyyy h:mm tt'`), so an edit shows the\n * date the way the cell does. Default `'yyyy-MM-dd'`, with time\n * `'yyyy-MM-dd HH:mm'`.\n */\n editorFormatString?: string\n /**\n * Per-column tooltip. String shows as a native `title=`; `(ctx) => string`\n * runs per cell so the tooltip can reflect the value. Returning an empty\n * string skips the tooltip.\n */\n tooltip?: string | ((ctx: CellContext<TData>) => string | null | undefined)\n /**\n * Declarative per-cell validation. Runs for EVERY\n * rendered cell - including values already present in `data` on load, not\n * just on edit - so bad data is flagged immediately. Invalid cells get the\n * `sv-grid-cell-invalid` class (red highlight) and the returned message as\n * their tooltip.\n *\n * Return value:\n * - `null` / `undefined` / `true` → valid (no highlight)\n * - `false` → invalid, no message\n * - a non-empty `string` → invalid, string is the tooltip\n *\n * On its own `validate` flags: the value keeps rendering as-is and an\n * edit that fails it still lands. Set `rejectInvalid` to refuse such an\n * edit instead.\n */\n validate?: (params: {\n value: unknown\n row: TData\n rowIndex: number\n column: Column<TData>\n }) => string | boolean | null | undefined\n /**\n * Refuse an edit that `validate` flags. When true, a committed value that\n * makes `validate` return `false` or a message is not written: the cell\n * keeps its old value, no history step is recorded and\n * `onCellValueChange` does not fire. The value is checked after\n * `valueParser` has run, so the rule sees what would be stored. Applies to\n * the inline editor, a commit to a selection and a full-row edit; paste\n * does not go through the editor and is not checked.\n */\n rejectInvalid?: boolean\n /**\n * Gate editing per column or per cell.\n *\n * - `true` (or omitted): the column is fully editable.\n * - `false`: the column is read-only - double-click, type-to-edit,\n * fill-handle drag, Delete, and clipboard paste all skip it.\n * - `(ctx) => boolean`: evaluated for each cell, so you can lock\n * individual rows (e.g. by role, status, ownership). Returning\n * `false` opts the cell out of every editing path, identical to\n * setting `editable: false` on the whole column for that row.\n *\n * The grid-wide `enableInlineEditing` prop still wins when set to\n * `false`.\n */\n editable?: boolean | ((context: CellContext<TData>) => boolean)\n /**\n * Transform the committed edit value before it is written to the row.\n * Runs after the built-in per-`editorType` coercion, so `newValue` is\n * already type-parsed; return the final value to store (e.g. round a\n * number, uppercase a code, look up an id). A `valueParser` hook.\n */\n valueParser?: (params: ValueParserParams<TData>) => unknown\n /**\n * Briefly flash / highlight this column's cell when its value changes\n * (streaming feeds, edits, server pushes). `true` uses the default flash;\n * pass `{ className }` to apply your own animation class instead.\n */\n cellFlash?: boolean | { className?: string }\n /**\n * When `false`, this column never shows a sort indicator and clicking\n * its header is a no-op - `api.setSort(thisColumn, ...)` is also\n * ignored. Defaults to `true` (the column participates in sorting as\n * long as `rowSortingFeature` is registered).\n */\n sortable?: boolean\n /**\n * When `false`, this column never shows a filter funnel / menu and\n * `api.setFilter(thisColumn, ...)` is ignored. Defaults to `true` (the\n * column is filterable as long as `columnFilteringFeature` is\n * registered).\n */\n filterable?: boolean\n /**\n * Replace the built-in filter condition with your own control and model.\n * See {@link CustomColumnFilter}. Without `menu` or `floating` the column\n * keeps the built-in UI and the model is set only through\n * `api.setCustomFilter`.\n */\n customFilter?: CustomColumnFilter<TData>\n /**\n * Options for `editorType: 'list' | 'chips'`. Either bare values (the\n * string is both value and label) or `{ value, label }` objects.\n * For `chips` this is optional - when omitted, the chips editor becomes\n * free-form (user types and presses Enter to commit a chip).\n *\n * Pass a function `(row) => options` for row-dependent (cascading)\n * options - e.g. City options that depend on Country in the same row.\n *\n * Either form may return a **Promise**, for options that come from the\n * server. While it resolves, the editor shows a loading state and the cell\n * renders its raw value.\n *\n * Results are cached so reopening an editor does not refetch: a static source\n * per column, a per-row source per row AND per that row's data - so a cascade\n * reloads by itself when the cell it depends on is edited. Call\n * `api.refreshEditorOptions(columnId?)` when the list changes server-side.\n */\n editorOptions?:\n | EditorOptionSource\n | Promise<EditorOptionSource>\n | ((row: TData) => EditorOptionSource | Promise<EditorOptionSource>)\n /** When true, list/chips allow multiple selections. Cell value becomes an array. */\n editorMultiple?: boolean\n /**\n * The text editor accepts line breaks: Alt+Enter inserts one and the\n * editor grows a line per break, while Enter still commits. What a\n * spreadsheet cell with wrapped text wants; `editorType: 'textarea'` is\n * the other shape, where Enter itself is the line break.\n */\n editorMultiline?: boolean\n /** Separator used when joining array values for the readonly cell display. Defaults to ', '. */\n editorSeparator?: string\n format?: CellFormatConfig\n formatter?: CellFormatter<TData>\n /**\n * The number this column sorts a value by, in place of the value: a status\n * option's position in its list, say, so \"To do\" comes before \"Done\".\n * Blanks and anything not a number sort first, as in a number column.\n */\n sortValue?: (value: unknown) => number | null | undefined\n /**\n * Compare two of this column's values yourself, in place of the built-in\n * order. `desc` is the direction being sorted; the grid reverses your result\n * for a descending sort, so return the ascending order unless you want a\n * value held at one end in both directions (`@svgrid/enterprise`'s\n * `blanksLast` does that). `sortValue` wins over it.\n */\n sortComparator?: (a: unknown, b: unknown, desc: boolean) => number\n /**\n * Aggregate this column's values into the group row when grouping is\n * active. `'sum' | 'avg' | 'min' | 'max' | 'count' | 'countDistinct' |\n * 'extent' | 'first'`, or a custom `(values, rows) => unknown`. The result\n * is formatted with this column's `format` and shown in the group header.\n */\n aggregate?: GroupAggregator<TData>\n /**\n * What this column contributes to the grid's footer summary row (the one\n * turned on with `summary` / `enableRowSummaries`). Takes the same\n * aggregators as {@link aggregate}, and the result is formatted with this\n * column's `format`.\n *\n * Without it the footer falls back to its default: the sum of a numeric\n * column, `Count: N` otherwise. Set `false` to leave the cell blank, which is\n * usually what an actions or checkbox column wants.\n *\n * { field: 'amount', summary: 'avg' }\n * { id: 'actions', summary: false }\n */\n summary?: GroupAggregator<TData> | false\n /**\n * Render the cell as an in-cell sparkline chart. The cell value should be\n * an array of numbers (or a comma/space separated string). Mutually\n * exclusive with a custom `cell` renderer (a `cell` wins if both are set).\n *\n * { sparkline: { type: 'line' } } // default line\n * { sparkline: { type: 'bar', color: '#16a34a' } }\n * { sparkline: { type: 'winloss' } } // sign-only up/down\n *\n * See `SparklineConfig` for the full option set (type, color,\n * negativeColor, width, height, fixed min/max).\n */\n sparkline?: SparklineConfig\n /** Initial column width in pixels. Falls back to the grid's `columnWidth` prop. */\n width?: number\n /**\n * Whether the user may resize this column. Only consulted when the grid has\n * `columnResize` on - it narrows that, it does not enable anything.\n *\n * `false` removes the column's drag handle entirely, so pointer drag, the\n * keyboard arrows and double-click-to-autosize are all gone with it, and the\n * column menu drops its Autosize item. Use it for the columns whose width is\n * part of the layout rather than a preference: a row-number gutter, a\n * checkbox column, a fixed icon column.\n *\n * Programmatic sizing is unaffected - `api.autosizeColumn()`,\n * `api.setColumnWidth()` and `fitColumns` all still apply, the same way they\n * do when `columnResize` is off. This governs the user affordance only.\n */\n resizable?: boolean\n /**\n * Initial visibility. Set `false` to start the column hidden while still\n * listing it in the Choose Columns UI for the user to re-enable. Applied\n * once at mount; after that `api.setColumnVisible` / user toggles win.\n * On a group column, `false` hides the whole group's leaf columns.\n */\n visible?: boolean\n /**\n * Horizontal alignment for header and body cells. When omitted, the\n * default is inferred from `editorType`:\n * - `'number' | 'date' | 'datetime'` → `'right'`\n * - `'checkbox'` → `'center'`\n * - everything else → `'left'`\n */\n align?: 'left' | 'center' | 'right'\n /**\n * Per-cell conditional CSS. Two shapes:\n *\n * - **String** (or array of strings): class name(s) added to the\n * cell's `<td>` for every row in this column.\n * - **Function**: invoked per cell with the same `CellContext` shape\n * the `cell` renderer receives. Return a string, an array of\n * strings, or an object mapping class names to booleans.\n *\n * Use it for status tinting, conditional bold, \"negative number\"\n * coloring - anything that's a function of the row's value. Cells\n * still receive their format / cell renderer; the class just\n * augments the rendered `<td>`.\n */\n cellClass?:\n | string\n | ReadonlyArray<string>\n | ((ctx: CellContext<TData>) => string | ReadonlyArray<string> | Record<string, boolean> | undefined | null)\n}\n```\n\n### `type GridColumnDef`\n\nA column definition keyed only by your row type - the ergonomic form of\n{@link ColumnDef}, whose first parameter is a phantom feature bag that is\nalmost always `{}`.\n\n```ts\nconst columns: GridColumns<Person> = [{ field: 'firstName', header: 'Name' }]\n```\n\nInterchangeable with `ColumnDef<{}, TData>` and `ColumnDef<typeof features,\nTData>` in both directions, so it mixes freely with existing code.\n\n```ts\nexport type GridColumnDef<TData extends RowData = RowData> = ColumnDef<TableFeatures, TData>\n```\n\n### `type GridColumns`\n\nAn array of {@link GridColumnDef} - what you pass to `<SvGrid columns={...}>`.\n\n```ts\nexport type GridColumns<TData extends RowData = RowData> = Array<GridColumnDef<TData>>\n```\n\n### `type Column`\n\nA resolved column: your {@link ColumnDef} plus everything the grid computed\nfrom it - its id, its depth under any group header, and the sort handlers a\nheader needs. This is what you receive in render contexts; the `ColumnDef`\nis what you wrote.\n\n```ts\nexport type Column<TData extends RowData> = {\n id: string\n columnDef: ColumnDef<any, TData>\n depth: number\n parentId?: string\n getCanSort: () => boolean\n getCanFilter: () => boolean\n getIsSorted: () => false | 'asc' | 'desc'\n getToggleSortingHandler: () => () => void\n}\n```\n\n### `type Header`\n\nOne header cell. `colSpan` is how many leaf columns it covers, and\n`isPlaceholder` marks the empty cells that pad a group-header row so the\nlevels line up.\n\n```ts\nexport type Header<TData extends RowData> = {\n id: string\n isPlaceholder: boolean\n colSpan: number\n column: Column<TData>\n getContext: () => HeaderContext<TData>\n}\n```\n\n### `type HeaderGroup`\n\nOne row of header cells. A grid with grouped columns has several, outermost first.\n\n```ts\nexport type HeaderGroup<TData extends RowData> = {\n id: string\n headers: Array<Header<TData>>\n}\n```\n\n### `type Cell`\n\nOne cell: the intersection of a {@link Row} and a {@link Column}.\n\n```ts\nexport type Cell<TData extends RowData> = {\n id: string\n row: Row<TData>\n column: Column<TData>\n getValue: () => unknown\n getContext: () => CellContext<TData>\n}\n```\n\n### `type Row`\n\nA row in the display model. `original` is your untouched data object;\neverything else is grid-computed. `index` is the position in the displayed\nset, so it shifts as sorting and filtering change - key on `id`, not index.\n\nGroup rows and tree parents carry `subRows`; a plain data row does not.\n\n```ts\nexport type Row<TData extends RowData> = {\n id: string\n index: number\n original: TData\n depth: number\n subRows?: Array<Row<TData>>\n /** Total leaf (data) rows under this group row. Undefined for data rows. */\n leafCount?: number\n getCanExpand: () => boolean\n getIsExpanded: () => boolean\n toggleExpanded: () => void\n getIsSelected: () => boolean\n toggleSelected: () => void\n getAllCells: () => Array<Cell<TData>>\n getCellValueByColumnId: (columnId: string) => unknown\n}\n```\n\n### `type RowModel`\n\nThe output of the row pipeline: the rows to display, in order.\n\n```ts\nexport type RowModel<TData extends RowData> = {\n rows: Array<Row<TData>>\n}\n```\n\n### `type Store`\n\nThe minimal reactive store behind the headless core - read `state`, write\nthrough `setState`, and `subscribe` for changes. Deliberately framework\nfree, which is what lets the core run under plain Node.\n\nIn Svelte you rarely touch this: `subscribeGrid` wraps it with fine-grained\nselectors so a component only re-runs for the slice it read.\n\n```ts\nexport type Store<T> = {\n readonly state: T\n setState: (updater: (prev: T) => T) => void\n subscribe: (listener: () => void) => () => void\n}\n```\n\n### `const rowSortingFeature`\n\nClick-to-sort. Injected by the `sortable` shortcut.\n\nThis and the five features below are opaque markers: pass the ones you want\nto {@link tableFeatures} and the grid wires up the matching row model. With\n`<SvGrid>` you rarely name them - the boolean shortcuts (`sortable`,\n`filterable`, `pageable`, `groupable`) inject them for you. Reach for them\ndirectly when driving the headless core, or when you want a feature on\nwithout its UI.\n\nThe names match TanStack Table v9, so a features object written for it works\nhere unchanged.\n\n```ts\nexport const rowSortingFeature = { key: 'rowSortingFeature' }\n```\n\n### `const columnFilteringFeature`\n\nPer-column filtering. Injected by the `filterable` shortcut.\n\n```ts\nexport const columnFilteringFeature = { key: 'columnFilteringFeature' }\n```\n\n### `const rowPaginationFeature`\n\nPaging of the row model. Injected by the `pageable` shortcut.\n\n```ts\nexport const rowPaginationFeature = { key: 'rowPaginationFeature' }\n```\n\n### `const columnGroupingFeature`\n\nRow grouping with aggregation. Injected by the `groupable` shortcut.\n\n```ts\nexport const columnGroupingFeature = { key: 'columnGroupingFeature' }\n```\n\n### `const rowSelectionFeature`\n\nRow selection state (the checkbox column reads it).\n\n```ts\nexport const rowSelectionFeature = { key: 'rowSelectionFeature' }\n```\n\n### `const rowExpandingFeature`\n\nExpand / collapse, for tree rows and master-detail.\n\n```ts\nexport const rowExpandingFeature = { key: 'rowExpandingFeature' }\n```\n\n### `function tableFeatures`\n\nDeclare which features a grid uses. Identity at runtime - its whole job is to\ncapture the exact set in the type, so `ColumnDef<typeof features, Row>` knows\nwhat is registered and anything you did not register is tree-shaken out.\n\n```ts\nconst features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n```\n\nSame call signature as TanStack Table v9, so a features object written for it\ntransfers unchanged.\n\n```ts\nexport function tableFeatures<T extends TableFeatures>(features: T): T\n```\n\n### `const sortFns`\n\nBuilt-in comparators, chosen per column by its data type. `auto` compares as\ntext; set a column's type or supply your own comparator to override.\n\n```ts\nexport const sortFns = {\n auto: (a: unknown, b: unknown) => compareAutoValues(a, b),\n number: (a: unknown, b: unknown) => compareNumericKeys(numberSortKey(a), numberSortKey(b)),\n date: (a: unknown, b: unknown) => compareNumericKeys(dateSortKey(a), dateSortKey(b)),\n}\n```\n\n### `const filterFns`\n\nBuilt-in match functions, named by {@link ColumnFilter}'s `fn`.\n`includesString` is case-insensitive substring; `equals` is strict identity.\n\n```ts\nexport const filterFns = {\n includesString: (value: unknown, query: string) =>\n String(value).toLowerCase().includes(query.toLowerCase()),\n equals: (value: unknown, query: unknown) => value === query,\n}\n```\n\n### `type BaseRowCtx`\n\nEverything a base row needs that is the same for every row in the table.\n\nOne object per table, referenced by every row, instead of one closure scope\nper row. See {@link BASE_ROW_METHODS}.\n\n```ts\nexport type BaseRowCtx<TData extends RowData> = {\n grid: SvGrid<TData>\n store: { state: Record<string, any> }\n columns: Array<Column<TData>>\n columnCount: number\n columnIndexById: Map<string, number>\n}\n```\n\n### `const ROW_VALUES`\n\nA base row's cached cell values. @internal\n\n```ts\nexport const ROW_VALUES = Symbol('svgrid.row.values')\n```\n\n### `const ROW_CELLS`\n\nA base row's cached cells. @internal\n\n```ts\nexport const ROW_CELLS = Symbol('svgrid.row.cells')\n```\n\n### `const ROW_FILTER_POS`\n\nThe row's index in the last full filter's output (see ROW_FILTER_GEN). @internal\n\n```ts\nexport const ROW_FILTER_POS = Symbol('svgrid.row.filterPos')\n```\n\n### `function denseRows`\n\nThe rows as a plain dense array. For a lazyRows() list, makes the rows not\nmade yet and returns its backing array - the same row objects, without the\nProxy in front. Anything that reads every row (a sort, a filter) should go\nthrough this first: a trap per read, over several passes of a million rows,\ncost more than building the rows did.\n\n```ts\nexport function denseRows<T>(rows: T[]): T[]\n```\n\n### `type WindowedRowModel`\n\nThe row model for windowed data (windowed-data.ts), or null when `data` is\nan ordinary array. It lives in windowed-row-model.ts and is installed by the\nfirst createWindowedData() call, so a grid that is never handed windowed\ndata does not bundle it: this file imports nothing from either module.\n\n```ts\nexport type WindowedRowModel<TData extends RowData> = (data: unknown, columns: Array<Column<TData>>) => RowModel<TData> | null\n```\n\n### `type WindowedRowModelInstall`\n\nHow windowed-row-model.ts builds its row model from the base row helpers. @internal\n\n```ts\nexport type WindowedRowModelInstall =<TData extends RowData>(ctx: {\n rowCtxFor: (columns: Array<Column<TData>>) => BaseRowCtx<TData>\n getRowId: () => ((row: TData, index: number) => string) | undefined\n}) => WindowedRowModel<TData>\n```\n\n### `function registerWindowedRowModel`\n\nInternal: windowed-row-model.ts installs itself here.\n\n```ts\nexport function registerWindowedRowModel(install: WindowedRowModelInstall): void\n```\n\n### `type BaseRowState`\n\nA base row's private fields, on top of the public {@link Row} surface.\n\n```ts\nexport type BaseRowState<TData extends RowData> = Row<TData> & {\n [ROW_CTX]: BaseRowCtx<TData>\n [ROW_VALUES]: Array<unknown> | null\n [ROW_CELLS]: Array<Cell<TData>> | null\n [ROW_FILTER_GEN]: number\n [ROW_FILTER_POS]: number\n [ROW_SORT_DROPPED]: number\n [ROW_SORT_KEY]: unknown\n}\n```\n\n### `const BASE_ROW_METHODS`\n\nThe methods every base row carries, defined ONCE and assigned by reference.\n\nRows used to be built as object literals whose methods were closures, which\nmeant a 100k-row grid allocated 700k closures and a closure scope per row\nbefore painting anything. Measured at 100k x 9: 13.8 ms and 56.5 MB to build,\nagainst 2.0 ms and 14.5 MB for this shape - the single largest cost in\nmounting a large grid.\n\nThey read their row through `this` rather than a captured variable, which is\nwhy they can be shared. Note they are assigned as OWN properties rather than\nput on a prototype: `Row` is public, several row models legitimately do\n`{ ...row, depth }`, and a spread copies own properties but not a prototype.\nA class here would silently strip every method off a cloned row.\n\n```ts\nexport const BASE_ROW_METHODS = {\n getCanExpand(this: BaseRowState<RowData>) {\n return false\n },\n getIsExpanded(this: BaseRowState<RowData>) {\n return Boolean((this[ROW_CTX].store.state.expanded ?? {})[this.id])\n },\n toggleExpanded(this: BaseRowState<RowData>) {\n const id = this.id\n this[ROW_CTX].grid.setExpanded((prev) => ({ ...prev, [id]: !prev[id] }))\n },\n getIsSelected(this: BaseRowState<RowData>) {\n return Boolean((this[ROW_CTX].store.state.rowSelection ?? {})[this.id])\n },\n toggleSelected(this: BaseRowState<RowData>) {\n const id = this.id\n this[ROW_CTX].grid.setRowSelection((prev) => ({ ...prev, [id]: !prev[id] }))\n },\n getAllCells(this: BaseRowState<RowData>) {\n return this[ROW_CELLS] ?? buildBaseRowCells(this)\n },\n getCellValueByColumnId(this: BaseRowState<RowData>, columnId: string) {\n const idx = this[ROW_CTX].columnIndexById.get(columnId)\n if (idx === undefined) return undefined\n if (!this[ROW_VALUES]) this[ROW_VALUES] = baseRowValues(this)\n return this[ROW_VALUES][idx]\n },\n}\n```\n\n### `type RowModelFactory`\n\nOne stage of the row pipeline: takes the rows produced so far and returns the\nnext set. Stages compose in the order given to `_rowModels`, so filtering\nbefore sorting sorts only what survived the filter.\n\n```ts\nexport type RowModelFactory<TData extends RowData> = (args: {\n table: SvGrid<TData>\n rows: Array<Row<TData>>\n}) => Array<Row<TData>>\n```\n\n### `function createCoreRowModel`\n\nThe identity stage that starts every pipeline. Always required, even when no\nother stage is: it is what turns your data into rows.\n\n```ts\nexport function createCoreRowModel<TData extends RowData>(): RowModelFactory<TData>\n```\n\n### `function createFilteredRowModel`\n\nDrops rows that fail the active {@link ColumnFiltersState}. Pairs with\n`columnFilteringFeature`; without it there are no filters to apply.\n\n```ts\nexport function createFilteredRowModel<TData extends RowData>(): RowModelFactory<TData>\n```\n\n### `function createPaginatedRowModel`\n\nNarrows the rows to the current page. Put it LAST: anything after it would\nonly ever see one page of data.\n\n```ts\nexport function createPaginatedRowModel<TData extends RowData>(): RowModelFactory<TData>\n```\n\n### `function createGroupedRowModel`\n\nBuckets rows by the active {@link GroupingState} and inserts a group row\nahead of each bucket, carrying that bucket's aggregates.\n\n```ts\nexport function createGroupedRowModel<TData extends RowData>(): RowModelFactory<TData>\n```\n\n### `type TreeRowModelOptions`\n\nHow to read a hierarchy out of FLAT rows: each row names its parent, and the\ngrid reconstructs the tree. Rows whose parent id matches nothing become roots\nrather than disappearing.\n\nFor nested source data (`children: [...]`), flatten it first with\n{@link flattenTreeData}.\n\n```ts\nexport type TreeRowModelOptions = {\n /** Field holding each row's parent id. Rows with no parent are roots. */\n parentField: string\n /** Field holding the row's own id. Defaults to `'id'`. */\n idField?: string\n}\n```\n\n### `function createTreeRowModel`\n\nClient-side tree data: nest the grid's own flat rows into a parent/child\nhierarchy that `createExpandedRowModel` then walks.\n\nThis works on the rows the grid already built rather than on raw data, so\ntree rows keep their cells, editing, selection and formatting - they are real\ndata rows that happen to have children, not synthetic banners like grouping's.\nThat is also why the model is parent-id based: nested source arrays never\nbecome rows (the grid only builds rows for `data`), so nested input is\nflattened first with {@link flattenTreeData}. One code path, no duplicated\nrow construction.\n\nRows are tagged `__treeRow` so `isGroupRow` does not mistake an expandable\ndata row for a full-width group banner.\n\n```ts\nexport function createTreeRowModel<TData extends RowData>(\n options: TreeRowModelOptions,\n): RowModelFactory<TData>\n```\n\n### `type FlattenTreeOptions`\n\nHow to flatten NESTED source data into the parent-id shape tree rows need.\n`parentField` is written onto each row, so point `treeData.parentField` at\nthe same name afterwards.\n\n```ts\nexport type FlattenTreeOptions = {\n /** Field holding an array of child objects. */\n childrenField: string\n /** Field holding each object's id. Defaults to `'id'`. */\n idField?: string\n /** Field to WRITE the resolved parent id onto. Defaults to `'__parentId'`. */\n parentField?: string\n}\n```\n\n### `function flattenTreeData`\n\nFlatten nested tree data into the flat parent-id shape `createTreeRowModel`\nconsumes, stamping each child with its parent's id.\n\nChildren are emitted directly after their parent so the natural order already\nmatches the rendered tree. The `childrenField` array is left on the objects\n(harmless, and callers often still want it); only the parent link is added.\n\n```ts\nexport function flattenTreeData<T extends RowData>(\n data: ReadonlyArray<T>,\n options: FlattenTreeOptions,\n): T[]\n```\n\n### `function createExpandedRowModel`\n\nHides the descendants of collapsed rows. Needed for grouping, tree data and\nmaster-detail alike - all three are the same expand/collapse mechanism.\n\n```ts\nexport function createExpandedRowModel<TData extends RowData>(): RowModelFactory<TData>\n```\n\n### `function replacedRowsOf`\n\nThe rows `getRowModel` replaced in the rebuild this pipeline run follows, or null.\n\n```ts\nexport function replacedRowsOf(table: SvGrid<any>): ReadonlyMap<Row<any>, Row<any>> | null\n```\n\n### `function createSortedRowModel`\n\nThe sorting stage of the row pipeline: orders the rows by the grid's\n`sorting` state with the built-in comparators (or the `localSortFns` map\nhanded in), stable, equal keys keeping their data order. A tick that\nreplaces a few rows out of many is repaired incrementally rather than\nre-sorted (see the note inside). Registered by `rowSortingFeature`; an app\nonly calls this to install its own comparator set.\n\n```ts\nexport function createSortedRowModel<TData extends RowData>(\n localSortFns: typeof sortFns = sortFns,\n): RowModelFactory<TData>\n```\n\n### `type SvGridOptions`\n\nEverything {@link createSvGridCore} accepts: the data and columns, the\nfeatures and row models that make up the pipeline, and an `on*Change`\ncallback per piece of state for controlled use.\n\n`<SvGrid>` builds this for you from its props - you only construct it\ndirectly when driving the headless core.\n\n```ts\nexport type SvGridOptions<TFeatures extends TableFeatures, TData extends RowData> = {\n _features: TFeatures\n _rowModels?: {\n coreRowModel?: RowModelFactory<TData>\n filteredRowModel?: RowModelFactory<TData>\n sortedRowModel?: RowModelFactory<TData>\n paginatedRowModel?: RowModelFactory<TData>\n groupedRowModel?: RowModelFactory<TData>\n expandedRowModel?: RowModelFactory<TData>\n }\n columns: Array<ColumnDef<TFeatures, TData>>\n data: ReadonlyArray<TData>\n /**\n * Optional row-id resolver. When set, the value it returns becomes\n * `row.id` (and therefore the selection / expansion / edit key). When\n * omitted, ids fall back to the row's array index as a string. Use a\n * stable id (database PK, UUID, etc.) so selection survives reorders.\n */\n getRowId?: (row: TData, index: number) => string\n state?: Partial<Record<string, any>>\n onSortingChange?: (updater: Updater<SortingState>) => void\n onColumnFiltersChange?: (updater: Updater<ColumnFiltersState>) => void\n onPaginationChange?: (updater: Updater<PaginationState>) => void\n onGroupingChange?: (updater: Updater<GroupingState>) => void\n onExpandedChange?: (updater: Updater<ExpandedState>) => void\n onRowSelectionChange?: (updater: Updater<RowSelectionState>) => void\n onActiveCellChange?: (updater: Updater<ActiveCellState>) => void\n}\n```\n\n### `type SvGrid`\n\nThe headless grid instance: the state stores plus the read methods a renderer\nneeds (`getHeaderGroups()`, `getRowModel()`, the `set*` writers).\n\nFramework free by design - `<SvGrid>` is one renderer over this, and you can\nwrite another. See the \"Why headless?\" guide.\n\n```ts\nexport type SvGrid<TData extends RowData> = {\n store: Store<Record<string, any>>\n optionsStore: Store<Record<string, any>>\n state: Record<string, any>\n getState: () => Record<string, any>\n setOptions: (updater: Updater<Record<string, any>>) => void\n setColumnFilters: (updater: Updater<ColumnFiltersState>) => void\n setPagination: (updater: Updater<PaginationState>) => void\n setGrouping: (updater: Updater<GroupingState>) => void\n setExpanded: (updater: Updater<ExpandedState>) => void\n setRowSelection: (updater: Updater<RowSelectionState>) => void\n setActiveCell: (updater: Updater<ActiveCellState>) => void\n moveActiveCell: (next: { rowDelta?: number; colDelta?: number }) => void\n getAllColumns: () => Array<Column<TData>>\n getHeaderGroups: () => Array<HeaderGroup<TData>>\n getFooterGroups: () => Array<HeaderGroup<TData>>\n getRowModel: () => RowModel<TData>\n}\n```\n\n### `function createSvGridCore`\n\nBuild a headless grid: state, the row pipeline, and the read methods, with no\nDOM and no Svelte. This is the engine `<SvGrid>` renders.\n\nMost callers want `createSvGrid` (the runes-aware wrapper) or the component\nitself; reach for this when you are writing your own renderer or running the\npipeline outside a browser.\n\n```ts\nexport function createSvGridCore<TFeatures extends TableFeatures, TData extends RowData>(\n options: SvGridOptions<TFeatures, TData>,\n): SvGrid<TData>\n```\n\n### `function isFunction`\n\nNarrowing helper for the many options that accept a value or a function.\n\n```ts\nexport function isFunction(value: unknown): value is (...args: Array<any>) => any\n```\n"
7947
8018
  },
7948
8019
  {
7949
8020
  "slug": "reference/auto/svgrid-grid-createTree.svelte",
7950
8021
  "path": "docs/reference/auto/svgrid-grid-createTree.svelte.md",
7951
8022
  "title": "@svgrid/grid · createTree.svelte.ts",
7952
8023
  "section": "API reference",
7953
- "markdown": "# `@svgrid/grid` · `createTree.svelte.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\createTree.svelte.ts`.\n\n### `type TreeNode`\n\ncreateTree - the HEADLESS core behind <SvTree>, in the same spirit as\n`createSvGrid` for the grid: a runes-based state machine (expand/collapse,\nsingle-select highlight, cascading tri-state checkboxes, full keyboard) with\n**prop-getters** you spread onto YOUR OWN markup. The visible tree is\nflattened into `rows` so roving-focus keyboard nav stays a flat index walk.\n\n```svelte\n<script lang=\"ts\">\n import { createTree } from '@svgrid/grid'\n let selected = $state<string | null>(null)\n const tree = createTree({ nodes: () => nodes, selected: () => selected, onSelect: (id) => (selected = id) })\n</script>\n<div {...tree.treeProps()}>\n {#each tree.rows as row (row.node.id)}\n <div {...tree.itemProps(row)}>{row.node.label}</div>\n {/each}\n</div>\n```\n\nThe styled <SvTree> is just one renderer over this core. The cascade math\n(`treeDescendantIds`, `treeCheckState`) is exported as pure functions.\n\n```ts\nexport type TreeNode = {\n id: string\n label: string\n children?: TreeNode[]\n disabled?: boolean\n /** Marks a node whose children are loaded on demand (shows an expand arrow\n * even with no children yet; the renderer loads them on first expand). */\n lazy?: boolean\n}\n```\n\n### `type CheckState`\n\nA node's checkbox state. `'indeterminate'` means some but not all descendants are checked.\n\n```ts\nexport type CheckState = 'checked' | 'indeterminate' | 'unchecked'\n```\n\n### `type TreeRow`\n\nA single visible (flattened) tree row.\n\n```ts\nexport type TreeRow = {\n node: TreeNode\n depth: number\n hasChildren: boolean\n open: boolean\n parentId: string | null\n index: number\n}\n```\n\n### `function treeDescendantIds`\n\nAll descendant ids of `node` (pure, depth-first).\n\n```ts\nexport function treeDescendantIds(node: TreeNode): string[] {\n const ids: string[] = []\n const walk = (n: TreeNode) => { for (const c of n.children ?? []) { ids.push(c.id); walk(c) } }\n walk(node)\n return ids\n}\n```\n\n### `function treeCheckState`\n\nTri-state check status of `node` given the set of checked ids (pure).\n\n```ts\nexport function treeCheckState(node: TreeNode, checked: ReadonlySet<string>): CheckState {\n if (!node.children?.length) return checked.has(node.id) ? 'checked' : 'unchecked'\n const desc = treeDescendantIds(node)\n const on = desc.filter((id) => checked.has(id)).length\n if (on === 0 && !checked.has(node.id)) return 'unchecked'\n if (on === desc.length) return 'checked'\n return 'indeterminate'\n}\n```\n\n### `type TreeDropPosition`\n\nWhere a dragged node lands relative to the drop target.\n\n```ts\nexport type TreeDropPosition = 'before' | 'after' | 'inside'\n```\n\n### `function treeContains`\n\nTrue if `id` is inside `node`'s subtree (used to block invalid drops).\n\n```ts\nexport function treeContains(node: TreeNode, id: string): boolean {\n return node.children?.some((c) => c.id === id || treeContains(c, id)) ?? false\n}\n```\n\n### `function moveTreeNode`\n\nReturn a NEW node tree with `dragId` moved before/after/inside `targetId`\n(pure - the caller sets it back as the controlled `nodes`). No-ops on invalid\nmoves (self, or into own descendant).\n\n```ts\nexport function moveTreeNode(\n nodes: ReadonlyArray<TreeNode>,\n dragId: string,\n targetId: string,\n position: TreeDropPosition,\n): TreeNode[] {\n if (dragId === targetId) return [...nodes]\n const dragged = findNode(nodes, dragId)\n if (!dragged) return [...nodes]\n if (dragId === targetId || treeContains(dragged, targetId)) return [...nodes]\n\n const without = (list: ReadonlyArray<TreeNode>): TreeNode[] => {\n const out: TreeNode[] = []\n for (const n of list) {\n if (n.id === dragId) continue\n out.push(n.children ? { ...n, children: without(n.children) } : n)\n }\n return out\n }\n const insert = (list: ReadonlyArray<TreeNode>): TreeNode[] => {\n const out: TreeNode[] = []\n for (const n of list) {\n if (n.id === targetId) {\n if (position === 'before') { out.push(dragged, n) }\n else if (position === 'after') { out.push(n, dragged) }\n else out.push({ ...n, children: [...(n.children ?? []), dragged] })\n } else if (n.children) {\n out.push({ ...n, children: insert(n.children) })\n } else out.push(n)\n }\n return out\n }\n return insert(without(nodes))\n}\n```\n\n### `function sortTreeNodes`\n\nSort siblings (recursively) by a comparator (pure).\n\n```ts\nexport function sortTreeNodes(\n nodes: ReadonlyArray<TreeNode>,\n compare: (a: TreeNode, b: TreeNode) => number,\n): TreeNode[] {\n return [...nodes]\n .sort(compare)\n .map((n) => (n.children ? { ...n, children: sortTreeNodes(n.children, compare) } : n))\n}\n```\n\n### `type TreeConfig`\n\nReactive inputs are passed as getters so the core tracks live prop changes.\n\n```ts\nexport type TreeConfig = {\n nodes: () => ReadonlyArray<TreeNode>\n selected?: () => string | null\n onSelect?: (id: string) => void\n /** Seed the internally-managed expanded set (read once). */\n expandedIds?: () => string[] | undefined\n onToggle?: (id: string, expanded: boolean) => void\n checkable?: () => boolean\n checked?: () => string[]\n onCheck?: (ids: string[]) => void\n ariaLabel?: () => string | undefined\n /** Text direction; under `'rtl'` the Left/Right expand/collapse keys swap. */\n dir?: () => import('./editor-contract').EditorDir | undefined\n /** Filter query: show only matching nodes + their ancestors, auto-expanded. */\n filter?: () => string | undefined\n}\n```\n\n### `function createTree`\n\nBuild the headless tree model: expansion, selection and checkbox cascading, with no markup.\n\n```ts\nexport function createTree(config: TreeConfig) {\n const nodes = () => config.nodes()\n const checkable = () => config.checkable?.() ?? false\n const selected = () => config.selected?.() ?? null\n\n // Internal expanded set, seeded from the prop once (then self-managed).\n let expanded = $state<Set<string>>(new Set())\n let seeded = false\n $effect(() => {\n if (!seeded) { seeded = true; const ids = config.expandedIds?.(); if (ids) expanded = new Set(ids) }\n })\n\n // When filtering, precompute which nodes to show (a match, or an ancestor of a\n // match) and which to force-open so matches are revealed.\n const filterInfo = $derived.by(() => {\n const q = config.filter?.()?.trim().toLowerCase()\n if (!q) return null\n const visible = new Set<string>()\n const forceOpen = new Set<string>()\n const walk = (node: TreeNode): boolean => {\n let childMatch = false\n for (const c of node.children ?? []) childMatch = walk(c) || childMatch\n const selfMatch = node.label.toLowerCase().includes(q)\n if (selfMatch || childMatch) { visible.add(node.id); if (childMatch) forceOpen.add(node.id) }\n return selfMatch || childMatch\n }\n for (const n of nodes()) walk(n)\n return { visible, forceOpen }\n })\n\n const rows = $derived.by<TreeRow[]>(() => {\n const out: TreeRow[] = []\n const fi = filterInfo\n const walk = (list: ReadonlyArray<TreeNode>, depth: number, parentId: string | null) => {\n for (const node of list) {\n if (fi && !fi.visible.has(node.id)) continue\n const hasChildren = !!node.children?.length || !!node.lazy\n const open = fi ? fi.forceOpen.has(node.id) || expanded.has(node.id) : expanded.has(node.id)\n out.push({ node, depth, hasChildren, open, parentId, index: out.length })\n if (open && node.children?.length) walk(node.children, depth + 1, node.id)\n }\n }\n walk(nodes(), 0, null)\n return out\n })\n\n let active = $state(0)\n $effect(() => { if (active >= rows.length) active = Math.max(0, rows.length - 1) })\n\n const checkedSet = $derived(new Set(config.checked?.() ?? []))\n\n // Roving focus target; `focusTick` bumps only on keyboard moves.\n let focusTick = $state(0)\n function setActive(i: number, focus = false) { active = i; if (focus) focusTick++ }\n\n const checkStateOf = (node: TreeNode): CheckState => treeCheckState(node, checkedSet)\n const isExpanded = (id: string) => expanded.has(id)\n const isSelected = (id: string) => id === selected()\n\n function toggleExpand(node: TreeNode) {\n // Lazy nodes have no children *yet* - they must still be expandable so the\n // toggle fires onToggle and the host can fetch children on demand.\n if (!node.children?.length && !node.lazy) return\n const next = new Set(expanded)\n const willOpen = !next.has(node.id)\n willOpen ? next.add(node.id) : next.delete(node.id)\n expanded = next\n config.onToggle?.(node.id, willOpen)\n }\n const toggle = (id: string) => { const n = findNode(nodes(), id); if (n) toggleExpand(n) }\n\n function select(node: TreeNode) {\n if (node.disabled) return\n config.onSelect?.(node.id)\n }\n const selectId = (id: string) => { const n = findNode(nodes(), id); if (n) select(n) }\n\n function toggleCheck(node: TreeNode) {\n if (node.disabled) return\n const next = new Set(checkedSet)\n const ids = [node.id, ...treeDescendantIds(node)]\n const currentlyOn = checkStateOf(node) === 'checked'\n for (const id of ids) currentlyOn ? next.delete(id) : next.add(id)\n config.onCheck?.([...next])\n }\n\n // Step from `from` towards `dir` (+1/-1), skipping disabled rows, so roving\n // focus never lands on a node with zero semantic affordance for AT users.\n // Falls back to `from` if every row in that direction is disabled.\n function stepEnabled(from: number, dir: 1 | -1): number {\n let i = from\n while (i + dir >= 0 && i + dir <= rows.length - 1) {\n i += dir\n if (!rows[i]?.node.disabled) return i\n }\n return from\n }\n\n function onKeydown(e: KeyboardEvent) {\n const item = rows[active]\n if (!item) return\n // \"expand\" opens the node or steps into the first child; \"collapse\" closes it\n // or jumps to the parent. Under RTL the physical Left/Right keys are swapped.\n const expand = () => {\n if (item.hasChildren && !item.open) toggleExpand(item.node)\n else if (item.hasChildren && item.open) setActive(Math.min(active + 1, rows.length - 1), true)\n }\n const collapse = () => {\n if (item.hasChildren && item.open) toggleExpand(item.node)\n else if (item.parentId) { const pi = rows.findIndex((r) => r.node.id === item.parentId); if (pi >= 0) setActive(pi, true) }\n }\n const rtl = config.dir?.() === 'rtl'\n switch (e.key) {\n case 'ArrowDown': e.preventDefault(); setActive(stepEnabled(active, 1), true); break\n case 'ArrowUp': e.preventDefault(); setActive(stepEnabled(active, -1), true); break\n case 'ArrowRight': e.preventDefault(); (rtl ? collapse : expand)(); break\n case 'ArrowLeft': e.preventDefault(); (rtl ? expand : collapse)(); break\n case 'Enter': e.preventDefault(); select(item.node); break\n case ' ': e.preventDefault(); checkable() ? toggleCheck(item.node) : select(item.node); break\n case 'Home': e.preventDefault(); setActive(0, true); break\n case 'End': e.preventDefault(); setActive(rows.length - 1, true); break\n }\n }\n\n return {\n /** Internally-managed set of expanded node ids. */\n get expanded() { return expanded },\n /** Selected node id (single-select highlight). */\n get selected() { return selected() },\n /** Flattened list of visible rows. */\n get rows() { return rows },\n /** Roving-focus row index. */\n get activeIndex() { return active },\n /** Monotonic counter; changes only on keyboard navigation. */\n get focusTick() { return focusTick },\n isExpanded,\n isSelected,\n checkStateOf,\n toggle,\n toggleExpand,\n select: selectId,\n toggleCheck,\n setActive,\n onKeydown,\n /** Spread onto the tree container element. */\n treeProps: () => ({\n role: 'tree' as const,\n 'aria-label': config.ariaLabel?.(),\n 'aria-multiselectable': checkable(),\n }),\n /** Spread onto the treeitem element for a flattened `row`. */\n itemProps: (row: TreeRow) => {\n const cs = checkable() ? checkStateOf(row.node) : 'unchecked'\n const ariaChecked: 'true' | 'mixed' | 'false' | undefined =\n checkable() ? (cs === 'checked' ? 'true' : cs === 'indeterminate' ? 'mixed' : 'false') : undefined\n return {\n role: 'treeitem' as const,\n 'aria-level': row.depth + 1,\n 'aria-selected': row.node.id === selected(),\n 'aria-expanded': row.hasChildren ? row.open : undefined,\n 'aria-checked': ariaChecked,\n 'aria-disabled': row.node.disabled || undefined,\n 'data-row': row.index,\n tabindex: row.index === active ? 0 : -1,\n onclick: () => { setActive(row.index); select(row.node) },\n onkeydown: onKeydown,\n }\n },\n }\n}\n```\n\n### `type Tree`\n\nThe headless tree instance returned by {@link createTree}.\n\n```ts\nexport type Tree = ReturnType<typeof createTree>\n```\n"
8024
+ "markdown": "# `@svgrid/grid` · `createTree.svelte.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\createTree.svelte.ts`.\n\n### `type TreeNode`\n\ncreateTree - the HEADLESS core behind <SvTree>, in the same spirit as\n`createSvGrid` for the grid: a runes-based state machine (expand/collapse,\nsingle-select highlight, cascading tri-state checkboxes, full keyboard) with\n**prop-getters** you spread onto YOUR OWN markup. The visible tree is\nflattened into `rows` so roving-focus keyboard nav stays a flat index walk.\n\n```svelte\n<script lang=\"ts\">\n import { createTree } from '@svgrid/grid'\n let selected = $state<string | null>(null)\n const tree = createTree({ nodes: () => nodes, selected: () => selected, onSelect: (id) => (selected = id) })\n</script>\n<div {...tree.treeProps()}>\n {#each tree.rows as row (row.node.id)}\n <div {...tree.itemProps(row)}>{row.node.label}</div>\n {/each}\n</div>\n```\n\nThe styled <SvTree> is just one renderer over this core. The cascade math\n(`treeDescendantIds`, `treeCheckState`) is exported as pure functions.\n\n```ts\nexport type TreeNode = {\n id: string\n label: string\n children?: TreeNode[]\n disabled?: boolean\n /** Marks a node whose children are loaded on demand (shows an expand arrow\n * even with no children yet; the renderer loads them on first expand). */\n lazy?: boolean\n}\n```\n\n### `type CheckState`\n\nA node's checkbox state. `'indeterminate'` means some but not all descendants are checked.\n\n```ts\nexport type CheckState = 'checked' | 'indeterminate' | 'unchecked'\n```\n\n### `type TreeRow`\n\nA single visible (flattened) tree row.\n\n```ts\nexport type TreeRow = {\n node: TreeNode\n depth: number\n hasChildren: boolean\n open: boolean\n parentId: string | null\n index: number\n}\n```\n\n### `function treeDescendantIds`\n\nAll descendant ids of `node` (pure, depth-first).\n\n```ts\nexport function treeDescendantIds(node: TreeNode): string[]\n```\n\n### `function treeCheckState`\n\nTri-state check status of `node` given the set of checked ids (pure).\n\n```ts\nexport function treeCheckState(node: TreeNode, checked: ReadonlySet<string>): CheckState\n```\n\n### `type TreeDropPosition`\n\nWhere a dragged node lands relative to the drop target.\n\n```ts\nexport type TreeDropPosition = 'before' | 'after' | 'inside'\n```\n\n### `function treeContains`\n\nTrue if `id` is inside `node`'s subtree (used to block invalid drops).\n\n```ts\nexport function treeContains(node: TreeNode, id: string): boolean\n```\n\n### `function moveTreeNode`\n\nReturn a NEW node tree with `dragId` moved before/after/inside `targetId`\n(pure - the caller sets it back as the controlled `nodes`). No-ops on invalid\nmoves (self, or into own descendant).\n\n```ts\nexport function moveTreeNode(\n nodes: ReadonlyArray<TreeNode>,\n dragId: string,\n targetId: string,\n position: TreeDropPosition,\n): TreeNode[]\n```\n\n### `function sortTreeNodes`\n\nSort siblings (recursively) by a comparator (pure).\n\n```ts\nexport function sortTreeNodes(\n nodes: ReadonlyArray<TreeNode>,\n compare: (a: TreeNode, b: TreeNode) => number,\n): TreeNode[]\n```\n\n### `type TreeConfig`\n\nReactive inputs are passed as getters so the core tracks live prop changes.\n\n```ts\nexport type TreeConfig = {\n nodes: () => ReadonlyArray<TreeNode>\n selected?: () => string | null\n onSelect?: (id: string) => void\n /** Seed the internally-managed expanded set (read once). */\n expandedIds?: () => string[] | undefined\n onToggle?: (id: string, expanded: boolean) => void\n checkable?: () => boolean\n checked?: () => string[]\n onCheck?: (ids: string[]) => void\n ariaLabel?: () => string | undefined\n /** Text direction; under `'rtl'` the Left/Right expand/collapse keys swap. */\n dir?: () => import('./editor-contract').EditorDir | undefined\n /** Filter query: show only matching nodes + their ancestors, auto-expanded. */\n filter?: () => string | undefined\n}\n```\n\n### `function createTree`\n\nBuild the headless tree model: expansion, selection and checkbox cascading, with no markup.\n\n```ts\nexport function createTree(config: TreeConfig)\n```\n\n### `type Tree`\n\nThe headless tree instance returned by {@link createTree}.\n\n```ts\nexport type Tree = ReturnType<typeof createTree>\n```\n"
7954
8025
  },
7955
8026
  {
7956
8027
  "slug": "reference/auto/svgrid-grid-date-core",
7957
8028
  "path": "docs/reference/auto/svgrid-grid-date-core.md",
7958
8029
  "title": "@svgrid/grid · datetime/date-core.ts",
7959
8030
  "section": "API reference",
7960
- "markdown": "# `@svgrid/grid` · `datetime/date-core.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\date-core.ts`.\n\n### `type DateLike`\n\nAnything the date helpers accept: a `Date`, epoch milliseconds, or a parseable string.\n\n```ts\nexport type DateLike = Date | number | string\n```\n\n### `function toDate`\n\nCoerce a Date | epoch-ms | parseable string to a Date, or null if invalid.\n\n```ts\nexport function toDate(value: DateLike | null | undefined): Date | null {\n if (value == null) return null\n const d = value instanceof Date ? new Date(value.getTime()) : new Date(value)\n return isNaN(d.getTime()) ? null : d\n}\n```\n\n### `function startOfDay`\n\nA new Date at local midnight of the same calendar day (time stripped).\n\n```ts\nexport function startOfDay(d: Date): Date {\n return new Date(d.getFullYear(), d.getMonth(), d.getDate())\n}\n```\n\n### `function startOfMonth`\n\nFirst day (midnight) of the month `d` falls in.\n\n```ts\nexport function startOfMonth(d: Date): Date {\n return new Date(d.getFullYear(), d.getMonth(), 1)\n}\n```\n\n### `function endOfMonth`\n\nLast day (midnight) of the month `d` falls in.\n\n```ts\nexport function endOfMonth(d: Date): Date {\n return new Date(d.getFullYear(), d.getMonth() + 1, 0)\n}\n```\n\n### `function daysInMonth`\n\nNumber of days in the month `d` falls in.\n\n```ts\nexport function daysInMonth(d: Date): number {\n return endOfMonth(d).getDate()\n}\n```\n\n### `function startOfWeek`\n\nStart of the week containing `d`, honoring `firstDayOfWeek` (0-6). Returns a\nlocal-midnight Date on or before `d`.\n\n```ts\nexport function startOfWeek(d: Date, firstDayOfWeek = 0): Date {\n const start = startOfDay(d)\n const diff = (start.getDay() - firstDayOfWeek + 7) % 7\n start.setDate(start.getDate() - diff)\n return start\n}\n```\n\n### `function isSameDay`\n\nTrue when both dates are the same local calendar day.\n\n```ts\nexport function isSameDay(a: Date | null, b: Date | null): boolean {\n if (!a || !b) return false\n return (\n a.getFullYear() === b.getFullYear() &&\n a.getMonth() === b.getMonth() &&\n a.getDate() === b.getDate()\n )\n}\n```\n\n### `function isSameMonth`\n\nTrue when both dates are in the same year+month.\n\n```ts\nexport function isSameMonth(a: Date | null, b: Date | null): boolean {\n if (!a || !b) return false\n return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth()\n}\n```\n\n### `function compareDay`\n\n-1 / 0 / 1 comparison by calendar day (time-of-day ignored).\n\n```ts\nexport function compareDay(a: Date, b: Date): number {\n const av = startOfDay(a).getTime()\n const bv = startOfDay(b).getTime()\n return av < bv ? -1 : av > bv ? 1 : 0\n}\n```\n\n### `function addDays`\n\nAdd `n` days (can be negative), returning a new Date.\n\n```ts\nexport function addDays(d: Date, n: number): Date {\n const r = new Date(d.getTime())\n r.setDate(r.getDate() + n)\n return r\n}\n```\n\n### `function addMonths`\n\nAdd `n` calendar months, clamping the day-of-month so 31 Jan + 1 month = 28/29\nFeb rather than spilling into March (matches how calendars paginate).\n\n```ts\nexport function addMonths(d: Date, n: number): Date {\n const day = d.getDate()\n const r = new Date(d.getFullYear(), d.getMonth() + n, 1, d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds())\n r.setDate(Math.min(day, daysInMonth(r)))\n return r\n}\n```\n\n### `function addYears`\n\nAdd `n` years, clamping Feb-29 to Feb-28 on non-leap targets.\n\n```ts\nexport function addYears(d: Date, n: number): Date {\n return addMonths(d, n * 12)\n}\n```\n\n### `function clampDate`\n\nClamp `d` to the inclusive [min, max] range (either bound may be null).\n\n```ts\nexport function clampDate(d: Date, min: Date | null, max: Date | null): Date {\n if (min && d.getTime() < min.getTime()) return new Date(min.getTime())\n if (max && d.getTime() > max.getTime()) return new Date(max.getTime())\n return d\n}\n```\n\n### `function isoWeek`\n\nISO 8601 week number (1-53) for `d`. Week 1 is the week containing the first\nThursday of the year; weeks start Monday. Independent of `firstDayOfWeek`,\nmatching Smart's `weekNumbers` column which is always ISO.\n\n```ts\nexport function isoWeek(d: Date): number {\n // Shift to the Thursday of this week, then count weeks from Jan 1.\n const date = startOfDay(d)\n const day = (date.getDay() + 6) % 7 // Mon=0..Sun=6\n date.setDate(date.getDate() - day + 3) // Thursday of this week\n const firstThursday = new Date(date.getFullYear(), 0, 4)\n const firstDay = (firstThursday.getDay() + 6) % 7\n firstThursday.setDate(firstThursday.getDate() - firstDay + 3)\n const diffMs = date.getTime() - firstThursday.getTime()\n return 1 + Math.round(diffMs / (7 * 24 * 3600 * 1000))\n}\n```\n\n### `function decadeRange`\n\nThe [start, end] years of the decade block that `year` belongs to, as Smart\nrenders it: a 12-cell page running from the decade start minus 1 to plus 10\n(one leading + one trailing year for context). We expose the canonical\ndecade [Y0, Y0+9] and let the view pad.\n\n```ts\nexport function decadeRange(year: number): { start: number; end: number } {\n const start = Math.floor(year / 10) * 10\n return { start, end: start + 9 }\n}\n```\n\n### `function centuryRange`\n\nThe [start, end] years of the century block (100-year) `year` belongs to.\n\n```ts\nexport function centuryRange(year: number): { start: number; end: number } {\n const start = Math.floor(year / 100) * 100\n return { start, end: start + 99 }\n}\n```\n\n### `type MonthMatrixCell`\n\nOne cell of a month grid, including the leading and trailing days from adjacent months.\n\n```ts\nexport type MonthMatrixCell = {\n date: Date\n /** In the displayed month (vs. leading/trailing days of adjacent months). */\n inMonth: boolean\n /** ISO week number of the row this cell sits in. */\n week: number\n}\n```\n\n### `function monthMatrix`\n\nBuild a month grid of `weeks` rows x 7 columns starting at `firstDayOfWeek`,\npadded with the trailing days of the previous month and leading days of the\nnext so every row is full. `weeks` defaults to 6 (the max any month needs),\nmatching Smart's fixed-height calendar.\n\n```ts\nexport function monthMatrix(\n monthDate: Date,\n firstDayOfWeek = 0,\n weeks = 6,\n): MonthMatrixCell[][] {\n const first = startOfMonth(monthDate)\n const gridStart = startOfWeek(first, firstDayOfWeek)\n const rows: MonthMatrixCell[][] = []\n let cursor = gridStart\n for (let r = 0; r < weeks; r++) {\n const row: MonthMatrixCell[] = []\n const weekNo = isoWeek(cursor)\n for (let c = 0; c < 7; c++) {\n row.push({\n date: cursor,\n inMonth: cursor.getMonth() === first.getMonth() && cursor.getFullYear() === first.getFullYear(),\n week: weekNo,\n })\n cursor = addDays(cursor, 1)\n }\n rows.push(row)\n }\n return rows\n}\n```\n\n### `function weekdayOrder`\n\nOrdered weekday indexes (0-6) for a header row starting at `firstDayOfWeek`.\ne.g. firstDayOfWeek=1 -> [1,2,3,4,5,6,0].\n\n```ts\nexport function weekdayOrder(firstDayOfWeek = 0): number[] {\n return Array.from({ length: 7 }, (_, i) => (firstDayOfWeek + i) % 7)\n}\n```\n\n### `function withTime`\n\nMerge a calendar day with a time-of-day taken from `time`, returning a new Date.\n\n```ts\nexport function withTime(day: Date, time: Date): Date {\n return new Date(\n day.getFullYear(),\n day.getMonth(),\n day.getDate(),\n time.getHours(),\n time.getMinutes(),\n time.getSeconds(),\n time.getMilliseconds(),\n )\n}\n```\n\n### `function snapMinute`\n\nSnap a minute value to the nearest lower multiple of `interval` (>=1).\n\n```ts\nexport function snapMinute(minute: number, interval: number): number {\n const step = Math.max(1, Math.floor(interval))\n return Math.floor(minute / step) * step\n}\n```\n"
8031
+ "markdown": "# `@svgrid/grid` · `datetime/date-core.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\date-core.ts`.\n\n### `type DateLike`\n\nAnything the date helpers accept: a `Date`, epoch milliseconds, or a parseable string.\n\n```ts\nexport type DateLike = Date | number | string\n```\n\n### `function toDate`\n\nCoerce a Date | epoch-ms | parseable string to a Date, or null if invalid.\n\n```ts\nexport function toDate(value: DateLike | null | undefined): Date | null\n```\n\n### `function startOfDay`\n\nA new Date at local midnight of the same calendar day (time stripped).\n\n```ts\nexport function startOfDay(d: Date): Date\n```\n\n### `function startOfMonth`\n\nFirst day (midnight) of the month `d` falls in.\n\n```ts\nexport function startOfMonth(d: Date): Date\n```\n\n### `function endOfMonth`\n\nLast day (midnight) of the month `d` falls in.\n\n```ts\nexport function endOfMonth(d: Date): Date\n```\n\n### `function daysInMonth`\n\nNumber of days in the month `d` falls in.\n\n```ts\nexport function daysInMonth(d: Date): number\n```\n\n### `function startOfWeek`\n\nStart of the week containing `d`, honoring `firstDayOfWeek` (0-6). Returns a\nlocal-midnight Date on or before `d`.\n\n```ts\nexport function startOfWeek(d: Date, firstDayOfWeek = 0): Date\n```\n\n### `function isSameDay`\n\nTrue when both dates are the same local calendar day.\n\n```ts\nexport function isSameDay(a: Date | null, b: Date | null): boolean\n```\n\n### `function isSameMonth`\n\nTrue when both dates are in the same year+month.\n\n```ts\nexport function isSameMonth(a: Date | null, b: Date | null): boolean\n```\n\n### `function compareDay`\n\n-1 / 0 / 1 comparison by calendar day (time-of-day ignored).\n\n```ts\nexport function compareDay(a: Date, b: Date): number\n```\n\n### `function addDays`\n\nAdd `n` days (can be negative), returning a new Date.\n\n```ts\nexport function addDays(d: Date, n: number): Date\n```\n\n### `function addMonths`\n\nAdd `n` calendar months, clamping the day-of-month so 31 Jan + 1 month = 28/29\nFeb rather than spilling into March (matches how calendars paginate).\n\n```ts\nexport function addMonths(d: Date, n: number): Date\n```\n\n### `function addYears`\n\nAdd `n` years, clamping Feb-29 to Feb-28 on non-leap targets.\n\n```ts\nexport function addYears(d: Date, n: number): Date\n```\n\n### `function clampDate`\n\nClamp `d` to the inclusive [min, max] range (either bound may be null).\n\n```ts\nexport function clampDate(d: Date, min: Date | null, max: Date | null): Date\n```\n\n### `function isoWeek`\n\nISO 8601 week number (1-53) for `d`. Week 1 is the week containing the first\nThursday of the year; weeks start Monday. Independent of `firstDayOfWeek`,\nmatching Smart's `weekNumbers` column which is always ISO.\n\n```ts\nexport function isoWeek(d: Date): number\n```\n\n### `function decadeRange`\n\nThe [start, end] years of the decade block that `year` belongs to, as Smart\nrenders it: a 12-cell page running from the decade start minus 1 to plus 10\n(one leading + one trailing year for context). We expose the canonical\ndecade [Y0, Y0+9] and let the view pad.\n\n```ts\nexport function decadeRange(year: number): { start: number; end: number }\n```\n\n### `function centuryRange`\n\nThe [start, end] years of the century block (100-year) `year` belongs to.\n\n```ts\nexport function centuryRange(year: number): { start: number; end: number }\n```\n\n### `type MonthMatrixCell`\n\nOne cell of a month grid, including the leading and trailing days from adjacent months.\n\n```ts\nexport type MonthMatrixCell = {\n date: Date\n /** In the displayed month (vs. leading/trailing days of adjacent months). */\n inMonth: boolean\n /** ISO week number of the row this cell sits in. */\n week: number\n}\n```\n\n### `function monthMatrix`\n\nBuild a month grid of `weeks` rows x 7 columns starting at `firstDayOfWeek`,\npadded with the trailing days of the previous month and leading days of the\nnext so every row is full. `weeks` defaults to 6 (the max any month needs),\nmatching Smart's fixed-height calendar.\n\n```ts\nexport function monthMatrix(\n monthDate: Date,\n firstDayOfWeek = 0,\n weeks = 6,\n): MonthMatrixCell[][]\n```\n\n### `function weekdayOrder`\n\nOrdered weekday indexes (0-6) for a header row starting at `firstDayOfWeek`.\ne.g. firstDayOfWeek=1 -> [1,2,3,4,5,6,0].\n\n```ts\nexport function weekdayOrder(firstDayOfWeek = 0): number[]\n```\n\n### `function withTime`\n\nMerge a calendar day with a time-of-day taken from `time`, returning a new Date.\n\n```ts\nexport function withTime(day: Date, time: Date): Date\n```\n\n### `function snapMinute`\n\nSnap a minute value to the nearest lower multiple of `interval` (>=1).\n\n```ts\nexport function snapMinute(minute: number, interval: number): number\n```\n"
7961
8032
  },
7962
8033
  {
7963
8034
  "slug": "reference/auto/svgrid-grid-date-format",
7964
8035
  "path": "docs/reference/auto/svgrid-grid-date-format.md",
7965
8036
  "title": "@svgrid/grid · datetime/date-format.ts",
7966
8037
  "section": "API reference",
7967
- "markdown": "# `@svgrid/grid` · `datetime/date-format.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\date-format.ts`.\n\n### `function tokenizeMask`\n\nSplit a mask into an ordered list of token / literal parts.\n\n```ts\nexport function tokenizeMask(mask: string): Part[] {\n const parts: Part[] = []\n let i = 0\n while (i < mask.length) {\n const ch = mask[i]!\n // Backslash escape: next char is a literal.\n if (ch === '\\\\' && i + 1 < mask.length) {\n parts.push({ literal: mask[i + 1]! })\n i += 2\n continue\n }\n // Single-quoted literal run.\n if (ch === \"'\") {\n let j = i + 1\n let lit = ''\n while (j < mask.length && mask[j] !== \"'\") {\n lit += mask[j]\n j++\n }\n parts.push({ literal: lit })\n i = j + 1 // skip closing quote (or run to end)\n continue\n }\n // Greedy longest-token match.\n let matched: string | null = null\n for (const t of TOKENS) {\n if (mask.startsWith(t, i)) {\n matched = t\n break\n }\n }\n if (matched) {\n parts.push({ token: matched })\n i += matched.length\n } else {\n parts.push({ literal: ch })\n i += 1\n }\n }\n return parts\n}\n```\n\n### `function formatDate`\n\nRender `date` per `mask` in `locale`.\n\n```ts\nexport function formatDate(date: Date, mask: string, locale = 'en-US'): string {\n const parts = tokenizeMask(mask)\n const h24 = date.getHours()\n const h12 = h24 % 12 === 0 ? 12 : h24 % 12\n const ms = date.getMilliseconds()\n let out = ''\n for (const p of parts) {\n if ('literal' in p) {\n out += p.literal\n continue\n }\n switch (p.token) {\n case 'd': out += String(date.getDate()); break\n case 'dd': out += pad(date.getDate(), 2); break\n case 'ddd': out += weekdayNames(locale).short[date.getDay()]; break\n case 'dddd': out += weekdayNames(locale).long[date.getDay()]; break\n case 'M': out += String(date.getMonth() + 1); break\n case 'MM': out += pad(date.getMonth() + 1, 2); break\n case 'MMM': out += monthNames(locale).short[date.getMonth()]; break\n case 'MMMM': out += monthNames(locale).long[date.getMonth()]; break\n case 'yy': out += pad(date.getFullYear() % 100, 2); break\n case 'yyyy': out += pad(date.getFullYear(), 4); break\n case 'H': out += String(h24); break\n case 'HH': out += pad(h24, 2); break\n case 'h': out += String(h12); break\n case 'hh': out += pad(h12, 2); break\n case 'm': out += String(date.getMinutes()); break\n case 'mm': out += pad(date.getMinutes(), 2); break\n case 's': out += String(date.getSeconds()); break\n case 'ss': out += pad(date.getSeconds(), 2); break\n case 'f': out += pad(ms, 3).slice(0, 1); break\n case 'ff': out += pad(ms, 3).slice(0, 2); break\n case 'fff': out += pad(ms, 3); break\n case 't': out += (h24 < 12 ? dayPeriods(locale).am : dayPeriods(locale).pm).slice(0, 1); break\n case 'tt': out += h24 < 12 ? dayPeriods(locale).am : dayPeriods(locale).pm; break\n default: out += p.token\n }\n }\n return out\n}\n```\n\n### `function parseDate`\n\nParse `str` against `mask` in `locale`. Returns a Date or null if the string\ndoes not satisfy the mask. `yearCutoff` disambiguates 2-digit years: values\n<= (yearCutoff % 100) map to 2000s, above to 1900s (Smart's default 1926 ->\na 26 pivot). `base` supplies fields the mask omits (defaults to epoch-zero\nlocal midnight so a time-only mask yields a today-agnostic time).\n\n```ts\nexport function parseDate(\n str: string,\n mask: string,\n locale = 'en-US',\n yearCutoff = 2029,\n base?: Date,\n): Date | null {\n const parts = tokenizeMask(mask)\n const acc: Acc = {}\n let i = 0\n const s = str\n for (const p of parts) {\n if ('literal' in p) {\n // Literals must match (whitespace-insensitive at the boundary).\n for (const ch of p.literal) {\n if (ch === ' ') {\n while (s[i] === ' ') i++\n continue\n }\n if (s[i] !== ch) return null\n i++\n }\n continue\n }\n const tok = p.token\n switch (tok) {\n case 'ddd':\n case 'dddd': {\n const m = matchName(s, i, weekdayNames(locale)[tok === 'ddd' ? 'short' : 'long'])\n if (!m) return null\n i += m.len // weekday is informational; day-of-month drives the date\n break\n }\n case 'MMM':\n case 'MMMM': {\n const m = matchName(s, i, monthNames(locale)[tok === 'MMM' ? 'short' : 'long'])\n if (!m) return null\n acc.month = m.index\n i += m.len\n break\n }\n case 't':\n case 'tt': {\n const dp = dayPeriods(locale)\n const lower = s.slice(i).toLowerCase()\n if (lower.startsWith(dp.pm.toLowerCase())) { acc.isPm = true; i += dp.pm.length }\n else if (lower.startsWith(dp.am.toLowerCase())) { acc.isPm = false; i += dp.am.length }\n else if (lower.startsWith(dp.pm.slice(0, 1).toLowerCase())) { acc.isPm = true; i += 1 }\n else if (lower.startsWith(dp.am.slice(0, 1).toLowerCase())) { acc.isPm = false; i += 1 }\n else return null\n break\n }\n default: {\n const r = readDigits(s, i, MAX_DIGITS[tok] ?? 2)\n if (!r) return null\n i += r.len\n const v = r.value\n switch (tok) {\n case 'd': case 'dd': acc.day = v; break\n case 'M': case 'MM': acc.month = v - 1; break\n case 'yy': acc.year = v <= yearCutoff % 100 ? 2000 + v : 1900 + v; break\n case 'yyyy': acc.year = v; break\n case 'H': case 'HH': acc.hour = v; break\n case 'h': case 'hh': acc.hour12 = v; break\n case 'm': case 'mm': acc.minute = v; break\n case 's': case 'ss': acc.second = v; break\n case 'f': acc.ms = v * 100; break\n case 'ff': acc.ms = v * 10; break\n case 'fff': acc.ms = v; break\n }\n }\n }\n }\n // Trailing input that the mask did not consume is a mismatch.\n if (i !== s.length && s.slice(i).trim() !== '') return null\n\n const b = base ?? new Date(1970, 0, 1)\n let hour = acc.hour\n if (hour == null && acc.hour12 != null) {\n hour = acc.hour12 % 12\n if (acc.isPm) hour += 12\n }\n const year = acc.year ?? b.getFullYear()\n const month = acc.month ?? b.getMonth()\n const day = acc.day ?? b.getDate()\n const result = new Date(\n year,\n month,\n day,\n hour ?? b.getHours(),\n acc.minute ?? b.getMinutes(),\n acc.second ?? b.getSeconds(),\n acc.ms ?? b.getMilliseconds(),\n )\n // Reject impossible dates the constructor silently rolls over (e.g. Feb 31).\n if (\n (acc.day != null && result.getDate() !== day) ||\n (acc.month != null && result.getMonth() !== month)\n ) {\n return null\n }\n return isNaN(result.getTime()) ? null : result\n}\n```\n"
8038
+ "markdown": "# `@svgrid/grid` · `datetime/date-format.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\date-format.ts`.\n\n### `function tokenizeMask`\n\nSplit a mask into an ordered list of token / literal parts.\n\n```ts\nexport function tokenizeMask(mask: string): Part[]\n```\n\n### `function formatDate`\n\nRender `date` per `mask` in `locale`.\n\n```ts\nexport function formatDate(date: Date, mask: string, locale = 'en-US'): string\n```\n\n### `function parseDate`\n\nParse `str` against `mask` in `locale`. Returns a Date or null if the string\ndoes not satisfy the mask. `yearCutoff` disambiguates 2-digit years: values\n<= (yearCutoff % 100) map to 2000s, above to 1900s (Smart's default 1926 ->\na 26 pivot). `base` supplies fields the mask omits (defaults to epoch-zero\nlocal midnight so a time-only mask yields a today-agnostic time).\n\n```ts\nexport function parseDate(\n str: string,\n mask: string,\n locale = 'en-US',\n yearCutoff = 2029,\n base?: Date,\n): Date | null\n```\n"
7968
8039
  },
7969
8040
  {
7970
8041
  "slug": "reference/auto/svgrid-grid-date-restrict",
7971
8042
  "path": "docs/reference/auto/svgrid-grid-date-restrict.md",
7972
8043
  "title": "@svgrid/grid · datetime/date-restrict.ts",
7973
8044
  "section": "API reference",
7974
- "markdown": "# `@svgrid/grid` · `datetime/date-restrict.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\date-restrict.ts`.\n\n### `type RestrictOptions`\n\nWhich dates a picker allows: bounds, an explicit disabled set, and disabled weekdays.\n\n```ts\nexport type RestrictOptions = {\n min?: DateLike | null\n max?: DateLike | null\n /** Individual dates (or predicate) that cannot be selected. */\n restrictedDates?: ReadonlyArray<DateLike> | ((d: Date) => boolean) | null\n}\n```\n\n### `function isOutOfRange`\n\nTrue when `d` is outside the inclusive [min, max] day range.\n\n```ts\nexport function isOutOfRange(d: Date, min?: DateLike | null, max?: DateLike | null): boolean {\n const lo = toDate(min ?? null)\n const hi = toDate(max ?? null)\n if (lo && compareDay(d, lo) < 0) return true\n if (hi && compareDay(d, hi) > 0) return true\n return false\n}\n```\n\n### `function isRestricted`\n\nTrue when `d` is explicitly restricted (by list membership or predicate).\n\n```ts\nexport function isRestricted(\n d: Date,\n restrictedDates?: ReadonlyArray<DateLike> | ((day: Date) => boolean) | null,\n): boolean {\n if (!restrictedDates) return false\n if (typeof restrictedDates === 'function') return restrictedDates(d)\n return normalizeList(restrictedDates).some((r) => isSameDay(r, d))\n}\n```\n\n### `function isDisabledDay`\n\nTrue when `d` cannot be selected: out of [min, max] OR restricted. This is\nthe single predicate the calendar/pickers use to disable a day.\n\n```ts\nexport function isDisabledDay(d: Date, opts: RestrictOptions): boolean {\n return isOutOfRange(d, opts.min, opts.max) || isRestricted(d, opts.restrictedDates)\n}\n```\n\n### `function isImportant`\n\nTrue when `d` is flagged important (highlighted). Never affects selectability.\n\n```ts\nexport function isImportant(\n d: Date,\n importantDates?: ReadonlyArray<DateLike> | ((day: Date) => boolean) | null,\n): boolean {\n if (!importantDates) return false\n if (typeof importantDates === 'function') return importantDates(d)\n return normalizeList(importantDates).some((r) => isSameDay(r, d))\n}\n```\n"
8045
+ "markdown": "# `@svgrid/grid` · `datetime/date-restrict.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\date-restrict.ts`.\n\n### `type RestrictOptions`\n\nWhich dates a picker allows: bounds, an explicit disabled set, and disabled weekdays.\n\n```ts\nexport type RestrictOptions = {\n min?: DateLike | null\n max?: DateLike | null\n /** Individual dates (or predicate) that cannot be selected. */\n restrictedDates?: ReadonlyArray<DateLike> | ((d: Date) => boolean) | null\n}\n```\n\n### `function isOutOfRange`\n\nTrue when `d` is outside the inclusive [min, max] day range.\n\n```ts\nexport function isOutOfRange(d: Date, min?: DateLike | null, max?: DateLike | null): boolean\n```\n\n### `function isRestricted`\n\nTrue when `d` is explicitly restricted (by list membership or predicate).\n\n```ts\nexport function isRestricted(\n d: Date,\n restrictedDates?: ReadonlyArray<DateLike> | ((day: Date) => boolean) | null,\n): boolean\n```\n\n### `function isDisabledDay`\n\nTrue when `d` cannot be selected: out of [min, max] OR restricted. This is\nthe single predicate the calendar/pickers use to disable a day.\n\n```ts\nexport function isDisabledDay(d: Date, opts: RestrictOptions): boolean\n```\n\n### `function isImportant`\n\nTrue when `d` is flagged important (highlighted). Never affects selectability.\n\n```ts\nexport function isImportant(\n d: Date,\n importantDates?: ReadonlyArray<DateLike> | ((day: Date) => boolean) | null,\n): boolean\n```\n"
7975
8046
  },
7976
8047
  {
7977
8048
  "slug": "reference/auto/svgrid-grid-dock-manager-model",
7978
8049
  "path": "docs/reference/auto/svgrid-grid-dock-manager-model.md",
7979
8050
  "title": "@svgrid/grid · dock-manager-model.ts",
7980
8051
  "section": "API reference",
7981
- "markdown": "# `@svgrid/grid` · `dock-manager-model.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\dock-manager-model.ts`.\n\n### `type DockSide`\n\nWhich edge a pane docks against when dropped.\n\n```ts\nexport type DockSide = Exclude<DockZone, 'center'>\n```\n\n### `type FloatWindow`\n\nA floating window: one tabs leaf shown in a movable/resizable frame.\n\n```ts\nexport type FloatWindow = {\n id: string\n leaf: DockTabs\n x: number\n y: number\n width: number\n height: number\n /** Stacking order; higher is on top. */\n z: number\n /** Collapsed to just its title bar. */\n minimized?: boolean\n /** Expanded to fill the manager (its x/y/w/h are kept for restore). */\n maximized?: boolean\n}\n```\n\n### `type AutoHideEntry`\n\nA leaf collapsed to an edge; a fly-out reveals it, \"pin\" re-docks it.\n\n```ts\nexport type AutoHideEntry = {\n id: string\n side: DockSide\n leaf: DockTabs\n /** Fly-out panel size in px along the reveal axis. */\n size: number\n}\n```\n\n### `type DockManagerState`\n\nThe whole dock manager: its layout tree plus floating and pinned panes.\n\n```ts\nexport type DockManagerState = {\n main: DockNode | null\n floating: FloatWindow[]\n autoHide: AutoHideEntry[]\n /** A tiled leaf shown maximized (filling the docked area), or null. */\n maximizedLeaf?: string | null\n}\n```\n\n### `type PaneLocation`\n\nWhere a pane currently lives.\n\n```ts\nexport type PaneLocation =\n | { kind: 'main' }\n | { kind: 'floating'; windowId: string }\n | { kind: 'autoHide'; entryId: string }\n```\n\n### `function locatePane`\n\nFind a pane in the layout tree by id, returning it with its parent for mutation.\n\n```ts\nexport function locatePane(state: DockManagerState, paneId: string): PaneLocation | null {\n if (state.main && findTabsWithPane(state.main, paneId)) return { kind: 'main' }\n for (const w of state.floating) {\n if (w.leaf.panes.some((p) => p.id === paneId)) return { kind: 'floating', windowId: w.id }\n }\n for (const e of state.autoHide) {\n if (e.leaf.panes.some((p) => p.id === paneId)) return { kind: 'autoHide', entryId: e.id }\n }\n return null\n}\n```\n\n### `function surfaceOfTabs`\n\nWhich surface holds a tabs leaf: 'main', a window id, or null.\n\n```ts\nexport function surfaceOfTabs(state: DockManagerState, tabsId: string): 'main' | string | null {\n if (state.main && containsTabs(state.main, tabsId)) return 'main'\n const w = state.floating.find((f) => f.leaf.id === tabsId)\n return w ? w.id : null\n}\n```\n\n### `function reorderTab`\n\nReorder a tab within its leaf, wherever that leaf lives (main or a float).\n\n```ts\nexport function reorderTab(state: DockManagerState, tabsId: string, from: number, to: number): DockManagerState {\n if (state.main && containsTabs(state.main, tabsId)) {\n return { ...state, main: reorderPane(state.main, tabsId, from, to) }\n }\n return {\n ...state,\n floating: state.floating.map((w) => {\n if (w.leaf.id !== tabsId) return w\n const reordered = reorderPane(w.leaf, tabsId, from, to)\n return reordered.type === 'tabs' ? { ...w, leaf: reordered } : w\n }),\n }\n}\n```\n\n### `function resizeGroup`\n\nResize a group's children (splitter drag). Groups only exist in `main`\n (floating windows are single leaves), so this targets the main tree.\n\n```ts\nexport function resizeGroup(state: DockManagerState, groupId: string, sizes: number[]): DockManagerState {\n if (!state.main) return state\n return { ...state, main: setSizesInTree(state.main, groupId, sizes) }\n}\n```\n\n### `function setManagerActive`\n\nSet the active tab of a leaf in main or a floating window.\n\n```ts\nexport function setManagerActive(state: DockManagerState, tabsId: string, active: number): DockManagerState {\n const w = state.floating.find((f) => f.leaf.id === tabsId)\n if (w) {\n return {\n ...state,\n floating: state.floating.map((f) =>\n f.id === w.id ? { ...f, leaf: { ...f.leaf, active: clamp(active, f.leaf.panes.length) } } : f,\n ),\n }\n }\n // Auto-hidden leaf: activate a pane so its edge tab / flyout opens on it.\n const ah = state.autoHide.find((e) => e.leaf.id === tabsId)\n if (ah) {\n return {\n ...state,\n autoHide: state.autoHide.map((e) =>\n e.id === ah.id ? { ...e, leaf: { ...e.leaf, active: clamp(active, e.leaf.panes.length) } } : e,\n ),\n }\n }\n return { ...state, main: state.main ? setActiveInTree(state.main, tabsId, active) : state.main }\n}\n```\n\n### `function dockPaneOnto`\n\nDock a pane onto a target leaf (`center` = new tab, edge = split). Works\nacross surfaces: a floating pane can dock into main, a main pane into a float\n(centre only), etc. Edge zones only apply when the target is in `main`.\n\n```ts\nexport function dockPaneOnto(\n state: DockManagerState,\n paneId: string,\n targetTabsId: string,\n zone: DockZone,\n genId: IdGen,\n): DockManagerState {\n const moving = findPaneObject(state, paneId)\n if (!moving) return state\n const targetSurface = surfaceOfTabs(state, targetTabsId)\n if (!targetSurface) return state\n\n const stripped = stripPane(state, paneId)\n // The target leaf might have dissolved (it was the pane's own single leaf).\n if (surfaceOfTabs(stripped, targetTabsId) === null) return state\n\n if (targetSurface === 'main') {\n const base = stripped.main\n if (!base) return state\n return { ...stripped, main: dockInto(base, targetTabsId, moving, zone, genId) }\n }\n // Docking into a floating window: centre only (add as a tab).\n return {\n ...stripped,\n floating: stripped.floating.map((w) => {\n if (w.id !== targetSurface) return w\n const panes = [...w.leaf.panes, moving]\n return { ...w, leaf: { ...w.leaf, panes, active: panes.length - 1 } }\n }),\n }\n}\n```\n\n### `function addPaneToMain`\n\nInsert a NEW pane into the main area - the first leaf (as a tab), or as the\n whole main when empty. Used to pop a window/pop-out back into the layout.\n\n```ts\nexport function addPaneToMain(state: DockManagerState, p: DockPane, genId: IdGen): DockManagerState {\n if (!state.main) return { ...state, main: tabs(genId, [p], 0) }\n let added = false\n const walk = (n: DockNode): DockNode => {\n if (added) return n\n if (n.type === 'tabs') {\n added = true\n const panes = [...n.panes, p]\n return { ...n, panes, active: panes.length - 1 }\n }\n return { ...n, children: n.children.map(walk) }\n }\n return { ...state, main: walk(state.main) }\n}\n```\n\n### `function dockPaneToEmptyMain`\n\nDock a pane into an empty main area (main becomes a single leaf holding it).\n\n```ts\nexport function dockPaneToEmptyMain(state: DockManagerState, paneId: string, genId: IdGen): DockManagerState {\n const moving = findPaneObject(state, paneId)\n if (!moving) return state\n const stripped = stripPane(state, paneId)\n if (stripped.main) return { ...stripped, main: stripped.main } // main not empty; caller should dock onto a leaf\n return { ...stripped, main: tabs(genId, [moving], 0) }\n}\n```\n\n### `function floatPane`\n\nPop a pane out into a new floating window at the given rect.\n\n```ts\nexport function floatPane(\n state: DockManagerState,\n paneId: string,\n rect: { x: number; y: number; width: number; height: number },\n genId: IdGen,\n): DockManagerState {\n const moving = findPaneObject(state, paneId)\n if (!moving) return state\n const loc = locatePane(state, paneId)\n // Already the sole pane of its own float - nothing to pop out.\n if (loc?.kind === 'floating') {\n const w = state.floating.find((f) => f.id === loc.windowId)\n if (w && w.leaf.panes.length === 1) return state\n }\n const stripped = stripPane(state, paneId)\n const win: FloatWindow = {\n id: genId(),\n leaf: tabs(genId, [moving], 0),\n x: rect.x,\n y: rect.y,\n width: rect.width,\n height: rect.height,\n z: maxZ(state) + 1,\n }\n return { ...stripped, floating: [...stripped.floating, win] }\n}\n```\n\n### `function dockWindowOnto`\n\nDock an entire floating window's panes back into a main leaf.\n\n```ts\nexport function dockWindowOnto(\n state: DockManagerState,\n windowId: string,\n targetTabsId: string,\n zone: DockZone,\n genId: IdGen,\n): DockManagerState {\n const win = state.floating.find((w) => w.id === windowId)\n if (!win) return state\n if (surfaceOfTabs(state, targetTabsId) !== 'main' || !state.main) return state\n const rest = state.floating.filter((w) => w.id !== windowId)\n if (zone === 'center') {\n return {\n ...state,\n floating: rest,\n main: state.main\n ? mergePanesInto(state.main, targetTabsId, win.leaf.panes)\n : state.main,\n }\n }\n // Edge: drop the window's whole leaf beside the target.\n const leaf = tabs(genId, win.leaf.panes, win.leaf.active)\n const dir = zone === 'left' || zone === 'right' ? 'row' : 'column'\n const before = zone === 'left' || zone === 'top'\n return {\n ...state,\n floating: rest,\n main: insertLeafBeside(state.main, targetTabsId, leaf, dir, before, genId),\n }\n}\n```\n\n### `function moveWindow`\n\nMove a floating window (top-left).\n\n```ts\nexport function moveWindow(state: DockManagerState, windowId: string, x: number, y: number): DockManagerState {\n return { ...state, floating: state.floating.map((w) => (w.id === windowId ? { ...w, x, y } : w)) }\n}\n```\n\n### `function resizeWindow`\n\nResize a floating window.\n\n```ts\nexport function resizeWindow(\n state: DockManagerState,\n windowId: string,\n width: number,\n height: number,\n): DockManagerState {\n return {\n ...state,\n floating: state.floating.map((w) =>\n w.id === windowId ? { ...w, width: Math.max(140, width), height: Math.max(80, height) } : w,\n ),\n }\n}\n```\n\n### `function bringToFront`\n\nRaise a floating window to the top of the stack.\n\n```ts\nexport function bringToFront(state: DockManagerState, windowId: string): DockManagerState {\n const top = maxZ(state)\n return { ...state, floating: state.floating.map((w) => (w.id === windowId ? { ...w, z: top + 1 } : w)) }\n}\n```\n\n### `function setWindowMinimized`\n\nCollapse a floating window to just its title bar (or restore it).\n\n```ts\nexport function setWindowMinimized(state: DockManagerState, windowId: string, minimized: boolean): DockManagerState {\n return {\n ...state,\n floating: state.floating.map((w) =>\n w.id === windowId ? { ...w, minimized, maximized: minimized ? false : w.maximized } : w,\n ),\n }\n}\n```\n\n### `function toggleWindowMaximized`\n\nToggle a floating window between filling the manager and its own rect.\n\n```ts\nexport function toggleWindowMaximized(state: DockManagerState, windowId: string): DockManagerState {\n return {\n ...state,\n floating: state.floating.map((w) =>\n w.id === windowId ? { ...w, maximized: !w.maximized, minimized: false } : w,\n ),\n }\n}\n```\n\n### `function closeWindow`\n\nClose a floating window and all its panes.\n\n```ts\nexport function closeWindow(state: DockManagerState, windowId: string): DockManagerState {\n return { ...state, floating: state.floating.filter((w) => w.id !== windowId) }\n}\n```\n\n### `function findLeafById`\n\nFind a tabs leaf anywhere (main or a floating window) by id.\n\n```ts\nexport function findLeafById(state: DockManagerState, tabsId: string): DockTabs | null {\n const scan = (n: DockNode): DockTabs | null => {\n if (n.type === 'tabs') return n.id === tabsId ? n : null\n for (const c of n.children) { const hit = scan(c); if (hit) return hit }\n return null\n }\n if (state.main) { const m = scan(state.main); if (m) return m }\n const w = state.floating.find((f) => f.leaf.id === tabsId)\n if (w) return w.leaf\n const e = state.autoHide.find((x) => x.leaf.id === tabsId)\n return e ? e.leaf : null\n}\n```\n\n### `function toggleMaximizeLeaf`\n\nToggle a tiled leaf maximized (filling the docked area). Clears if it is gone.\n\n```ts\nexport function toggleMaximizeLeaf(state: DockManagerState, tabsId: string): DockManagerState {\n const on = state.maximizedLeaf === tabsId\n return { ...state, maximizedLeaf: on ? null : tabsId }\n}\n```\n\n### `function autoHideWindow`\n\nSend a floating window's panel to an edge as an auto-hidden entry.\n\n```ts\nexport function autoHideWindow(\n state: DockManagerState,\n windowId: string,\n side: DockSide,\n genId: IdGen,\n size = 260,\n): DockManagerState {\n const w = state.floating.find((f) => f.id === windowId)\n if (!w) return state\n const entry: AutoHideEntry = { id: genId(), side, leaf: tabs(genId, w.leaf.panes, w.leaf.active), size }\n return { ...state, floating: state.floating.filter((f) => f.id !== windowId), autoHide: [...state.autoHide, entry] }\n}\n```\n\n### `function autoHideLeaf`\n\nCollapse a MAIN leaf to an edge strip (auto-hide) on the given side.\n\n```ts\nexport function autoHideLeaf(\n state: DockManagerState,\n tabsId: string,\n side: DockSide,\n size = 260,\n): DockManagerState {\n if (!state.main) return state\n const { root, leaf } = removeLeaf(state.main, tabsId)\n if (!leaf) return state\n const entry: AutoHideEntry = { id: `ah-${tabsId}`, side, leaf, size }\n return { ...state, main: root, autoHide: [...state.autoHide, entry] }\n}\n```\n\n### `function autoHidePaneToSide`\n\nAuto-hide a single pane to an edge (drag a tab to the manager border). The\n pane leaves its leaf and becomes its own collapsed entry on that side.\n\n```ts\nexport function autoHidePaneToSide(\n state: DockManagerState,\n paneId: string,\n side: DockSide,\n genId: IdGen,\n size = 260,\n): DockManagerState {\n const moving = findPaneObject(state, paneId)\n if (!moving) return state\n const stripped = stripPane(state, paneId)\n const entry: AutoHideEntry = { id: genId(), side, leaf: tabs(genId, [moving], 0), size }\n return { ...stripped, autoHide: [...stripped.autoHide, entry] }\n}\n```\n\n### `function pinAutoHidden`\n\nPin an auto-hidden entry back into the main dock area on its edge. `fraction`\nis the share of the axis the re-docked panel should take (default 0.25).\n\n```ts\nexport function pinAutoHidden(\n state: DockManagerState,\n entryId: string,\n genId: IdGen,\n fraction = 0.25,\n): DockManagerState {\n const entry = state.autoHide.find((e) => e.id === entryId)\n if (!entry) return state\n const leaf = tabs(genId, entry.leaf.panes, entry.leaf.active)\n return {\n ...state,\n autoHide: state.autoHide.filter((e) => e.id !== entryId),\n main: dockLeafToEdge(state.main, leaf, entry.side, genId, fraction),\n }\n}\n```\n\n### `function setAutoHideSize`\n\nResize an auto-hide fly-out.\n\n```ts\nexport function setAutoHideSize(state: DockManagerState, entryId: string, size: number): DockManagerState {\n return {\n ...state,\n autoHide: state.autoHide.map((e) => (e.id === entryId ? { ...e, size: Math.max(120, size) } : e)),\n }\n}\n```\n\n### `function closePane`\n\nClose a pane wherever it lives.\n\n```ts\nexport function closePane(state: DockManagerState, paneId: string): DockManagerState {\n return stripPane(state, paneId)\n}\n```\n\n### `function allManagerPaneIds`\n\nEvery pane id across all surfaces.\n\n```ts\nexport function allManagerPaneIds(state: DockManagerState): string[] {\n const ids: string[] = []\n if (state.main) ids.push(...allPaneIds(state.main))\n for (const w of state.floating) ids.push(...w.leaf.panes.map((p) => p.id))\n for (const e of state.autoHide) ids.push(...e.leaf.panes.map((p) => p.id))\n return ids\n}\n```\n\n### `function allManagerIds`\n\nEvery id used anywhere in the workspace: node ids (groups + tabs leaves),\n pane ids, floating-window ids and auto-hide entry ids. Used to keep a freshly\n generated id unique even against a workspace restored from storage - the\n manager's id counter is module-scoped and resets on reload, so without this\n the same `dm-N` can be minted twice and collide (a keyed `{#each}` then throws\n `each_key_duplicate`).\n\n```ts\nexport function allManagerIds(state: DockManagerState): string[] {\n const ids: string[] = []\n const walk = (n: DockNode) => {\n ids.push(n.id)\n if (n.type === 'tabs') for (const p of n.panes) ids.push(p.id)\n else for (const c of n.children) walk(c)\n }\n if (state.main) walk(state.main)\n for (const w of state.floating) { ids.push(w.id); walk(w.leaf) }\n for (const e of state.autoHide) { ids.push(e.id); walk(e.leaf) }\n return ids\n}\n```\n\n### `function dedupeManagerNodeIds`\n\nReassign any duplicate group / tabs NODE id (and floating-window / auto-hide\n entry id) so no keyed sibling list sees a collision. Pane ids are left alone -\n they key the `pane` snippet to its content, so a rename would blank a panel;\n a restored workspace's repeats are always on the generated node ids anyway.\n Idempotent: a clean workspace is returned value-equal.\n\n```ts\nexport function dedupeManagerNodeIds(state: DockManagerState): DockManagerState {\n const seen = new Set<string>()\n let n = 1\n const fresh = (): string => { let id = `dm-d${n++}`; while (seen.has(id)) id = `dm-d${n++}`; return id }\n const uniq = (id: string): string => {\n const next = seen.has(id) ? fresh() : id\n seen.add(next)\n return next\n }\n const walk = (node: DockNode): DockNode => {\n const id = uniq(node.id)\n if (node.type === 'tabs') return id === node.id ? node : { ...node, id }\n const children = node.children.map(walk)\n const same = id === node.id && children.every((c, i) => c === node.children[i])\n return same ? node : { ...node, id, children }\n }\n const main = state.main ? walk(state.main) : state.main\n let floatChanged = false\n const floating = state.floating.map((w) => {\n const id = uniq(w.id)\n const leaf = walk(w.leaf) as DockTabs\n if (id === w.id && leaf === w.leaf) return w\n floatChanged = true\n return { ...w, id, leaf }\n })\n let hideChanged = false\n const autoHide = state.autoHide.map((e) => {\n const id = uniq(e.id)\n const leaf = walk(e.leaf) as DockTabs\n if (id === e.id && leaf === e.leaf) return e\n hideChanged = true\n return { ...e, id, leaf }\n })\n // Preserve identity when nothing was duplicated - keeps the effect that seeds\n // the manager from re-running and avoids needless re-renders.\n if (main === state.main && !floatChanged && !hideChanged) return state\n return { ...state, main, floating: floatChanged ? floating : state.floating, autoHide: hideChanged ? autoHide : state.autoHide }\n}\n```\n"
8052
+ "markdown": "# `@svgrid/grid` · `dock-manager-model.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\dock-manager-model.ts`.\n\n### `type DockSide`\n\nWhich edge a pane docks against when dropped.\n\n```ts\nexport type DockSide = Exclude<DockZone, 'center'>\n```\n\n### `type FloatWindow`\n\nA floating window: one tabs leaf shown in a movable/resizable frame.\n\n```ts\nexport type FloatWindow = {\n id: string\n leaf: DockTabs\n x: number\n y: number\n width: number\n height: number\n /** Stacking order; higher is on top. */\n z: number\n /** Collapsed to just its title bar. */\n minimized?: boolean\n /** Expanded to fill the manager (its x/y/w/h are kept for restore). */\n maximized?: boolean\n}\n```\n\n### `type AutoHideEntry`\n\nA leaf collapsed to an edge; a fly-out reveals it, \"pin\" re-docks it.\n\n```ts\nexport type AutoHideEntry = {\n id: string\n side: DockSide\n leaf: DockTabs\n /** Fly-out panel size in px along the reveal axis. */\n size: number\n}\n```\n\n### `type DockManagerState`\n\nThe whole dock manager: its layout tree plus floating and pinned panes.\n\n```ts\nexport type DockManagerState = {\n main: DockNode | null\n floating: FloatWindow[]\n autoHide: AutoHideEntry[]\n /** A tiled leaf shown maximized (filling the docked area), or null. */\n maximizedLeaf?: string | null\n}\n```\n\n### `type PaneLocation`\n\nWhere a pane currently lives.\n\n```ts\nexport type PaneLocation =\n | { kind: 'main' }\n | { kind: 'floating'; windowId: string }\n | { kind: 'autoHide'; entryId: string }\n```\n\n### `function locatePane`\n\nFind a pane in the layout tree by id, returning it with its parent for mutation.\n\n```ts\nexport function locatePane(state: DockManagerState, paneId: string): PaneLocation | null\n```\n\n### `function surfaceOfTabs`\n\nWhich surface holds a tabs leaf: 'main', a window id, or null.\n\n```ts\nexport function surfaceOfTabs(state: DockManagerState, tabsId: string): 'main' | string | null\n```\n\n### `function reorderTab`\n\nReorder a tab within its leaf, wherever that leaf lives (main or a float).\n\n```ts\nexport function reorderTab(state: DockManagerState, tabsId: string, from: number, to: number): DockManagerState\n```\n\n### `function resizeGroup`\n\nResize a group's children (splitter drag). Groups only exist in `main`\n (floating windows are single leaves), so this targets the main tree.\n\n```ts\nexport function resizeGroup(state: DockManagerState, groupId: string, sizes: number[]): DockManagerState\n```\n\n### `function setManagerActive`\n\nSet the active tab of a leaf in main or a floating window.\n\n```ts\nexport function setManagerActive(state: DockManagerState, tabsId: string, active: number): DockManagerState\n```\n\n### `function dockPaneOnto`\n\nDock a pane onto a target leaf (`center` = new tab, edge = split). Works\nacross surfaces: a floating pane can dock into main, a main pane into a float\n(centre only), etc. Edge zones only apply when the target is in `main`.\n\n```ts\nexport function dockPaneOnto(\n state: DockManagerState,\n paneId: string,\n targetTabsId: string,\n zone: DockZone,\n genId: IdGen,\n): DockManagerState\n```\n\n### `function addPaneToMain`\n\nInsert a NEW pane into the main area - the first leaf (as a tab), or as the\n whole main when empty. Used to pop a window/pop-out back into the layout.\n\n```ts\nexport function addPaneToMain(state: DockManagerState, p: DockPane, genId: IdGen): DockManagerState\n```\n\n### `function dockPaneToEmptyMain`\n\nDock a pane into an empty main area (main becomes a single leaf holding it).\n\n```ts\nexport function dockPaneToEmptyMain(state: DockManagerState, paneId: string, genId: IdGen): DockManagerState\n```\n\n### `function floatPane`\n\nPop a pane out into a new floating window at the given rect.\n\n```ts\nexport function floatPane(\n state: DockManagerState,\n paneId: string,\n rect: { x: number; y: number; width: number; height: number },\n genId: IdGen,\n): DockManagerState\n```\n\n### `function dockWindowOnto`\n\nDock an entire floating window's panes back into a main leaf.\n\n```ts\nexport function dockWindowOnto(\n state: DockManagerState,\n windowId: string,\n targetTabsId: string,\n zone: DockZone,\n genId: IdGen,\n): DockManagerState\n```\n\n### `function moveWindow`\n\nMove a floating window (top-left).\n\n```ts\nexport function moveWindow(state: DockManagerState, windowId: string, x: number, y: number): DockManagerState\n```\n\n### `function resizeWindow`\n\nResize a floating window.\n\n```ts\nexport function resizeWindow(\n state: DockManagerState,\n windowId: string,\n width: number,\n height: number,\n): DockManagerState\n```\n\n### `function bringToFront`\n\nRaise a floating window to the top of the stack.\n\n```ts\nexport function bringToFront(state: DockManagerState, windowId: string): DockManagerState\n```\n\n### `function setWindowMinimized`\n\nCollapse a floating window to just its title bar (or restore it).\n\n```ts\nexport function setWindowMinimized(state: DockManagerState, windowId: string, minimized: boolean): DockManagerState\n```\n\n### `function toggleWindowMaximized`\n\nToggle a floating window between filling the manager and its own rect.\n\n```ts\nexport function toggleWindowMaximized(state: DockManagerState, windowId: string): DockManagerState\n```\n\n### `function closeWindow`\n\nClose a floating window and all its panes.\n\n```ts\nexport function closeWindow(state: DockManagerState, windowId: string): DockManagerState\n```\n\n### `function findLeafById`\n\nFind a tabs leaf anywhere (main or a floating window) by id.\n\n```ts\nexport function findLeafById(state: DockManagerState, tabsId: string): DockTabs | null\n```\n\n### `function toggleMaximizeLeaf`\n\nToggle a tiled leaf maximized (filling the docked area). Clears if it is gone.\n\n```ts\nexport function toggleMaximizeLeaf(state: DockManagerState, tabsId: string): DockManagerState\n```\n\n### `function autoHideWindow`\n\nSend a floating window's panel to an edge as an auto-hidden entry.\n\n```ts\nexport function autoHideWindow(\n state: DockManagerState,\n windowId: string,\n side: DockSide,\n genId: IdGen,\n size = 260,\n): DockManagerState\n```\n\n### `function autoHideLeaf`\n\nCollapse a MAIN leaf to an edge strip (auto-hide) on the given side.\n\n```ts\nexport function autoHideLeaf(\n state: DockManagerState,\n tabsId: string,\n side: DockSide,\n size = 260,\n): DockManagerState\n```\n\n### `function autoHidePaneToSide`\n\nAuto-hide a single pane to an edge (drag a tab to the manager border). The\n pane leaves its leaf and becomes its own collapsed entry on that side.\n\n```ts\nexport function autoHidePaneToSide(\n state: DockManagerState,\n paneId: string,\n side: DockSide,\n genId: IdGen,\n size = 260,\n): DockManagerState\n```\n\n### `function pinAutoHidden`\n\nPin an auto-hidden entry back into the main dock area on its edge. `fraction`\nis the share of the axis the re-docked panel should take (default 0.25).\n\n```ts\nexport function pinAutoHidden(\n state: DockManagerState,\n entryId: string,\n genId: IdGen,\n fraction = 0.25,\n): DockManagerState\n```\n\n### `function setAutoHideSize`\n\nResize an auto-hide fly-out.\n\n```ts\nexport function setAutoHideSize(state: DockManagerState, entryId: string, size: number): DockManagerState\n```\n\n### `function closePane`\n\nClose a pane wherever it lives.\n\n```ts\nexport function closePane(state: DockManagerState, paneId: string): DockManagerState\n```\n\n### `function allManagerPaneIds`\n\nEvery pane id across all surfaces.\n\n```ts\nexport function allManagerPaneIds(state: DockManagerState): string[]\n```\n\n### `function allManagerIds`\n\nEvery id used anywhere in the workspace: node ids (groups + tabs leaves),\n pane ids, floating-window ids and auto-hide entry ids. Used to keep a freshly\n generated id unique even against a workspace restored from storage - the\n manager's id counter is module-scoped and resets on reload, so without this\n the same `dm-N` can be minted twice and collide (a keyed `{#each}` then throws\n `each_key_duplicate`).\n\n```ts\nexport function allManagerIds(state: DockManagerState): string[]\n```\n\n### `function dedupeManagerNodeIds`\n\nReassign any duplicate group / tabs NODE id (and floating-window / auto-hide\n entry id) so no keyed sibling list sees a collision. Pane ids are left alone -\n they key the `pane` snippet to its content, so a rename would blank a panel;\n a restored workspace's repeats are always on the generated node ids anyway.\n Idempotent: a clean workspace is returned value-equal.\n\n```ts\nexport function dedupeManagerNodeIds(state: DockManagerState): DockManagerState\n```\n"
7982
8053
  },
7983
8054
  {
7984
8055
  "slug": "reference/auto/svgrid-grid-dock-model",
7985
8056
  "path": "docs/reference/auto/svgrid-grid-dock-model.md",
7986
8057
  "title": "@svgrid/grid · dock-model.ts",
7987
8058
  "section": "API reference",
7988
- "markdown": "# `@svgrid/grid` · `dock-model.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\dock-model.ts`.\n\n### `type DockPane`\n\nOne dockable pane: its id, title, and the state a tab needs to render.\n\n```ts\nexport type DockPane = {\n id: string\n title: string\n /** Show a close (x) affordance on the tab. Default true. */\n closable?: boolean\n /** Minimum size (px) for this pane's leaf along the split axis. */\n minSize?: number\n}\n```\n\n### `type DockTabs`\n\nA leaf: a stack of panes rendered as tabs (`active` is the visible one).\n\n```ts\nexport type DockTabs = {\n type: 'tabs'\n id: string\n panes: DockPane[]\n active: number\n}\n```\n\n### `type DockGroup`\n\nA row (side-by-side) or column (stacked) of children with per-child sizes.\n\n```ts\nexport type DockGroup = {\n type: 'group'\n id: string\n direction: 'row' | 'column'\n children: DockNode[]\n /** Size weight per child; parallel to `children`, normalized to sum ~1. */\n sizes: number[]\n}\n```\n\n### `type DockNode`\n\nA node in the layout tree - either a split group or a tabbed leaf.\n\n```ts\nexport type DockNode = DockGroup | DockTabs\n```\n\n### `type DockZone`\n\nWhere a dragged pane lands relative to a target leaf.\n\n```ts\nexport type DockZone = 'left' | 'right' | 'top' | 'bottom' | 'center'\n```\n\n### `type IdGen`\n\nSupplies ids for newly created nodes, so layouts stay deterministic in tests.\n\n```ts\nexport type IdGen = () => string\n```\n\n### `function pane`\n\nBuild a {@link DockPane}.\n\n```ts\nexport function pane(id: string, title: string, closable = true): DockPane {\n return { id, title, closable }\n}\n```\n\n### `function leafMinSize`\n\nLargest per-pane `minSize` in a leaf (0 if none). Used by splitter clamping.\n\n```ts\nexport function leafMinSize(node: DockTabs): number {\n return node.panes.reduce((m, p) => Math.max(m, p.minSize ?? 0), 0)\n}\n```\n\n### `function tabs`\n\nBuild a tabbed leaf holding the given panes.\n\n```ts\nexport function tabs(genId: IdGen, panes: DockPane[], active = 0): DockTabs {\n return { type: 'tabs', id: genId(), panes, active: clampIndex(active, panes.length) }\n}\n```\n\n### `function group`\n\nBuild a split group: panes or nested groups laid out in a row or column.\n\n```ts\nexport function group(\n genId: IdGen,\n direction: 'row' | 'column',\n children: DockNode[],\n sizes?: number[],\n): DockGroup {\n return { type: 'group', id: genId(), direction, children, sizes: normalizeSizes(sizes, children.length) }\n}\n```\n\n### `function normalizeSizes`\n\nReturn sizes summing to 1, padded/trimmed to `count`. Even split when absent.\n\n```ts\nexport function normalizeSizes(sizes: number[] | undefined, count: number): number[] {\n if (count <= 0) return []\n const src = sizes && sizes.length === count ? sizes.slice() : new Array(count).fill(1)\n const total = src.reduce((a, b) => a + (b > 0 ? b : 0), 0)\n if (total <= 0) return new Array(count).fill(1 / count)\n return src.map((s) => (s > 0 ? s : 0) / total)\n}\n```\n\n### `function findTabsWithPane`\n\nThe tabs leaf that holds `paneId`, or null.\n\n```ts\nexport function findTabsWithPane(root: DockNode, paneId: string): DockTabs | null {\n if (root.type === 'tabs') return root.panes.some((p) => p.id === paneId) ? root : null\n for (const c of root.children) {\n const hit = findTabsWithPane(c, paneId)\n if (hit) return hit\n }\n return null\n}\n```\n\n### `function allPaneIds`\n\nEvery pane id in the tree, in document order.\n\n```ts\nexport function allPaneIds(root: DockNode): string[] {\n if (root.type === 'tabs') return root.panes.map((p) => p.id)\n return root.children.flatMap(allPaneIds)\n}\n```\n\n### `function normalize`\n\nCollapse the tree after edits: drop empty tabs and empty groups, unwrap a\ngroup that has a single child, and flatten a child group into its parent when\nthey share a direction (so repeated docking never nests infinitely deep).\nReturns the tidied node, or null when nothing is left.\n\n```ts\nexport function normalize(node: DockNode): DockNode | null {\n if (node.type === 'tabs') {\n if (node.panes.length === 0) return null\n return { ...node, active: clampIndex(node.active, node.panes.length) }\n }\n\n // Normalize children first, dropping the empties.\n const kept: DockNode[] = []\n const keptSizes: number[] = []\n node.children.forEach((child, i) => {\n const n = normalize(child)\n if (n) {\n kept.push(n)\n keptSizes.push(node.sizes[i] ?? 1)\n }\n })\n\n if (kept.length === 0) return null\n if (kept.length === 1) return kept[0]! // unwrap single-child group\n\n // Flatten same-direction child groups into this one.\n const flatChildren: DockNode[] = []\n const flatSizes: number[] = []\n kept.forEach((child, i) => {\n if (child.type === 'group' && child.direction === node.direction) {\n const share = keptSizes[i]!\n child.children.forEach((gc, j) => {\n flatChildren.push(gc)\n flatSizes.push(share * (child.sizes[j] ?? 1 / child.children.length))\n })\n } else {\n flatChildren.push(child)\n flatSizes.push(keptSizes[i]!)\n }\n })\n\n return { ...node, children: flatChildren, sizes: normalizeSizes(flatSizes, flatChildren.length) }\n}\n```\n\n### `function setActive`\n\nSet the active tab index of a tabs leaf.\n\n```ts\nexport function setActive(root: DockNode, tabsId: string, active: number): DockNode {\n return mapNodes(root, (n) =>\n n.type === 'tabs' && n.id === tabsId ? { ...n, active: clampIndex(active, n.panes.length) } : n,\n )\n}\n```\n\n### `function setSizes`\n\nReplace a group's size weights (e.g. after a splitter drag).\n\n```ts\nexport function setSizes(root: DockNode, groupId: string, sizes: number[]): DockNode {\n return mapNodes(root, (n) =>\n n.type === 'group' && n.id === groupId ? { ...n, sizes: normalizeSizes(sizes, n.children.length) } : n,\n )\n}\n```\n\n### `function reorderPane`\n\nReorder a pane WITHIN its tabs leaf (dragging a tab along the strip). `active`\nfollows the pane that was showing. No-op if the indices are out of range.\n\n```ts\nexport function reorderPane(root: DockNode, tabsId: string, from: number, to: number): DockNode {\n return mapNodes(root, (n) => {\n if (n.type !== 'tabs' || n.id !== tabsId) return n\n if (from < 0 || from >= n.panes.length) return n\n const showing = n.panes[n.active]?.id\n const panes = n.panes.slice()\n const [moved] = panes.splice(from, 1)\n if (!moved) return n\n // `to` is an insertion point in [0, length] (length = append), not a select\n // index - clampIndex would wrongly cap it at length-1.\n panes.splice(Math.max(0, Math.min(to, panes.length)), 0, moved)\n const active = panes.findIndex((p) => p.id === showing)\n return { ...n, panes, active: active < 0 ? 0 : active }\n })\n}\n```\n\n### `function removePane`\n\nRemove a pane. Returns the tidied tree (or null if it emptied) plus the pane\nthat was pulled out, so a caller can re-dock it elsewhere.\n\n```ts\nexport function removePane(root: DockNode, paneId: string): { root: DockNode | null; pane: DockPane | null } {\n let removed: DockPane | null = null\n const strip = (node: DockNode): DockNode => {\n if (node.type === 'tabs') {\n const idx = node.panes.findIndex((p) => p.id === paneId)\n if (idx < 0) return node\n removed = node.panes[idx]!\n const panes = node.panes.filter((_, i) => i !== idx)\n return { ...node, panes, active: clampIndex(node.active > idx ? node.active - 1 : node.active, panes.length) }\n }\n return { ...node, children: node.children.map(strip) }\n }\n const stripped = strip(root)\n return { root: normalize(stripped), pane: removed }\n}\n```\n\n### `function dockInto`\n\nDock `movingPane` relative to the leaf `targetTabsId`. `center` adds it as a\ntab; an edge splits: the target is wrapped in (or extended into) a group whose\ndirection matches the edge, with the new pane on the requested side.\n\n```ts\nexport function dockInto(\n root: DockNode,\n targetTabsId: string,\n movingPane: DockPane,\n zone: DockZone,\n genId: IdGen,\n): DockNode {\n const dir: 'row' | 'column' = zone === 'left' || zone === 'right' ? 'row' : 'column'\n const before = zone === 'left' || zone === 'top'\n\n const transform = (node: DockNode): DockNode => {\n if (node.type === 'tabs') {\n if (node.id !== targetTabsId) return node\n if (zone === 'center') {\n const panes = [...node.panes, movingPane]\n return { ...node, panes, active: panes.length - 1 }\n }\n // Edge on a bare leaf: wrap it in a new group with the new leaf beside it.\n const leaf = tabs(genId, [movingPane], 0)\n const kids = before ? [leaf, node] : [node, leaf]\n return group(genId, dir, kids)\n }\n\n // Group: if it directly contains the target leaf and matches the edge\n // direction, insert a sibling in place (keeps the tree flat).\n const idx = node.children.findIndex((c) => c.type === 'tabs' && c.id === targetTabsId)\n if (idx >= 0 && zone !== 'center' && node.direction === dir) {\n const leaf = tabs(genId, [movingPane], 0)\n const children = node.children.slice()\n const sizes = node.sizes.slice()\n const half = (node.sizes[idx] ?? 1 / node.children.length) / 2\n const insertAt = before ? idx : idx + 1\n children.splice(insertAt, 0, leaf)\n sizes.splice(idx, 1, half, half) // split the target's slot in two\n // splice above replaced 1 with 2 at idx; the new leaf takes `before`/after\n if (before) {\n // children: [..., leaf, target, ...]; sizes already [half(leaf), half(target)]\n } else {\n // we inserted leaf AFTER target but sizes are [half, half] at idx/idx+1 - correct\n }\n return { ...node, children, sizes: normalizeSizes(sizes, children.length) }\n }\n\n return { ...node, children: node.children.map(transform) }\n }\n\n return normalize(transform(root)) ?? root\n}\n```\n\n### `function removeLeaf`\n\nPull a whole tabs leaf out of the tree (for auto-hide). Returns the tidied\n tree (or null) plus the extracted leaf.\n\n```ts\nexport function removeLeaf(root: DockNode, tabsId: string): { root: DockNode | null; leaf: DockTabs | null } {\n let taken: DockTabs | null = null\n const strip = (node: DockNode): DockNode | null => {\n if (node.type === 'tabs') {\n if (node.id === tabsId) { taken = node; return null }\n return node\n }\n const kids: DockNode[] = []\n const sizes: number[] = []\n node.children.forEach((c, i) => {\n const n = strip(c)\n if (n) { kids.push(n); sizes.push(node.sizes[i] ?? 1) }\n })\n if (kids.length === 0) return null\n return { ...node, children: kids, sizes: normalizeSizes(sizes, kids.length) }\n }\n const stripped = strip(root)\n return { root: stripped ? normalize(stripped) : null, leaf: taken }\n}\n```\n\n### `function dockLeafToEdge`\n\nDock a whole leaf against an EDGE of the entire tree (for pinning an\n auto-hidden panel back in). Wraps the root in a new group as needed; the\n pinned leaf takes `fraction` of that axis (clamped 0.1..0.6), the rest keeps\n the existing content.\n\n```ts\nexport function dockLeafToEdge(\n root: DockNode | null,\n leaf: DockTabs,\n side: Exclude<DockZone, 'center'>,\n genId: IdGen,\n fraction = 0.25,\n): DockNode {\n if (!root) return leaf\n const dir: 'row' | 'column' = side === 'left' || side === 'right' ? 'row' : 'column'\n const before = side === 'left' || side === 'top'\n const f = Math.min(0.6, Math.max(0.1, fraction))\n const kids = before ? [leaf, root] : [root, leaf]\n const sizes = before ? [f, 1 - f] : [1 - f, f]\n return normalize(group(genId, dir, kids, sizes)) ?? leaf\n}\n```\n\n### `function movePane`\n\nMove an existing pane to a new dock position (remove then dock).\n\n```ts\nexport function movePane(\n root: DockNode,\n paneId: string,\n targetTabsId: string,\n zone: DockZone,\n genId: IdGen,\n): DockNode {\n const { root: without, pane: moved } = removePane(root, paneId)\n if (!without || !moved) return root\n // If removing the pane dissolved the target leaf (it was the pane's own\n // single-pane leaf), there is nothing to dock against - leave the tree as-is.\n if (!containsTabs(without, targetTabsId)) return root\n return dockInto(without, targetTabsId, moved, zone, genId)\n}\n```\n\n### `function dockPane`\n\nA pane (tab). Alias of `pane`, named for the public builder set.\n\n```ts\nexport function dockPane(\n id: string,\n title: string,\n opts?: boolean | { closable?: boolean; minSize?: number },\n): DockPane {\n const o = typeof opts === 'boolean' ? { closable: opts } : (opts ?? {})\n return { id, title, closable: o.closable ?? true, ...(o.minSize != null ? { minSize: o.minSize } : {}) }\n}\n```\n\n### `function dockTabs`\n\nA tab-leaf holding one or more panes.\n\n```ts\nexport function dockTabs(panes: DockPane[], active = 0): DockTabs {\n return tabs(autoId, panes, active)\n}\n```\n\n### `function dockGroup`\n\nA row (side-by-side) or column (stacked) of children.\n\n```ts\nexport function dockGroup(\n direction: 'row' | 'column',\n children: DockNode[],\n sizes?: number[],\n): DockGroup {\n return group(autoId, direction, children, sizes)\n}\n```\n"
8059
+ "markdown": "# `@svgrid/grid` · `dock-model.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\dock-model.ts`.\n\n### `type DockPane`\n\nOne dockable pane: its id, title, and the state a tab needs to render.\n\n```ts\nexport type DockPane = {\n id: string\n title: string\n /** Show a close (x) affordance on the tab. Default true. */\n closable?: boolean\n /** Minimum size (px) for this pane's leaf along the split axis. */\n minSize?: number\n}\n```\n\n### `type DockTabs`\n\nA leaf: a stack of panes rendered as tabs (`active` is the visible one).\n\n```ts\nexport type DockTabs = {\n type: 'tabs'\n id: string\n panes: DockPane[]\n active: number\n}\n```\n\n### `type DockGroup`\n\nA row (side-by-side) or column (stacked) of children with per-child sizes.\n\n```ts\nexport type DockGroup = {\n type: 'group'\n id: string\n direction: 'row' | 'column'\n children: DockNode[]\n /** Size weight per child; parallel to `children`, normalized to sum ~1. */\n sizes: number[]\n}\n```\n\n### `type DockNode`\n\nA node in the layout tree - either a split group or a tabbed leaf.\n\n```ts\nexport type DockNode = DockGroup | DockTabs\n```\n\n### `type DockZone`\n\nWhere a dragged pane lands relative to a target leaf.\n\n```ts\nexport type DockZone = 'left' | 'right' | 'top' | 'bottom' | 'center'\n```\n\n### `type IdGen`\n\nSupplies ids for newly created nodes, so layouts stay deterministic in tests.\n\n```ts\nexport type IdGen = () => string\n```\n\n### `function pane`\n\nBuild a {@link DockPane}.\n\n```ts\nexport function pane(id: string, title: string, closable = true): DockPane\n```\n\n### `function leafMinSize`\n\nLargest per-pane `minSize` in a leaf (0 if none). Used by splitter clamping.\n\n```ts\nexport function leafMinSize(node: DockTabs): number\n```\n\n### `function tabs`\n\nBuild a tabbed leaf holding the given panes.\n\n```ts\nexport function tabs(genId: IdGen, panes: DockPane[], active = 0): DockTabs\n```\n\n### `function group`\n\nBuild a split group: panes or nested groups laid out in a row or column.\n\n```ts\nexport function group(\n genId: IdGen,\n direction: 'row' | 'column',\n children: DockNode[],\n sizes?: number[],\n): DockGroup\n```\n\n### `function normalizeSizes`\n\nReturn sizes summing to 1, padded/trimmed to `count`. Even split when absent.\n\n```ts\nexport function normalizeSizes(sizes: number[] | undefined, count: number): number[]\n```\n\n### `function findTabsWithPane`\n\nThe tabs leaf that holds `paneId`, or null.\n\n```ts\nexport function findTabsWithPane(root: DockNode, paneId: string): DockTabs | null\n```\n\n### `function allPaneIds`\n\nEvery pane id in the tree, in document order.\n\n```ts\nexport function allPaneIds(root: DockNode): string[]\n```\n\n### `function normalize`\n\nCollapse the tree after edits: drop empty tabs and empty groups, unwrap a\ngroup that has a single child, and flatten a child group into its parent when\nthey share a direction (so repeated docking never nests infinitely deep).\nReturns the tidied node, or null when nothing is left.\n\n```ts\nexport function normalize(node: DockNode): DockNode | null\n```\n\n### `function setActive`\n\nSet the active tab index of a tabs leaf.\n\n```ts\nexport function setActive(root: DockNode, tabsId: string, active: number): DockNode\n```\n\n### `function setSizes`\n\nReplace a group's size weights (e.g. after a splitter drag).\n\n```ts\nexport function setSizes(root: DockNode, groupId: string, sizes: number[]): DockNode\n```\n\n### `function reorderPane`\n\nReorder a pane WITHIN its tabs leaf (dragging a tab along the strip). `active`\nfollows the pane that was showing. No-op if the indices are out of range.\n\n```ts\nexport function reorderPane(root: DockNode, tabsId: string, from: number, to: number): DockNode\n```\n\n### `function removePane`\n\nRemove a pane. Returns the tidied tree (or null if it emptied) plus the pane\nthat was pulled out, so a caller can re-dock it elsewhere.\n\n```ts\nexport function removePane(root: DockNode, paneId: string): { root: DockNode | null; pane: DockPane | null }\n```\n\n### `function dockInto`\n\nDock `movingPane` relative to the leaf `targetTabsId`. `center` adds it as a\ntab; an edge splits: the target is wrapped in (or extended into) a group whose\ndirection matches the edge, with the new pane on the requested side.\n\n```ts\nexport function dockInto(\n root: DockNode,\n targetTabsId: string,\n movingPane: DockPane,\n zone: DockZone,\n genId: IdGen,\n): DockNode\n```\n\n### `function removeLeaf`\n\nPull a whole tabs leaf out of the tree (for auto-hide). Returns the tidied\n tree (or null) plus the extracted leaf.\n\n```ts\nexport function removeLeaf(root: DockNode, tabsId: string): { root: DockNode | null; leaf: DockTabs | null }\n```\n\n### `function dockLeafToEdge`\n\nDock a whole leaf against an EDGE of the entire tree (for pinning an\n auto-hidden panel back in). Wraps the root in a new group as needed; the\n pinned leaf takes `fraction` of that axis (clamped 0.1..0.6), the rest keeps\n the existing content.\n\n```ts\nexport function dockLeafToEdge(\n root: DockNode | null,\n leaf: DockTabs,\n side: Exclude<DockZone, 'center'>,\n genId: IdGen,\n fraction = 0.25,\n): DockNode\n```\n\n### `function movePane`\n\nMove an existing pane to a new dock position (remove then dock).\n\n```ts\nexport function movePane(\n root: DockNode,\n paneId: string,\n targetTabsId: string,\n zone: DockZone,\n genId: IdGen,\n): DockNode\n```\n\n### `function dockPane`\n\nA pane (tab). Alias of `pane`, named for the public builder set.\n\n```ts\nexport function dockPane(\n id: string,\n title: string,\n opts?: boolean | { closable?: boolean; minSize?: number },\n): DockPane\n```\n\n### `function dockTabs`\n\nA tab-leaf holding one or more panes.\n\n```ts\nexport function dockTabs(panes: DockPane[], active = 0): DockTabs\n```\n\n### `function dockGroup`\n\nA row (side-by-side) or column (stacked) of children.\n\n```ts\nexport function dockGroup(\n direction: 'row' | 'column',\n children: DockNode[],\n sizes?: number[],\n): DockGroup\n```\n"
7989
8060
  },
7990
8061
  {
7991
8062
  "slug": "reference/auto/svgrid-grid-duration",
7992
8063
  "path": "docs/reference/auto/svgrid-grid-duration.md",
7993
8064
  "title": "@svgrid/grid · duration.ts",
7994
8065
  "section": "API reference",
7995
- "markdown": "# `@svgrid/grid` · `duration.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\duration.ts`.\n\n### `function parseDuration`\n\nParse a human duration to minutes, or `null` if unparseable. Accepts:\n- `h:mm` e.g. \"1:30\" -> 90\n- unit form e.g. \"1h 30m\", \"1.5h\", \"45m\" -> 90 / 90 / 45\n- a bare number e.g. \"90\" -> 90 (treated as minutes)\n\n```ts\nexport function parseDuration(input: string): number | null {\n const s = input.trim().toLowerCase()\n if (!s) return null\n\n const colon = s.match(/^(\\d+):(\\d{1,2})$/)\n if (colon) {\n const mm = parseInt(colon[2]!, 10)\n if (mm > 59) return null\n return parseInt(colon[1]!, 10) * 60 + mm\n }\n\n const units = s.match(/\\d+(?:\\.\\d+)?\\s*[hm]/g)\n if (units && units.join('').replace(/\\s/g, '').length === s.replace(/\\s/g, '').length) {\n let total = 0\n for (const part of units) {\n const m = part.match(/(\\d+(?:\\.\\d+)?)\\s*([hm])/)!\n const n = parseFloat(m[1]!)\n total += m[2] === 'h' ? n * 60 : n\n }\n return Math.round(total)\n }\n\n const num = Number(s)\n return Number.isFinite(num) ? Math.round(num) : null\n}\n```\n\n### `function formatDuration`\n\nFormat minutes as `h:mm` (colon) or `Nh Nm` (units). Empty for invalid input.\n\n```ts\nexport function formatDuration(minutes: number, style: 'colon' | 'units' = 'colon'): string {\n if (!Number.isFinite(minutes) || minutes < 0) return ''\n const h = Math.floor(minutes / 60)\n const m = Math.round(minutes % 60)\n if (style === 'units') {\n if (h && m) return `${h}h ${m}m`\n if (h) return `${h}h`\n return `${m}m`\n }\n return `${h}:${String(m).padStart(2, '0')}`\n}\n```\n"
8066
+ "markdown": "# `@svgrid/grid` · `duration.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\duration.ts`.\n\n### `function parseDuration`\n\nParse a human duration to minutes, or `null` if unparseable. Accepts:\n- `h:mm` e.g. \"1:30\" -> 90\n- unit form e.g. \"1h 30m\", \"1.5h\", \"45m\" -> 90 / 90 / 45\n- a bare number e.g. \"90\" -> 90 (treated as minutes)\n\n```ts\nexport function parseDuration(input: string): number | null\n```\n\n### `function formatDuration`\n\nFormat minutes as `h:mm` (colon) or `Nh Nm` (units). Empty for invalid input.\n\n```ts\nexport function formatDuration(minutes: number, style: 'colon' | 'units' = 'colon'): string\n```\n"
7996
8067
  },
7997
8068
  {
7998
8069
  "slug": "reference/auto/svgrid-grid-editor-contract",
7999
8070
  "path": "docs/reference/auto/svgrid-grid-editor-contract.md",
8000
8071
  "title": "@svgrid/grid · editor-contract.ts",
8001
8072
  "section": "API reference",
8002
- "markdown": "# `@svgrid/grid` · `editor-contract.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\editor-contract.ts`.\n\n### `type EditorSize`\n\nHow much room a cell editor asks for, so the grid can size its overlay.\n\n```ts\nexport type EditorSize = 'sm' | 'md' | 'lg'\n```\n\n### `type EditorAction`\n\nA small action button rendered inside a framed field (via `SvField`'s\n`actions`) - the generalized form of the clear / reveal buttons, for a lookup,\na generate, a copy, etc. `icon` is a Svelte snippet; when absent the `label`\ntext is shown. (Type-only Svelte import, so this module stays runtime-free.)\n\n```ts\nexport type EditorAction = {\n /** Accessible name + tooltip for the button. */\n label: string\n /** Invoked when the button is pressed. */\n onClick: () => void\n /** Optional icon snippet; falls back to the `label` text. */\n icon?: import('svelte').Snippet\n disabled?: boolean\n}\n```\n\n### `type EditorDir`\n\nText direction. `'auto'` defers to the surrounding document/CSS.\n\n```ts\nexport type EditorDir = 'ltr' | 'rtl' | 'auto'\n```\n\n### `type SvEditorProps`\n\nProps shared by every value-bearing editor in the kit.\n\n```ts\nexport type SvEditorProps = {\n /** Disable interaction + form submission. */\n disabled?: boolean\n /** Read-only: the value is shown but not editable. */\n readonly?: boolean\n /** Required for validation (adds `aria-required` + participates in validity). */\n required?: boolean\n /** Marks the control invalid (`aria-invalid` + error styling). */\n invalid?: boolean\n /**\n * Fill the container instead of the control's own default width. A default\n * width is right for a control sitting on its own; in a form grid a row of\n * inputs each stopping at a different width reads as broken.\n */\n block?: boolean\n /** Error message; when set it is announced via `aria-describedby` and shown. */\n error?: string\n /** Visible field label, rendered above the control and wired via `for`/`id`. */\n label?: string\n /** Helper text shown under the control and announced via `aria-describedby`. */\n hint?: string\n /** Control size / density. */\n size?: EditorSize\n /**\n * Text direction. `'rtl'` mirrors layout for Arabic/Hebrew/etc.; `'auto'` (the\n * default) inherits from the surrounding document so a page-level `dir` wins.\n */\n dir?: EditorDir\n /** Form field name; the editor emits a hidden input carrying its value. */\n name?: string\n /** Root/control element id (the label/hint/error ids derive from it). */\n id?: string\n /** Accessible name when there is no visible `label`. */\n ariaLabel?: string\n /** Busy state - shows a spinner (e.g. while an async value/validation resolves). */\n loading?: boolean\n}\n```\n\n### `type EditorInteraction`\n\nThe interaction surface an editor exposes when embedded as a grid cell editor.\nStandalone usage ignores these; the grid supplies them so every editor shares\none commit / cancel / move contract (Enter commits, Escape cancels, Tab moves)\ninstead of each cell-editor re-implementing key handling.\n\n`CellEditorContext` (editor-registry.ts) extends this type, so what the grid\nhands a registered editor and what this contract promises are the same thing\nby construction rather than by convention.\n\n```ts\nexport type EditorInteraction<V = unknown> = {\n /**\n * Commit the value and stop editing (Enter, option pick, blur-commit).\n * The argument is optional: an editor that has been reporting through\n * `onChange` can just call `onCommit()` to commit what the grid already has.\n */\n onCommit?: (value?: V) => void\n /** Abandon the edit and restore the previous value (Escape). */\n onCancel?: () => void\n /** Commit, then move to the adjacent cell (Tab = 1, Shift+Tab = -1). */\n onCommitAndMove?: (value: V | undefined, direction: 1 | -1) => void\n /** Ask the surrounding popover/panel to close without committing. */\n onRequestClose?: () => void\n /** True while mounted inside a grid cell (lets an editor tune autofocus etc.). */\n inCell?: boolean\n}\n```\n\n### `const editorErrorId`\n\nStable DOM id for an editor's error text, for `aria-describedby` wiring.\n\n```ts\nexport const editorErrorId = (id?: string): string | undefined => (id ? `${id}__error` : undefined)\n```\n\n### `const editorHintId`\n\nStable DOM id for an editor's hint text, for `aria-describedby` wiring.\n\n```ts\nexport const editorHintId = (id?: string): string | undefined => (id ? `${id}__hint` : undefined)\n```\n\n### `const nextEditorId`\n\nGenerate a stable-per-instance element id. Call ONCE per component instance\n(e.g. `const uid = provided ?? nextEditorId()`) so label/hint/error wiring\nalways has an anchor even when the consumer passes no `id`.\n\n```ts\nexport const nextEditorId = (prefix = 'sv-ed'): string => `${prefix}-${_autoId++}`\n```\n\n### `type EditorAriaState`\n\nA subset of {@link SvEditorProps} that drives ARIA on the focusable control.\n\n```ts\nexport type EditorAriaState = Pick<\n SvEditorProps,\n 'id' | 'invalid' | 'required' | 'error' | 'hint' | 'ariaLabel'\n```\n\n### `function editorAria`\n\nARIA attributes for the focusable control of an editor, derived from its state.\nSpread onto the input/button/combobox:\n`<input {...editorAria({ id, invalid, required, error, hint, ariaLabel })} />`\n\n`aria-describedby` points at the error text (when invalid) and/or the hint\ntext - both ids derive from `id`, so pass a stable `id` (see {@link nextEditorId}).\nUndefined values are omitted by Svelte, so unset props add no attributes.\n\n```ts\nexport function editorAria(state: EditorAriaState): {\n 'aria-invalid': 'true' | undefined\n 'aria-required': 'true' | undefined\n 'aria-describedby': string | undefined\n 'aria-label': string | undefined\n} {\n const described = [\n state.error ? editorErrorId(state.id) : undefined,\n state.hint ? editorHintId(state.id) : undefined,\n ].filter(Boolean)\n return {\n 'aria-invalid': state.invalid ? 'true' : undefined,\n 'aria-required': state.required ? 'true' : undefined,\n 'aria-describedby': described.length ? described.join(' ') : undefined,\n 'aria-label': state.ariaLabel,\n }\n}\n```\n\n### `function resolveMessages`\n\nMerge a component's default message strings with a consumer's `messages`\noverride, so every editor can be fully localized from the outside.\n\n```ts\nconst M = { clear: 'Clear', noResults: 'No results' }\nconst messages = resolveMessages(M, props.messages) // Partial override\n```\n\nUndefined/empty overrides fall back to the default, so a partial `messages`\nobject only replaces the keys it sets.\n\n```ts\nexport function resolveMessages<T extends Record<string, string>>(\n defaults: T,\n overrides?: Partial<T> | null,\n): T {\n if (!overrides) return defaults\n const out = { ...defaults }\n for (const k in overrides) {\n const v = overrides[k]\n if (v != null && v !== '') out[k] = v as T[Extract<keyof T, string>]\n }\n return out\n}\n```\n"
8073
+ "markdown": "# `@svgrid/grid` · `editor-contract.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\editor-contract.ts`.\n\n### `type EditorSize`\n\nHow much room a cell editor asks for, so the grid can size its overlay.\n\n```ts\nexport type EditorSize = 'sm' | 'md' | 'lg'\n```\n\n### `type EditorAction`\n\nA small action button rendered inside a framed field (via `SvField`'s\n`actions`) - the generalized form of the clear / reveal buttons, for a lookup,\na generate, a copy, etc. `icon` is a Svelte snippet; when absent the `label`\ntext is shown. (Type-only Svelte import, so this module stays runtime-free.)\n\n```ts\nexport type EditorAction = {\n /** Accessible name + tooltip for the button. */\n label: string\n /** Invoked when the button is pressed. */\n onClick: () => void\n /** Optional icon snippet; falls back to the `label` text. */\n icon?: import('svelte').Snippet\n disabled?: boolean\n}\n```\n\n### `type EditorDir`\n\nText direction. `'auto'` defers to the surrounding document/CSS.\n\n```ts\nexport type EditorDir = 'ltr' | 'rtl' | 'auto'\n```\n\n### `type SvEditorProps`\n\nProps shared by every value-bearing editor in the kit.\n\n```ts\nexport type SvEditorProps = {\n /** Disable interaction + form submission. */\n disabled?: boolean\n /** Read-only: the value is shown but not editable. */\n readonly?: boolean\n /** Required for validation (adds `aria-required` + participates in validity). */\n required?: boolean\n /** Marks the control invalid (`aria-invalid` + error styling). */\n invalid?: boolean\n /**\n * Fill the container instead of the control's own default width. A default\n * width is right for a control sitting on its own; in a form grid a row of\n * inputs each stopping at a different width reads as broken.\n */\n block?: boolean\n /** Error message; when set it is announced via `aria-describedby` and shown. */\n error?: string\n /** Visible field label, rendered above the control and wired via `for`/`id`. */\n label?: string\n /** Helper text shown under the control and announced via `aria-describedby`. */\n hint?: string\n /** Control size / density. */\n size?: EditorSize\n /**\n * Text direction. `'rtl'` mirrors layout for Arabic/Hebrew/etc.; `'auto'` (the\n * default) inherits from the surrounding document so a page-level `dir` wins.\n */\n dir?: EditorDir\n /** Form field name; the editor emits a hidden input carrying its value. */\n name?: string\n /** Root/control element id (the label/hint/error ids derive from it). */\n id?: string\n /** Accessible name when there is no visible `label`. */\n ariaLabel?: string\n /** Busy state - shows a spinner (e.g. while an async value/validation resolves). */\n loading?: boolean\n}\n```\n\n### `type EditorInteraction`\n\nThe interaction surface an editor exposes when embedded as a grid cell editor.\nStandalone usage ignores these; the grid supplies them so every editor shares\none commit / cancel / move contract (Enter commits, Escape cancels, Tab moves)\ninstead of each cell-editor re-implementing key handling.\n\n`CellEditorContext` (editor-registry.ts) extends this type, so what the grid\nhands a registered editor and what this contract promises are the same thing\nby construction rather than by convention.\n\n```ts\nexport type EditorInteraction<V = unknown> = {\n /**\n * Commit the value and stop editing (Enter, option pick, blur-commit).\n * The argument is optional: an editor that has been reporting through\n * `onChange` can just call `onCommit()` to commit what the grid already has.\n */\n onCommit?: (value?: V) => void\n /** Abandon the edit and restore the previous value (Escape). */\n onCancel?: () => void\n /** Commit, then move to the adjacent cell (Tab = 1, Shift+Tab = -1). */\n onCommitAndMove?: (value: V | undefined, direction: 1 | -1) => void\n /** Ask the surrounding popover/panel to close without committing. */\n onRequestClose?: () => void\n /** True while mounted inside a grid cell (lets an editor tune autofocus etc.). */\n inCell?: boolean\n}\n```\n\n### `const editorErrorId`\n\nStable DOM id for an editor's error text, for `aria-describedby` wiring.\n\n```ts\nexport const editorErrorId = (id?: string): string | undefined => ...\n```\n\n### `const editorHintId`\n\nStable DOM id for an editor's hint text, for `aria-describedby` wiring.\n\n```ts\nexport const editorHintId = (id?: string): string | undefined => ...\n```\n\n### `const nextEditorId`\n\nGenerate a stable-per-instance element id. Call ONCE per component instance\n(e.g. `const uid = provided ?? nextEditorId()`) so label/hint/error wiring\nalways has an anchor even when the consumer passes no `id`.\n\n```ts\nexport const nextEditorId = (prefix = 'sv-ed'): string => ...\n```\n\n### `type EditorAriaState`\n\nA subset of {@link SvEditorProps} that drives ARIA on the focusable control.\n\n```ts\nexport type EditorAriaState = Pick<\n SvEditorProps,\n 'id' | 'invalid' | 'required' | 'error' | 'hint' | 'ariaLabel'\n```\n\n### `function editorAria`\n\nARIA attributes for the focusable control of an editor, derived from its state.\nSpread onto the input/button/combobox:\n`<input {...editorAria({ id, invalid, required, error, hint, ariaLabel })} />`\n\n`aria-describedby` points at the error text (when invalid) and/or the hint\ntext - both ids derive from `id`, so pass a stable `id` (see {@link nextEditorId}).\nUndefined values are omitted by Svelte, so unset props add no attributes.\n\n```ts\nexport function editorAria(state: EditorAriaState): {\n 'aria-invalid': 'true' | undefined\n 'aria-required': 'true' | undefined\n 'aria-describedby': string | undefined\n 'aria-label': string | undefined\n}\n```\n\n### `function resolveMessages`\n\nMerge a component's default message strings with a consumer's `messages`\noverride, so every editor can be fully localized from the outside.\n\n```ts\nconst M = { clear: 'Clear', noResults: 'No results' }\nconst messages = resolveMessages(M, props.messages) // Partial override\n```\n\nUndefined/empty overrides fall back to the default, so a partial `messages`\nobject only replaces the keys it sets.\n\n```ts\nexport function resolveMessages<T extends Record<string, string>>(\n defaults: T,\n overrides?: Partial<T> | null,\n): T\n```\n"
8003
8074
  },
8004
8075
  {
8005
8076
  "slug": "reference/auto/svgrid-grid-editor-registry",
8006
8077
  "path": "docs/reference/auto/svgrid-grid-editor-registry.md",
8007
8078
  "title": "@svgrid/grid · editor-registry.ts",
8008
8079
  "section": "API reference",
8009
- "markdown": "# `@svgrid/grid` · `editor-registry.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\editor-registry.ts`.\n\n### `type CellEditorContext`\n\nContext the grid hands a cell editor when it mounts one for an edit.\n\nExtends {@link EditorInteraction} - the shared commit / cancel / move contract\nthe `Sv*` editors are written against - and narrows the parts the grid always\nsupplies, so a registered component and a built-in editor speak the same\nlanguage. `onCommitAndMove`, `onRequestClose` and `inCell` come from the\ncontract and are always populated by the grid.\n\n```ts\nexport type CellEditorContext<T = unknown> = Required<\n Pick<EditorInteraction<T>, 'onCommit' | 'onCancel' | 'onCommitAndMove' | 'onRequestClose' | 'inCell'>\n```\n\n### `type CellEditorRegistration`\n\nHow a registered component is mounted and wired for a cell edit.\n\n```ts\nexport type CellEditorRegistration = {\n /** The Svelte component to mount in the editing cell. */\n component: Component<any>\n /**\n * Map the editing context to the component's props. Defaults to\n * {@link defaultEditorProps} (value + onChange/onCommit/onCancel).\n */\n props?: (ctx: CellEditorContext) => Record<string, unknown>\n /** Hint that the editor should open its popover immediately on mount. */\n autoOpen?: boolean\n /**\n * Whether typing on a selected cell starts this editor with the typed\n * character (`typed: true` on the context). A function decides per key,\n * e.g. digits only for a number editor. Default: every printable key.\n */\n typeToEdit?: boolean | ((char: string) => boolean)\n}\n```\n\n### `function registerCellEditor`\n\nRegister a cell editor under `type`. Pass a component (uses the default prop\nmapping) or a full {@link CellEditorRegistration} for custom prop mapping.\nRe-registering the same type replaces it.\n\n```ts\nexport function registerCellEditor(\n type: string,\n registration: CellEditorRegistration | Component<any>,\n): void {\n registry.set(\n type,\n typeof registration === 'function' ? { component: registration } : registration,\n )\n}\n```\n\n### `function getCellEditor`\n\nLook up a registered cell editor by type.\n\n```ts\nexport function getCellEditor(type: string): CellEditorRegistration | undefined {\n return registry.get(type)\n}\n```\n\n### `function hasCellEditor`\n\nWhether a custom editor is registered for `type`.\n\n```ts\nexport function hasCellEditor(type: string): boolean {\n return registry.has(type)\n}\n```\n\n### `function unregisterCellEditor`\n\nRemove a registered cell editor.\n\n```ts\nexport function unregisterCellEditor(type: string): void {\n registry.delete(type)\n}\n```\n\n### `function registeredCellEditorTypes`\n\nAll registered custom editor type names.\n\n```ts\nexport function registeredCellEditorTypes(): string[] {\n return [...registry.keys()]\n}\n```\n\n### `function defaultEditorProps`\n\nThe default context → props mapping used when a registration has no `props`.\nPasses the whole {@link EditorInteraction} surface, so an editor written\nagainst the shared contract works when registered with no mapping at all.\nSvelte ignores props a component doesn't declare, so the extra keys are inert\nfor a simple editor that only wants `value` + `onCommit`.\n\n```ts\nexport function defaultEditorProps(ctx: CellEditorContext): Record<string, unknown> {\n return {\n value: ctx.value,\n onChange: ctx.onChange,\n onCommit: ctx.onCommit,\n onCancel: ctx.onCancel,\n onCommitAndMove: ctx.onCommitAndMove,\n onRequestClose: ctx.onRequestClose,\n inCell: ctx.inCell,\n }\n}\n```\n\n### `function resolveEditorProps`\n\nResolve the props to spread onto a registered editor for a given context.\n\n```ts\nexport function resolveEditorProps(\n registration: CellEditorRegistration,\n ctx: CellEditorContext,\n): Record<string, unknown> {\n return registration.props ? registration.props(ctx) : defaultEditorProps(ctx)\n}\n```\n"
8080
+ "markdown": "# `@svgrid/grid` · `editor-registry.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\editor-registry.ts`.\n\n### `type CellEditorContext`\n\nContext the grid hands a cell editor when it mounts one for an edit.\n\nExtends {@link EditorInteraction} - the shared commit / cancel / move contract\nthe `Sv*` editors are written against - and narrows the parts the grid always\nsupplies, so a registered component and a built-in editor speak the same\nlanguage. `onCommitAndMove`, `onRequestClose` and `inCell` come from the\ncontract and are always populated by the grid.\n\n```ts\nexport type CellEditorContext<T = unknown> = Required<\n Pick<EditorInteraction<T>, 'onCommit' | 'onCancel' | 'onCommitAndMove' | 'onRequestClose' | 'inCell'>\n```\n\n### `type CellEditorRegistration`\n\nHow a registered component is mounted and wired for a cell edit.\n\n```ts\nexport type CellEditorRegistration = {\n /** The Svelte component to mount in the editing cell. */\n component: Component<any>\n /**\n * Map the editing context to the component's props. Defaults to\n * {@link defaultEditorProps} (value + onChange/onCommit/onCancel).\n */\n props?: (ctx: CellEditorContext) => Record<string, unknown>\n /** Hint that the editor should open its popover immediately on mount. */\n autoOpen?: boolean\n /**\n * Whether typing on a selected cell starts this editor with the typed\n * character (`typed: true` on the context). A function decides per key,\n * e.g. digits only for a number editor. Default: every printable key.\n */\n typeToEdit?: boolean | ((char: string) => boolean)\n}\n```\n\n### `function registerCellEditor`\n\nRegister a cell editor under `type`. Pass a component (uses the default prop\nmapping) or a full {@link CellEditorRegistration} for custom prop mapping.\nRe-registering the same type replaces it.\n\n```ts\nexport function registerCellEditor(\n type: string,\n registration: CellEditorRegistration | Component<any>,\n): void\n```\n\n### `function getCellEditor`\n\nLook up a registered cell editor by type.\n\n```ts\nexport function getCellEditor(type: string): CellEditorRegistration | undefined\n```\n\n### `function hasCellEditor`\n\nWhether a custom editor is registered for `type`.\n\n```ts\nexport function hasCellEditor(type: string): boolean\n```\n\n### `function unregisterCellEditor`\n\nRemove a registered cell editor.\n\n```ts\nexport function unregisterCellEditor(type: string): void\n```\n\n### `function registeredCellEditorTypes`\n\nAll registered custom editor type names.\n\n```ts\nexport function registeredCellEditorTypes(): string[]\n```\n\n### `function defaultEditorProps`\n\nThe default context → props mapping used when a registration has no `props`.\nPasses the whole {@link EditorInteraction} surface, so an editor written\nagainst the shared contract works when registered with no mapping at all.\nSvelte ignores props a component doesn't declare, so the extra keys are inert\nfor a simple editor that only wants `value` + `onCommit`.\n\n```ts\nexport function defaultEditorProps(ctx: CellEditorContext): Record<string, unknown>\n```\n\n### `function resolveEditorProps`\n\nResolve the props to spread onto a registered editor for a given context.\n\n```ts\nexport function resolveEditorProps(\n registration: CellEditorRegistration,\n ctx: CellEditorContext,\n): Record<string, unknown>\n```\n"
8010
8081
  },
8011
8082
  {
8012
8083
  "slug": "reference/auto/svgrid-grid-filter-operator-catalogue",
8013
8084
  "path": "docs/reference/auto/svgrid-grid-filter-operator-catalogue.md",
8014
8085
  "title": "@svgrid/grid · filtering/filter-operator-catalogue.ts",
8015
8086
  "section": "API reference",
8016
- "markdown": "# `@svgrid/grid` · `filtering/filter-operator-catalogue.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\filtering\\filter-operator-catalogue.ts`.\n\n### `type FilterValueType`\n\nCoarse value type used to decide which operators a column offers.\n\n```ts\nexport type FilterValueType = 'text' | 'number' | 'date' | 'datetime' | 'boolean'\n```\n\n### `const ALL_FILTER_OPERATORS`\n\nEvery filter operator, in the grid's filter-menu order. Any surface that\npresents operators should be able to account for all of these.\n\n```ts\nexport const ALL_FILTER_OPERATORS: ReadonlyArray<ExcelFilterOperator> = [\n 'contains',\n 'notContains',\n 'equals',\n 'notEquals',\n 'startsWith',\n 'endsWith',\n 'regex',\n 'in',\n 'notIn',\n 'greaterThan',\n 'lessThan',\n 'between',\n 'isBlank',\n 'isNotBlank',\n]\n```\n\n### `const SET_OPERATOR_IDS`\n\nOperators whose predicate is a set-membership test over a token list.\n A filter UI renders a multi-value chip input for these.\n\n```ts\nexport const SET_OPERATOR_IDS: ReadonlyArray<ExcelFilterOperator> = ['in', 'notIn']\n```\n\n### `const VALUELESS_OPERATOR_IDS`\n\nOperators that need no value input - they act on emptiness alone.\n\n```ts\nexport const VALUELESS_OPERATOR_IDS: ReadonlyArray<ExcelFilterOperator> = [\n 'isBlank',\n 'isNotBlank',\n]\n```\n\n### `const RANGE_OPERATOR_IDS`\n\nOperators that need a second value (`valueTo`).\n\n```ts\nexport const RANGE_OPERATOR_IDS: ReadonlyArray<ExcelFilterOperator> = ['between']\n```\n\n### `function isSetOperator`\n\nWhether an operator takes a multi-value token list.\n\n```ts\nexport function isSetOperator(op: ExcelFilterOperator): boolean {\n return SET_OPERATOR_IDS.includes(op)\n}\n```\n\n### `function isValuelessOperator`\n\nWhether an operator needs no value input.\n\n```ts\nexport function isValuelessOperator(op: ExcelFilterOperator): boolean {\n return VALUELESS_OPERATOR_IDS.includes(op)\n}\n```\n\n### `function isRangeOperator`\n\nWhether an operator needs a second (`valueTo`) value.\n\n```ts\nexport function isRangeOperator(op: ExcelFilterOperator): boolean {\n return RANGE_OPERATOR_IDS.includes(op)\n}\n```\n"
8087
+ "markdown": "# `@svgrid/grid` · `filtering/filter-operator-catalogue.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\filtering\\filter-operator-catalogue.ts`.\n\n### `type FilterValueType`\n\nCoarse value type used to decide which operators a column offers.\n\n```ts\nexport type FilterValueType = 'text' | 'number' | 'date' | 'datetime' | 'boolean'\n```\n\n### `const ALL_FILTER_OPERATORS`\n\nEvery filter operator, in the grid's filter-menu order. Any surface that\npresents operators should be able to account for all of these.\n\n```ts\nexport const ALL_FILTER_OPERATORS: ReadonlyArray<ExcelFilterOperator> = [\n 'contains',\n 'notContains',\n 'equals',\n 'notEquals',\n 'startsWith',\n 'endsWith',\n 'regex',\n 'in',\n 'notIn',\n 'greaterThan',\n 'lessThan',\n 'between',\n 'isBlank',\n 'isNotBlank',\n]\n```\n\n### `const SET_OPERATOR_IDS`\n\nOperators whose predicate is a set-membership test over a token list.\n A filter UI renders a multi-value chip input for these.\n\n```ts\nexport const SET_OPERATOR_IDS: ReadonlyArray<ExcelFilterOperator> = ['in', 'notIn']\n```\n\n### `const VALUELESS_OPERATOR_IDS`\n\nOperators that need no value input - they act on emptiness alone.\n\n```ts\nexport const VALUELESS_OPERATOR_IDS: ReadonlyArray<ExcelFilterOperator> = [\n 'isBlank',\n 'isNotBlank',\n]\n```\n\n### `const RANGE_OPERATOR_IDS`\n\nOperators that need a second value (`valueTo`).\n\n```ts\nexport const RANGE_OPERATOR_IDS: ReadonlyArray<ExcelFilterOperator> = ['between']\n```\n\n### `function isSetOperator`\n\nWhether an operator takes a multi-value token list.\n\n```ts\nexport function isSetOperator(op: ExcelFilterOperator): boolean\n```\n\n### `function isValuelessOperator`\n\nWhether an operator needs no value input.\n\n```ts\nexport function isValuelessOperator(op: ExcelFilterOperator): boolean\n```\n\n### `function isRangeOperator`\n\nWhether an operator needs a second (`valueTo`) value.\n\n```ts\nexport function isRangeOperator(op: ExcelFilterOperator): boolean\n```\n"
8017
8088
  },
8018
8089
  {
8019
8090
  "slug": "reference/auto/svgrid-grid-grid-icons",
@@ -8027,98 +8098,98 @@ export const docs = [
8027
8098
  "path": "docs/reference/auto/svgrid-grid-grid-messages.md",
8028
8099
  "title": "@svgrid/grid · grid-messages.ts",
8029
8100
  "section": "API reference",
8030
- "markdown": "# `@svgrid/grid` · `grid-messages.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\grid-messages.ts`.\n\n### `type GridMessages`\n\nEvery string `localization.text` accepts: the grid chrome's own\n({@link GridChromeMessages}) and the chart panel's\n({@link GridChartPanelMessages}).\n\n```ts\nexport type GridMessages = GridChromeMessages & GridChartPanelMessages\n```\n\n### `type GridChromeMessages`\n\nEvery localizable chrome string, grouped by area in the comments.\n\n```ts\nexport type GridChromeMessages = {\n // Empty / loading state\n noRows: string\n /** The empty state when a filter is what emptied the grid. */\n noRowsFiltered: string\n /** The button in that empty state that clears every filter. */\n clearFilters: string\n loading: string\n // Tool panel\n columns: string\n filters: string\n clearFilter: string\n // Pagination\n pageSize: string\n page: string\n of: string\n firstPage: string\n prevPage: string\n nextPage: string\n lastPage: string\n // Status bar aggregate labels\n statCount: string\n statSum: string\n statAvg: string\n statMin: string\n statMax: string\n // Grouping chrome\n group: string\n grandTotal: string\n total: string\n rowsSuffix: string\n rowSuffix: string\n // Screen-reader announcements. Unlike the labels above these are whole\n // sentences, so they take `{placeholders}` - a translator needs to control\n // word order, which assembling atoms in English order does not allow.\n announceFilterResults: string\n announceNoMatches: string\n announceFiltersCleared: string\n announceRowsSelected: string\n announceSelectionCleared: string\n // Advanced-filter toolbar chip\n advancedFilterActive: string\n advancedFilterClear: string\n // Filter operator labels (mirror filterOperatorOptions ids)\n opContains: string\n opNotContains: string\n opEquals: string\n opNotEquals: string\n opStartsWith: string\n opEndsWith: string\n opRegex: string\n opIn: string\n opNotIn: string\n opGreaterThan: string\n opLessThan: string\n opBetween: string\n opIsBlank: string\n opIsNotBlank: string\n // Date-column relabels for less/greater than\n opBefore: string\n opAfter: string\n // Context menu\n menuCopy: string\n menuCut: string\n menuPaste: string\n menuClear: string\n menuInsertRowAbove: string\n menuInsertRowBelow: string\n menuRemoveRow: string\n menuRemoveColumn: string\n menuEditComment: string\n // Selection bar\n selectionBarLabel: string\n selectionBarCount: string\n selectionBarClear: string\n selectionBarMore: string\n selectionBarSelectAll: string\n selectionBarEditFields: string\n selectionBarDelete: string\n /** `{count}` is the number of selected rows. */\n selectionBarDeleteConfirm: string\n selectionBarCancel: string\n // Pin splitter (`pinSplitter`)\n pinSplitterLabel: string\n pinSplitterHint: string\n pinSplitterNone: string\n pinSplitterOne: string\n /** `{count}` is the number of pinned columns. */\n pinSplitterMany: string\n // Bulk edit dialog\n bulkEditTitle: string\n bulkEditLead: string\n bulkEditMixed: string\n bulkEditApply: string\n bulkEditCancel: string\n bulkEditNoFields: string\n chartRange: string\n // Rows whose data has not arrived (server-side / infinite loading)\n rowLoadFailed: string\n rowLoadRetry: string\n // The expander on a client-side group row\n expandGroup: string\n collapseGroup: string\n // The chevron of the detail-toggle column (`showDetailToggle`)\n openDetail: string\n closeDetail: string\n // Upsell notes (enterprise views not installed)\n pivotUpsellTitle: string\n pivotUpsellBody: string\n ganttUpsellTitle: string\n ganttUpsellBody: string\n /** Placeholder in the Gantt view's search box. */\n ganttSearchPlaceholder: string\n /** Shared licensing line under every Enterprise upsell note. */\n upsellLicense: string\n upsellLicenseLink: string\n}\n```\n\n### `const defaultGridMessages`\n\nEnglish defaults - the literal strings the grid shipped before localization.\n\n```ts\nexport const defaultGridMessages: GridChromeMessages = {\n noRows: 'No rows to display.',\n noRowsFiltered: 'No rows match the current filters.',\n clearFilters: 'Clear filters',\n loading: 'Loading grid data...',\n columns: 'Columns',\n filters: 'Filters',\n clearFilter: 'Clear filter',\n pageSize: 'Page Size:',\n page: 'Page',\n of: 'of',\n firstPage: 'First page',\n prevPage: 'Previous page',\n nextPage: 'Next page',\n lastPage: 'Last page',\n statCount: 'Count',\n statSum: 'Sum',\n statAvg: 'Avg',\n statMin: 'Min',\n statMax: 'Max',\n group: 'Group',\n grandTotal: 'Grand total',\n total: 'Total',\n rowsSuffix: 'rows',\n rowSuffix: 'row',\n announceFilterResults: '{visible} of {total} rows match the current filters',\n announceNoMatches: 'No rows match the current filters',\n announceFiltersCleared: 'Filters cleared, showing all {total} rows',\n announceRowsSelected: '{count} rows selected',\n announceSelectionCleared: 'Selection cleared',\n advancedFilterActive: 'Advanced filter',\n advancedFilterClear: 'Clear advanced filter',\n menuCopy: 'Copy',\n menuCut: 'Cut',\n menuPaste: 'Paste',\n menuClear: 'Clear',\n menuInsertRowAbove: 'Insert row above',\n menuInsertRowBelow: 'Insert row below',\n menuRemoveRow: 'Remove row',\n menuRemoveColumn: 'Remove column',\n menuEditComment: 'Edit comment',\n selectionBarLabel: 'Selection actions',\n /** Label beside the count CHIP, which carries the number itself. */\n selectionBarCount: 'selected',\n selectionBarClear: 'Clear selection',\n selectionBarMore: 'More actions',\n selectionBarSelectAll: 'Select all',\n selectionBarEditFields: 'Edit fields',\n selectionBarDelete: 'Delete',\n selectionBarDeleteConfirm: 'Delete {count} rows?',\n selectionBarCancel: 'Cancel',\n pinSplitterLabel: 'Pinned columns',\n pinSplitterHint: 'Drag to pin or unpin columns',\n pinSplitterNone: 'No pinned columns',\n pinSplitterOne: '1 pinned column',\n pinSplitterMany: '{count} pinned columns',\n bulkEditTitle: 'Edit fields',\n bulkEditLead:\n 'Changes apply to all {count} selected items. Fields you leave alone keep their existing values.',\n bulkEditMixed: 'Multiple values',\n bulkEditApply: 'Apply to {count} items',\n bulkEditCancel: 'Cancel',\n bulkEditNoFields: 'No editable fields on this grid.',\n opContains: 'Contains',\n opNotContains: 'Not contains',\n opEquals: 'Equals',\n opNotEquals: 'Not equals',\n opStartsWith: 'Starts with',\n opEndsWith: 'Ends with',\n opRegex: 'Regex',\n opIn: 'In',\n opNotIn: 'Not in',\n opGreaterThan: 'Greater than',\n opLessThan: 'Less than',\n opBetween: 'Between',\n opIsBlank: 'Blank',\n opIsNotBlank: 'Not blank',\n opBefore: 'Before',\n opAfter: 'After',\n chartRange: 'Chart selected range',\n rowLoadFailed: 'Could not load these rows.',\n rowLoadRetry: 'Retry',\n expandGroup: 'Expand group',\n collapseGroup: 'Collapse group',\n openDetail: 'Open details',\n closeDetail: 'Close details',\n pivotUpsellTitle: 'Pivot mode',\n pivotUpsellBody: 'Pivot mode is an Enterprise feature. Install @svgrid/enterprise and call enablePivot() to use it.',\n ganttUpsellTitle: 'Gantt view',\n ganttUpsellBody: 'The Gantt view is an Enterprise feature. Install @svgrid/enterprise and call enableGanttView() to render it.',\n ganttSearchPlaceholder: 'Search tasks...',\n upsellLicense:\n 'A license key is required for production use. Without one the feature still works, but the grid renders an unlicensed watermark.',\n upsellLicenseLink: 'View licensing',\n}\n```\n\n### `function resolveGridMessages`\n\nMerge a consumer's `localeText` over the English defaults. Undefined/empty\nvalues fall back to the default (via `resolveMessages`), so a partial map only\nreplaces the keys it sets.\n\n```ts\nexport function resolveGridMessages(overrides?: Partial<GridMessages> | null): GridChromeMessages {\n return resolveMessages(defaultGridMessages, overrides)\n}\n```\n"
8101
+ "markdown": "# `@svgrid/grid` · `grid-messages.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\grid-messages.ts`.\n\n### `type GridMessages`\n\nEvery string `localization.text` accepts: the grid chrome's own\n({@link GridChromeMessages}) and the chart panel's\n({@link GridChartPanelMessages}).\n\n```ts\nexport type GridMessages = GridChromeMessages & GridChartPanelMessages\n```\n\n### `type GridChromeMessages`\n\nEvery localizable chrome string, grouped by area in the comments.\n\n```ts\nexport type GridChromeMessages = {\n // Empty / loading state\n noRows: string\n /** The empty state when a filter is what emptied the grid. */\n noRowsFiltered: string\n /** The button in that empty state that clears every filter. */\n clearFilters: string\n loading: string\n // Tool panel\n columns: string\n filters: string\n clearFilter: string\n // Pagination\n pageSize: string\n page: string\n of: string\n firstPage: string\n prevPage: string\n nextPage: string\n lastPage: string\n // Status bar aggregate labels\n statCount: string\n statSum: string\n statAvg: string\n statMin: string\n statMax: string\n // Grouping chrome\n group: string\n grandTotal: string\n total: string\n rowsSuffix: string\n rowSuffix: string\n // Screen-reader announcements. Unlike the labels above these are whole\n // sentences, so they take `{placeholders}` - a translator needs to control\n // word order, which assembling atoms in English order does not allow.\n announceFilterResults: string\n announceNoMatches: string\n announceFiltersCleared: string\n announceRowsSelected: string\n announceSelectionCleared: string\n // Advanced-filter toolbar chip\n advancedFilterActive: string\n advancedFilterClear: string\n // Filter operator labels (mirror filterOperatorOptions ids)\n opContains: string\n opNotContains: string\n opEquals: string\n opNotEquals: string\n opStartsWith: string\n opEndsWith: string\n opRegex: string\n opIn: string\n opNotIn: string\n opGreaterThan: string\n opLessThan: string\n opBetween: string\n opIsBlank: string\n opIsNotBlank: string\n // Date-column relabels for less/greater than\n opBefore: string\n opAfter: string\n // Context menu\n menuCopy: string\n menuCut: string\n menuPaste: string\n menuClear: string\n menuInsertRowAbove: string\n menuInsertRowBelow: string\n menuRemoveRow: string\n menuRemoveColumn: string\n menuEditComment: string\n // Selection bar\n selectionBarLabel: string\n selectionBarCount: string\n selectionBarClear: string\n selectionBarMore: string\n selectionBarSelectAll: string\n selectionBarEditFields: string\n selectionBarDelete: string\n /** `{count}` is the number of selected rows. */\n selectionBarDeleteConfirm: string\n selectionBarCancel: string\n // Pin splitter (`pinSplitter`)\n pinSplitterLabel: string\n pinSplitterHint: string\n pinSplitterNone: string\n pinSplitterOne: string\n /** `{count}` is the number of pinned columns. */\n pinSplitterMany: string\n // Bulk edit dialog\n bulkEditTitle: string\n bulkEditLead: string\n bulkEditMixed: string\n bulkEditApply: string\n bulkEditCancel: string\n bulkEditNoFields: string\n chartRange: string\n // Rows whose data has not arrived (server-side / infinite loading)\n rowLoadFailed: string\n rowLoadRetry: string\n // The expander on a client-side group row\n expandGroup: string\n collapseGroup: string\n // The chevron of the detail-toggle column (`showDetailToggle`)\n openDetail: string\n closeDetail: string\n // Upsell notes (enterprise views not installed)\n pivotUpsellTitle: string\n pivotUpsellBody: string\n ganttUpsellTitle: string\n ganttUpsellBody: string\n /** Placeholder in the Gantt view's search box. */\n ganttSearchPlaceholder: string\n /** Shared licensing line under every Enterprise upsell note. */\n upsellLicense: string\n upsellLicenseLink: string\n}\n```\n\n### `const defaultGridMessages`\n\nEnglish defaults - the literal strings the grid shipped before localization.\n\n```ts\nexport const defaultGridMessages: GridChromeMessages = {\n noRows: 'No rows to display.',\n noRowsFiltered: 'No rows match the current filters.',\n clearFilters: 'Clear filters',\n loading: 'Loading grid data...',\n columns: 'Columns',\n filters: 'Filters',\n clearFilter: 'Clear filter',\n pageSize: 'Page Size:',\n page: 'Page',\n of: 'of',\n firstPage: 'First page',\n prevPage: 'Previous page',\n nextPage: 'Next page',\n lastPage: 'Last page',\n statCount: 'Count',\n statSum: 'Sum',\n statAvg: 'Avg',\n statMin: 'Min',\n statMax: 'Max',\n group: 'Group',\n grandTotal: 'Grand total',\n total: 'Total',\n rowsSuffix: 'rows',\n rowSuffix: 'row',\n announceFilterResults: '{visible} of {total} rows match the current filters',\n announceNoMatches: 'No rows match the current filters',\n announceFiltersCleared: 'Filters cleared, showing all {total} rows',\n announceRowsSelected: '{count} rows selected',\n announceSelectionCleared: 'Selection cleared',\n advancedFilterActive: 'Advanced filter',\n advancedFilterClear: 'Clear advanced filter',\n menuCopy: 'Copy',\n menuCut: 'Cut',\n menuPaste: 'Paste',\n menuClear: 'Clear',\n menuInsertRowAbove: 'Insert row above',\n menuInsertRowBelow: 'Insert row below',\n menuRemoveRow: 'Remove row',\n menuRemoveColumn: 'Remove column',\n menuEditComment: 'Edit comment',\n selectionBarLabel: 'Selection actions',\n /** Label beside the count CHIP, which carries the number itself. */\n selectionBarCount: 'selected',\n selectionBarClear: 'Clear selection',\n selectionBarMore: 'More actions',\n selectionBarSelectAll: 'Select all',\n selectionBarEditFields: 'Edit fields',\n selectionBarDelete: 'Delete',\n selectionBarDeleteConfirm: 'Delete {count} rows?',\n selectionBarCancel: 'Cancel',\n pinSplitterLabel: 'Pinned columns',\n pinSplitterHint: 'Drag to pin or unpin columns',\n pinSplitterNone: 'No pinned columns',\n pinSplitterOne: '1 pinned column',\n pinSplitterMany: '{count} pinned columns',\n bulkEditTitle: 'Edit fields',\n bulkEditLead:\n 'Changes apply to all {count} selected items. Fields you leave alone keep their existing values.',\n bulkEditMixed: 'Multiple values',\n bulkEditApply: 'Apply to {count} items',\n bulkEditCancel: 'Cancel',\n bulkEditNoFields: 'No editable fields on this grid.',\n opContains: 'Contains',\n opNotContains: 'Not contains',\n opEquals: 'Equals',\n opNotEquals: 'Not equals',\n opStartsWith: 'Starts with',\n opEndsWith: 'Ends with',\n opRegex: 'Regex',\n opIn: 'In',\n opNotIn: 'Not in',\n opGreaterThan: 'Greater than',\n opLessThan: 'Less than',\n opBetween: 'Between',\n opIsBlank: 'Blank',\n opIsNotBlank: 'Not blank',\n opBefore: 'Before',\n opAfter: 'After',\n chartRange: 'Chart selected range',\n rowLoadFailed: 'Could not load these rows.',\n rowLoadRetry: 'Retry',\n expandGroup: 'Expand group',\n collapseGroup: 'Collapse group',\n openDetail: 'Open details',\n closeDetail: 'Close details',\n pivotUpsellTitle: 'Pivot mode',\n pivotUpsellBody: 'Pivot mode is an Enterprise feature. Install @svgrid/enterprise and call enablePivot() to use it.',\n ganttUpsellTitle: 'Gantt view',\n ganttUpsellBody: 'The Gantt view is an Enterprise feature. Install @svgrid/enterprise and call enableGanttView() to render it.',\n ganttSearchPlaceholder: 'Search tasks...',\n upsellLicense:\n 'A license key is required for production use. Without one the feature still works, but the grid renders an unlicensed watermark.',\n upsellLicenseLink: 'View licensing',\n}\n```\n\n### `function resolveGridMessages`\n\nMerge a consumer's `localeText` over the English defaults. Undefined/empty\nvalues fall back to the default (via `resolveMessages`), so a partial map only\nreplaces the keys it sets.\n\n```ts\nexport function resolveGridMessages(overrides?: Partial<GridMessages> | null): GridChromeMessages\n```\n"
8031
8102
  },
8032
8103
  {
8033
8104
  "slug": "reference/auto/svgrid-grid-list-option",
8034
8105
  "path": "docs/reference/auto/svgrid-grid-list-option.md",
8035
8106
  "title": "@svgrid/grid · list-option.ts",
8036
8107
  "section": "API reference",
8037
- "markdown": "# `@svgrid/grid` · `list-option.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\list-option.ts`.\n\n### `type ListOption`\n\nShared option shape for the SvGrid UI-kit selection controls.\n\n```ts\nexport type ListOption = {\n value: string | number\n label: string\n disabled?: boolean\n /** Optional group heading this option belongs under. */\n group?: string\n /** Optional color swatch (any CSS color) shown before the label. */\n color?: string\n /**\n * Optional muted text pinned to the trailing edge of the row - a count, a\n * shortcut, a unit. Not part of the label, so it does not affect matching\n * or the accessible name.\n */\n hint?: string\n}\n```\n\n### `function normalizeOptions`\n\nCoerce a raw options array into well-formed ListOptions. A primitive item\n(`1`, `'a'`) becomes `{ value, label: String(value) }`; an object missing a\n`label` or `value` gets the other filled in. This makes a caller who passes\ne.g. `[1, 2, 3]` or `['a', 'b']` render sensibly instead of crashing a keyed\n`#each` on `undefined`/duplicate `value`s.\n\n```ts\nexport function normalizeOptions(raw: ReadonlyArray<ListOption | string | number> | null | undefined): ListOption[] {\n if (!raw) return []\n return raw.map((o) => {\n if (o != null && typeof o === 'object') {\n const opt = o as Partial<ListOption>\n const value = opt.value ?? opt.label ?? ''\n return { ...(opt as ListOption), value, label: opt.label ?? String(value) }\n }\n return { value: o, label: String(o) }\n })\n}\n```\n\n### `function filterOptions`\n\nCase-insensitive substring filter over option labels.\n\n```ts\nexport function filterOptions(options: ReadonlyArray<ListOption>, query: string): ListOption[] {\n const q = query.trim().toLowerCase()\n if (!q) return [...options]\n return options.filter((o) => o.label.toLowerCase().includes(q))\n}\n```\n\n### `type IndexedOption`\n\nAn option carrying its position in the flat source array (for prop-getters).\n\n```ts\nexport type IndexedOption = ListOption & { index: number }\n```\n\n### `type OptionGroup`\n\nA section of options that share a `group` heading (null = ungrouped).\n\n```ts\nexport type OptionGroup = { group: string | null; options: IndexedOption[] }\n```\n\n### `function groupOptions`\n\nBucket options by their `group` heading, preserving each option's flat index\nso grouped rendering still drives `optionProps(index)` etc. Groups appear in\nfirst-seen order. When no option sets `group`, the result is a single\n`group: null` section (render it flat).\n\n```ts\nexport function groupOptions(options: ReadonlyArray<ListOption>): OptionGroup[] {\n const groups: OptionGroup[] = []\n const byName = new Map<string | null, OptionGroup>()\n options.forEach((o, index) => {\n const key = o.group ?? null\n let g = byName.get(key)\n if (!g) { g = { group: key, options: [] }; byName.set(key, g); groups.push(g) }\n g.options.push({ ...o, index })\n })\n return groups\n}\n```\n\n### `function hasGroups`\n\nWhether any option declares a `group` (so headings are worth rendering).\n\n```ts\nexport function hasGroups(options: ReadonlyArray<ListOption>): boolean {\n return options.some((o) => o.group != null)\n}\n```\n\n### `type RowHeight`\n\nFixed px, or a per-option function - lets a virtualized list mix row heights.\n\n```ts\nexport type RowHeight = number | ((opt: IndexedOption, index: number) => number)\n```\n\n### `type VirtualListRow`\n\nOne row of the flattened virtualization model: a group heading or an option.\n\n```ts\nexport type VirtualListRow =\n | { type: 'group'; label: string; size: number }\n | { type: 'option'; opt: IndexedOption; size: number }\n```\n\n### `type FlatVirtualModel`\n\nA flattened option list plus its measurements, for virtualizing long dropdowns.\n\n```ts\nexport type FlatVirtualModel = {\n /** Group headings + options in render order, each with its px height. */\n entries: VirtualListRow[]\n /** Whether any group heading rows are present. */\n hasGroups: boolean\n /** Height (px) of the entry at flat index `i` - feeds the virtualizer's `estimateSize`. */\n sizeAt: (i: number) => number\n /** Maps an OPTION index (position in the source options array, as used by\n * `optionProps(index)`) to its flat entry index - so the active option can\n * be scrolled into view even with group rows interleaved. */\n optionFlatIndex: number[]\n}\n```\n\n### `function flattenForVirtual`\n\nFlatten a (possibly grouped) option list into a single virtualization model:\ngroup headings become rows interleaved with their options, and each row\ncarries its pixel height. This is what lets the selection controls window a\nGROUPED list (previously they fell back to rendering every node) and support\nvariable row heights, while reusing the shared `createSvelteVirtualizer`.\n\nPure - no DOM. Builds on `groupOptions`, which already tags each option with\nits flat `index` (the value `optionProps(index)` expects).\n\n```ts\nexport function flattenForVirtual(\n options: ReadonlyArray<ListOption>,\n opts: { rowHeight: RowHeight; groupHeaderHeight?: number },\n): FlatVirtualModel {\n const headerH = Math.max(1, opts.groupHeaderHeight ?? 28)\n const rh = opts.rowHeight\n const sizeOf = (o: IndexedOption) => Math.max(1, typeof rh === 'function' ? rh(o, o.index) : rh)\n\n const entries: VirtualListRow[] = []\n const optionFlatIndex = new Array<number>(options.length)\n let anyGroups = false\n\n for (const g of groupOptions(options)) {\n if (g.group != null) {\n anyGroups = true\n entries.push({ type: 'group', label: g.group, size: headerH })\n }\n for (const opt of g.options) {\n optionFlatIndex[opt.index] = entries.length\n entries.push({ type: 'option', opt, size: sizeOf(opt) })\n }\n }\n\n return {\n entries,\n hasGroups: anyGroups,\n sizeAt: (i) => entries[i]?.size ?? 0,\n optionFlatIndex,\n }\n}\n```\n\n### `function nextTypeaheadIndex`\n\nNext enabled option index whose label starts with `buffer` (type-ahead),\nsearching forward from just after `from` and wrapping. Returns -1 for no\nmatch / empty buffer. Case-insensitive.\n\n```ts\nexport function nextTypeaheadIndex(\n options: ReadonlyArray<ListOption>,\n buffer: string,\n from: number,\n): number {\n const b = buffer.trim().toLowerCase()\n if (!b || !options.length) return -1\n const n = options.length\n for (let k = 1; k <= n; k++) {\n const i = (from + k) % n\n const o = options[i]\n if (o && !o.disabled && o.label.toLowerCase().startsWith(b)) return i\n }\n return -1\n}\n```\n\n### `function createTypeaheadBuffer`\n\nA tiny type-ahead buffer: accumulates printable characters within `timeout`\nms of each other, then resets. Frameworkfree; the caller supplies scheduling.\n\n```ts\nexport function createTypeaheadBuffer(timeout = 600) {\n let buffer = ''\n let timer: ReturnType<typeof setTimeout> | undefined\n return {\n get value() { return buffer },\n /** Append a character and (re)arm the reset timer. Returns the new buffer. */\n push(char: string): string {\n buffer += char\n if (timer) clearTimeout(timer)\n timer = setTimeout(() => { buffer = '' }, timeout)\n return buffer\n },\n clear() { buffer = ''; if (timer) clearTimeout(timer) },\n }\n}\n```\n\n### `function isTypeaheadKey`\n\nWhether a keydown is a bare printable character (a type-ahead candidate).\n\n```ts\nexport function isTypeaheadKey(e: KeyboardEvent): boolean {\n return e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey && e.key !== ' '\n}\n```\n"
8108
+ "markdown": "# `@svgrid/grid` · `list-option.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\list-option.ts`.\n\n### `type ListOption`\n\nShared option shape for the SvGrid UI-kit selection controls.\n\n```ts\nexport type ListOption = {\n value: string | number\n label: string\n disabled?: boolean\n /** Optional group heading this option belongs under. */\n group?: string\n /** Optional color swatch (any CSS color) shown before the label. */\n color?: string\n /**\n * Optional muted text pinned to the trailing edge of the row - a count, a\n * shortcut, a unit. Not part of the label, so it does not affect matching\n * or the accessible name.\n */\n hint?: string\n}\n```\n\n### `function normalizeOptions`\n\nCoerce a raw options array into well-formed ListOptions. A primitive item\n(`1`, `'a'`) becomes `{ value, label: String(value) }`; an object missing a\n`label` or `value` gets the other filled in. This makes a caller who passes\ne.g. `[1, 2, 3]` or `['a', 'b']` render sensibly instead of crashing a keyed\n`#each` on `undefined`/duplicate `value`s.\n\n```ts\nexport function normalizeOptions(raw: ReadonlyArray<ListOption | string | number> | null | undefined): ListOption[]\n```\n\n### `function filterOptions`\n\nCase-insensitive substring filter over option labels.\n\n```ts\nexport function filterOptions(options: ReadonlyArray<ListOption>, query: string): ListOption[]\n```\n\n### `type IndexedOption`\n\nAn option carrying its position in the flat source array (for prop-getters).\n\n```ts\nexport type IndexedOption = ListOption & { index: number }\n```\n\n### `type OptionGroup`\n\nA section of options that share a `group` heading (null = ungrouped).\n\n```ts\nexport type OptionGroup = { group: string | null; options: IndexedOption[] }\n```\n\n### `function groupOptions`\n\nBucket options by their `group` heading, preserving each option's flat index\nso grouped rendering still drives `optionProps(index)` etc. Groups appear in\nfirst-seen order. When no option sets `group`, the result is a single\n`group: null` section (render it flat).\n\n```ts\nexport function groupOptions(options: ReadonlyArray<ListOption>): OptionGroup[]\n```\n\n### `function hasGroups`\n\nWhether any option declares a `group` (so headings are worth rendering).\n\n```ts\nexport function hasGroups(options: ReadonlyArray<ListOption>): boolean\n```\n\n### `type RowHeight`\n\nFixed px, or a per-option function - lets a virtualized list mix row heights.\n\n```ts\nexport type RowHeight = number | ((opt: IndexedOption, index: number) => number)\n```\n\n### `type VirtualListRow`\n\nOne row of the flattened virtualization model: a group heading or an option.\n\n```ts\nexport type VirtualListRow =\n | { type: 'group'; label: string; size: number }\n | { type: 'option'; opt: IndexedOption; size: number }\n```\n\n### `type FlatVirtualModel`\n\nA flattened option list plus its measurements, for virtualizing long dropdowns.\n\n```ts\nexport type FlatVirtualModel = {\n /** Group headings + options in render order, each with its px height. */\n entries: VirtualListRow[]\n /** Whether any group heading rows are present. */\n hasGroups: boolean\n /** Height (px) of the entry at flat index `i` - feeds the virtualizer's `estimateSize`. */\n sizeAt: (i: number) => number\n /** Maps an OPTION index (position in the source options array, as used by\n * `optionProps(index)`) to its flat entry index - so the active option can\n * be scrolled into view even with group rows interleaved. */\n optionFlatIndex: number[]\n}\n```\n\n### `function flattenForVirtual`\n\nFlatten a (possibly grouped) option list into a single virtualization model:\ngroup headings become rows interleaved with their options, and each row\ncarries its pixel height. This is what lets the selection controls window a\nGROUPED list (previously they fell back to rendering every node) and support\nvariable row heights, while reusing the shared `createSvelteVirtualizer`.\n\nPure - no DOM. Builds on `groupOptions`, which already tags each option with\nits flat `index` (the value `optionProps(index)` expects).\n\n```ts\nexport function flattenForVirtual(\n options: ReadonlyArray<ListOption>,\n opts: { rowHeight: RowHeight; groupHeaderHeight?: number },\n): FlatVirtualModel\n```\n\n### `function nextTypeaheadIndex`\n\nNext enabled option index whose label starts with `buffer` (type-ahead),\nsearching forward from just after `from` and wrapping. Returns -1 for no\nmatch / empty buffer. Case-insensitive.\n\n```ts\nexport function nextTypeaheadIndex(\n options: ReadonlyArray<ListOption>,\n buffer: string,\n from: number,\n): number\n```\n\n### `function createTypeaheadBuffer`\n\nA tiny type-ahead buffer: accumulates printable characters within `timeout`\nms of each other, then resets. Frameworkfree; the caller supplies scheduling.\n\n```ts\nexport function createTypeaheadBuffer(timeout = 600)\n```\n\n### `function isTypeaheadKey`\n\nWhether a keydown is a bare printable character (a type-ahead candidate).\n\n```ts\nexport function isTypeaheadKey(e: KeyboardEvent): boolean\n```\n"
8038
8109
  },
8039
8110
  {
8040
8111
  "slug": "reference/auto/svgrid-grid-mask",
8041
8112
  "path": "docs/reference/auto/svgrid-grid-mask.md",
8042
8113
  "title": "@svgrid/grid · datetime/mask.ts",
8043
8114
  "section": "API reference",
8044
- "markdown": "# `@svgrid/grid` · `datetime/mask.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\mask.ts`.\n\n### `function applyMask`\n\nApply `pattern` to raw input `value`, inserting literals and dropping chars\nthat don't fit the next token. Returns the formatted string and the count of\nconsumed input characters (useful for caret math).\n\n```ts\nexport function applyMask(value: string, pattern: string): { formatted: string; filled: number } {\n let out = ''\n let vi = 0\n let filled = 0\n for (let pi = 0; pi < pattern.length; pi++) {\n const token = pattern[pi]!\n if (!isToken(token)) {\n // Literal: emit it only once we have (or will have) more input to place.\n out += token\n // Skip a matching literal the user may have typed.\n if (value[vi] === token) vi++\n continue\n }\n // Advance through input until a char fits this token.\n while (vi < value.length && !matches(token, value[vi]!)) vi++\n if (vi >= value.length) break // no more input for this token\n out += value[vi]!\n vi++\n filled++\n }\n // Drop any trailing literals with no following data char.\n return { formatted: trimTrailingLiterals(out), filled }\n}\n```\n\n### `function unmask`\n\nStrip literals, returning only the data characters the user supplied.\n\n```ts\nexport function unmask(value: string, pattern: string): string {\n let out = ''\n let vi = 0\n for (let pi = 0; pi < pattern.length && vi < value.length; pi++) {\n const token = pattern[pi]!\n if (!isToken(token)) {\n if (value[vi] === token) vi++\n continue\n }\n while (vi < value.length && !matches(token, value[vi]!)) vi++\n if (vi < value.length) { out += value[vi]!; vi++ }\n }\n return out\n}\n```\n\n### `function isMaskComplete`\n\nTrue when every token position in the pattern is filled.\n\n```ts\nexport function isMaskComplete(value: string, pattern: string): boolean {\n const tokenCount = [...pattern].filter(isToken).length\n return unmask(value, pattern).length >= tokenCount\n}\n```\n"
8115
+ "markdown": "# `@svgrid/grid` · `datetime/mask.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\mask.ts`.\n\n### `function applyMask`\n\nApply `pattern` to raw input `value`, inserting literals and dropping chars\nthat don't fit the next token. Returns the formatted string and the count of\nconsumed input characters (useful for caret math).\n\n```ts\nexport function applyMask(value: string, pattern: string): { formatted: string; filled: number }\n```\n\n### `function unmask`\n\nStrip literals, returning only the data characters the user supplied.\n\n```ts\nexport function unmask(value: string, pattern: string): string\n```\n\n### `function isMaskComplete`\n\nTrue when every token position in the pattern is filled.\n\n```ts\nexport function isMaskComplete(value: string, pattern: string): boolean\n```\n"
8045
8116
  },
8046
8117
  {
8047
8118
  "slug": "reference/auto/svgrid-grid-positioning",
8048
8119
  "path": "docs/reference/auto/svgrid-grid-positioning.md",
8049
8120
  "title": "@svgrid/grid · positioning.ts",
8050
8121
  "section": "API reference",
8051
- "markdown": "# `@svgrid/grid` · `positioning.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\positioning.ts`.\n\n### `type Side`\n\nA physical side the floating element is placed on, relative to the reference.\n\n```ts\nexport type Side = 'top' | 'bottom' | 'left' | 'right'\n```\n\n### `type Align`\n\nCross-axis alignment. `center` is the bare side (e.g. `'bottom'`).\n\n```ts\nexport type Align = 'start' | 'center' | 'end'\n```\n\n### `type Placement`\n\n`'bottom'` = bottom-center; `'bottom-start'` / `'bottom-end'` align the edges.\n\n```ts\nexport type Placement = Side | `${Side}-start` | `${Side}-end`\n```\n\n### `type Rect`\n\nA viewport-relative rectangle (CSS `getBoundingClientRect` shape suffices).\n\n```ts\nexport type Rect = { x: number; y: number; width: number; height: number }\n```\n\n### `type Viewport`\n\nThe available viewport (defaults to `window` in the browser).\n\n```ts\nexport type Viewport = { width: number; height: number }\n```\n\n### `type ComputePositionOptions`\n\nWhere to put a floating element: its preferred side, offsets, and collision behaviour.\n\n```ts\nexport type ComputePositionOptions = {\n /** Preferred placement. Default `'bottom-start'`. */\n placement?: Placement\n /** Main-axis gap between reference and floating. Default 6. */\n offset?: number\n /** Viewport edge kept clear on every side. Default 8. */\n padding?: number\n /** Flip to the opposite side when the preferred side overflows. Default true. */\n flip?: boolean\n /** Shift along the cross axis to stay in view (without flipping). Default true. */\n shift?: boolean\n /** Compute `maxWidth`/`maxHeight` for the chosen side. Default true. */\n size?: boolean\n /** When set, compute the arrow offset for an arrow element of this size (px). */\n arrow?: { size: number }\n /** Extra placements to try (after the automatic opposite) before giving up. */\n fallbackPlacements?: Placement[]\n /** Viewport to fit within. Defaults to the window; pure callers pass it. */\n viewport?: Viewport\n /** Floor for the available main-axis size returned by `size`. Default 0. */\n minMainAxis?: number\n}\n```\n\n### `type ComputePositionResult`\n\nThe resolved position, including the side actually used after collision handling.\n\n```ts\nexport type ComputePositionResult = {\n /** Floating left, in viewport (fixed-position) coordinates. */\n x: number\n /** Floating top, in viewport (fixed-position) coordinates. */\n y: number\n /** The resolved placement after flip. */\n placement: Placement\n /** The resolved side after flip. */\n side: Side\n /** The resolved cross-axis alignment. */\n align: Align\n /** Space available for the floating on the chosen side's main axis (+cross). */\n maxWidth: number\n maxHeight: number\n /**\n * Arrow offset within the floating box: `x` for top/bottom placements, `y` for\n * left/right. Only present when `options.arrow` is set. Clamped so the arrow\n * stays inside the floating (minus padding).\n */\n arrow?: { x?: number; y?: number }\n}\n```\n\n### `function parsePlacement`\n\nSplit a placement into its side + alignment (`center` when no suffix).\n\n```ts\nexport function parsePlacement(p: Placement): { side: Side; align: Align } {\n const [side, align] = p.split('-') as [Side, 'start' | 'end' | undefined]\n return { side, align: align ?? 'center' }\n}\n```\n\n### `function computePosition`\n\nCompute the floating position anchored to `reference`, applying flip (opposite\nside when the preferred side overflows), shift (cross-axis clamp to stay in\nview), size (available max width/height on the chosen side) and an optional\narrow offset. Pure - pass an explicit `viewport` in tests.\n\n```ts\nexport function computePosition(\n reference: Rect,\n floating: Viewport,\n options: ComputePositionOptions = {},\n): ComputePositionResult {\n const offset = options.offset ?? 6\n const pad = options.padding ?? 8\n const doFlip = options.flip !== false\n const doShift = options.shift !== false\n const v = resolveViewport(options.viewport)\n const preferred = options.placement ?? 'bottom-start'\n\n // ---- flip: pick the placement whose main-axis overflow is smallest ----\n const candidates: Placement[] = [preferred]\n if (doFlip) {\n candidates.push(opposite(preferred))\n for (const fb of options.fallbackPlacements ?? []) candidates.push(fb)\n }\n let chosen = preferred\n let best = Infinity\n for (const cand of candidates) {\n const { side, align } = parsePlacement(cand)\n const { x, y } = coordsFor(side, align, reference, floating, offset)\n const overflow = mainAxisOverflow(side, x, y, floating, v, pad)\n if (overflow <= 0) {\n chosen = cand\n best = overflow\n break\n }\n if (overflow < best) {\n best = overflow\n chosen = cand\n }\n }\n\n const { side, align } = parsePlacement(chosen)\n let { x, y } = coordsFor(side, align, reference, floating, offset)\n\n // ---- shift: clamp along the CROSS axis so the floating stays in view ----\n if (doShift) {\n if (side === 'top' || side === 'bottom') {\n x = clamp(x, pad, v.width - pad - floating.width)\n } else {\n y = clamp(y, pad, v.height - pad - floating.height)\n }\n }\n\n // ---- size: available room on the chosen side ----\n const minMain = options.minMainAxis ?? 0\n let maxWidth: number\n let maxHeight: number\n if (side === 'top' || side === 'bottom') {\n const avail = side === 'top' ? reference.y - offset - pad : v.height - pad - (reference.y + reference.height + offset)\n maxHeight = Math.max(minMain, Math.floor(avail))\n maxWidth = Math.max(0, v.width - 2 * pad)\n } else {\n const avail = side === 'left' ? reference.x - offset - pad : v.width - pad - (reference.x + reference.width + offset)\n maxWidth = Math.max(minMain, Math.floor(avail))\n maxHeight = Math.max(0, v.height - 2 * pad)\n }\n\n const result: ComputePositionResult = { x, y, placement: chosen, side, align, maxWidth, maxHeight }\n\n // ---- arrow: point at the reference center, clamped inside the floating ----\n if (options.arrow) {\n const a = options.arrow.size\n if (side === 'top' || side === 'bottom') {\n const center = reference.x + reference.width / 2\n const ax = clamp(center - x - a / 2, pad, floating.width - a - pad)\n result.arrow = { x: ax }\n } else {\n const center = reference.y + reference.height / 2\n const ay = clamp(center - y - a / 2, pad, floating.height - a - pad)\n result.arrow = { y: ay }\n }\n }\n\n return result\n}\n```\n\n### `function autoUpdate`\n\nRe-run `update` whenever the anchored position could change: the reference or\nfloating element resizes, an ancestor scrolls, or the window scrolls/resizes.\nReturns a cleanup function. SSR-safe (a no-op without `window`).\n\n```ts\nconst stop = autoUpdate(triggerEl, panelEl, () => reposition())\n// ...later\nstop()\n```\n\n```ts\nexport function autoUpdate(reference: Element, floating: HTMLElement, update: () => void): () => void {\n if (typeof window === 'undefined') return () => {}\n const ancestors = scrollParents(reference)\n for (const a of ancestors) a.addEventListener('scroll', update, { passive: true })\n window.addEventListener('scroll', update, { passive: true })\n window.addEventListener('resize', update)\n\n let ro: ResizeObserver | undefined\n if (typeof ResizeObserver === 'function') {\n ro = new ResizeObserver(update)\n ro.observe(reference)\n ro.observe(floating)\n }\n\n update()\n\n return () => {\n for (const a of ancestors) a.removeEventListener('scroll', update)\n window.removeEventListener('scroll', update)\n window.removeEventListener('resize', update)\n ro?.disconnect()\n }\n}\n```\n"
8122
+ "markdown": "# `@svgrid/grid` · `positioning.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\positioning.ts`.\n\n### `type Side`\n\nA physical side the floating element is placed on, relative to the reference.\n\n```ts\nexport type Side = 'top' | 'bottom' | 'left' | 'right'\n```\n\n### `type Align`\n\nCross-axis alignment. `center` is the bare side (e.g. `'bottom'`).\n\n```ts\nexport type Align = 'start' | 'center' | 'end'\n```\n\n### `type Placement`\n\n`'bottom'` = bottom-center; `'bottom-start'` / `'bottom-end'` align the edges.\n\n```ts\nexport type Placement = Side | `${Side}-start` | `${Side}-end`\n```\n\n### `type Rect`\n\nA viewport-relative rectangle (CSS `getBoundingClientRect` shape suffices).\n\n```ts\nexport type Rect = { x: number; y: number; width: number; height: number }\n```\n\n### `type Viewport`\n\nThe available viewport (defaults to `window` in the browser).\n\n```ts\nexport type Viewport = { width: number; height: number }\n```\n\n### `type ComputePositionOptions`\n\nWhere to put a floating element: its preferred side, offsets, and collision behaviour.\n\n```ts\nexport type ComputePositionOptions = {\n /** Preferred placement. Default `'bottom-start'`. */\n placement?: Placement\n /** Main-axis gap between reference and floating. Default 6. */\n offset?: number\n /** Viewport edge kept clear on every side. Default 8. */\n padding?: number\n /** Flip to the opposite side when the preferred side overflows. Default true. */\n flip?: boolean\n /** Shift along the cross axis to stay in view (without flipping). Default true. */\n shift?: boolean\n /** Compute `maxWidth`/`maxHeight` for the chosen side. Default true. */\n size?: boolean\n /** When set, compute the arrow offset for an arrow element of this size (px). */\n arrow?: { size: number }\n /** Extra placements to try (after the automatic opposite) before giving up. */\n fallbackPlacements?: Placement[]\n /** Viewport to fit within. Defaults to the window; pure callers pass it. */\n viewport?: Viewport\n /** Floor for the available main-axis size returned by `size`. Default 0. */\n minMainAxis?: number\n}\n```\n\n### `type ComputePositionResult`\n\nThe resolved position, including the side actually used after collision handling.\n\n```ts\nexport type ComputePositionResult = {\n /** Floating left, in viewport (fixed-position) coordinates. */\n x: number\n /** Floating top, in viewport (fixed-position) coordinates. */\n y: number\n /** The resolved placement after flip. */\n placement: Placement\n /** The resolved side after flip. */\n side: Side\n /** The resolved cross-axis alignment. */\n align: Align\n /** Space available for the floating on the chosen side's main axis (+cross). */\n maxWidth: number\n maxHeight: number\n /**\n * Arrow offset within the floating box: `x` for top/bottom placements, `y` for\n * left/right. Only present when `options.arrow` is set. Clamped so the arrow\n * stays inside the floating (minus padding).\n */\n arrow?: { x?: number; y?: number }\n}\n```\n\n### `function parsePlacement`\n\nSplit a placement into its side + alignment (`center` when no suffix).\n\n```ts\nexport function parsePlacement(p: Placement): { side: Side; align: Align }\n```\n\n### `function computePosition`\n\nCompute the floating position anchored to `reference`, applying flip (opposite\nside when the preferred side overflows), shift (cross-axis clamp to stay in\nview), size (available max width/height on the chosen side) and an optional\narrow offset. Pure - pass an explicit `viewport` in tests.\n\n```ts\nexport function computePosition(\n reference: Rect,\n floating: Viewport,\n options: ComputePositionOptions = {},\n): ComputePositionResult\n```\n\n### `function autoUpdate`\n\nRe-run `update` whenever the anchored position could change: the reference or\nfloating element resizes, an ancestor scrolls, or the window scrolls/resizes.\nReturns a cleanup function. SSR-safe (a no-op without `window`).\n\n```ts\nconst stop = autoUpdate(triggerEl, panelEl, () => reposition())\n// ...later\nstop()\n```\n\n```ts\nexport function autoUpdate(reference: Element, floating: HTMLElement, update: () => void): () => void\n```\n"
8052
8123
  },
8053
8124
  {
8054
8125
  "slug": "reference/auto/svgrid-grid-row-model",
8055
8126
  "path": "docs/reference/auto/svgrid-grid-row-model.md",
8056
8127
  "title": "@svgrid/grid · row-model.ts",
8057
8128
  "section": "API reference",
8058
- "markdown": "# `@svgrid/grid` · `row-model.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\row-model.ts`.\n\n### `type GridFilterState`\n\nThe filter state as the grid reports it, straight from `onFiltersChange`.\n\n```ts\nexport type GridFilterState = {\n global: string\n columns: Array<{\n id: string\n operator: FilterOperator\n value: string\n valueTo?: string\n selectedValues?: Array<string>\n }>\n}\n```\n\n### `type GridRowModelSort`\n\nThe sort the grid hands a row model: column id and direction, in priority order.\n\n```ts\nexport type GridRowModelSort = Array<{ id: string; desc: boolean }>\n```\n\n### `type GridRowModel`\n\nWhat `<SvGrid rowModel>` consumes: rows, a loading flag, a change\nsubscription, and whichever optional parts the model implements - sort,\nfilter, viewport, placeholders, group accessors, selection, filter\nvalues, paging, pinned rows and pivot columns. `createServerDataSource`\nand the Enterprise `createServerRowModel` both satisfy it.\n\n```ts\nexport type GridRowModel<TData> = {\n /**\n * Register a callback for \"something changed, re-read me\". Returns an\n * unsubscribe function, which the grid calls on unmount.\n */\n subscribe(onChange: () => void): () => void\n /** The rows to render, including any placeholders for unloaded ones. */\n getRows(): ReadonlyArray<TData>\n /** True while a fetch is in flight, for the loading overlay. */\n isLoading(): boolean\n /** Stable row id. Required once selection or editing is involved. */\n getRowId?(row: TData, index: number): string\n /** Sort on the server. Present means \"do not sort locally\". */\n setSort?(sort: GridRowModelSort): void\n /** Filter on the server. Present means \"do not filter locally\". */\n setFilter?(filters: GridFilterState): void\n /** Which rows are on screen, so a block-loading model knows what to fetch. */\n setViewport?(startIndex: number, endIndex: number): void\n /** Why a row has no data yet, or null when it does. */\n rowPlaceholder?(row: TData, rowIndex: number): 'loading' | 'failed' | null\n /** Retry the failed block a placeholder row belongs to. */\n retryRow?(row: TData, rowIndex: number): void\n /** Group / tree accessors, for the grid's treegrid keyboard and ARIA. */\n group?: {\n isGroup: (row: TData) => boolean\n level: (row: TData) => number\n expanded?: (row: TData) => boolean\n onToggle: (row: TData) => void\n /** Open or close the detail panel under a leaf. Ctrl+Enter on a row calls it when `renderDetailRow` is set, and so does the `showDetailToggle` chevron. */\n toggleDetail?: (row: TData) => void\n /** Whether the detail under a leaf is open: the chevron's direction. */\n detailOpen?: (row: TData) => boolean\n /** Whether a row can open a detail; the chevron is left out where this is false. */\n hasDetail?: (row: TData) => boolean\n }\n /** Selection the grid does not own - see the `rowSelectionModel` prop. */\n selection?: {\n isSelected: (rowId: string, row: TData) => boolean\n headerState: () => 'none' | 'some' | 'all'\n toggle: (rowId: string, row: TData, next: boolean) => void\n toggleAll: (next: boolean) => void\n selectedCount?: () => number | null\n bulkUpdate?: (patch: Record<string, unknown>) => Promise<number>\n }\n /** Distinct values for a column's set filter, fetched from the server. */\n filterValues?(columnId: string): Promise<Array<string>>\n /** Server-side paging. Omit it for infinite scrolling. */\n pagination?: {\n pageIndex: number\n pageSize: number\n rowCount: number\n setPage(pageIndex: number): void\n setPageSize(pageSize: number): void\n /** Choices for the footer's page-size selector. */\n pageSizes?: number[]\n /**\n * Ask the grid for as many rows as its body fits: it measures and calls\n * `setPageSize` whenever the fit changes.\n */\n autoPageSize?: boolean\n }\n /** Rows to pin above / below the scrolling body - a grand total, say. */\n readonly pinnedTopRows?: ReadonlyArray<TData>\n readonly pinnedBottomRows?: ReadonlyArray<TData>\n /**\n * Columns that replace the grid's `columns` while the model is in pivot\n * mode, or null. Read after every change notification.\n */\n readonly pivotResultColumns?: ReadonlyArray<unknown> | null\n}\n```\n\n### `function toServerFilterColumns`\n\nTurn the grid's filter payload into the column-keyed map a `ServerRequest`\ncarries. Exported because a hand-written `GridRowModel` needs exactly this\nconversion, and copying it is how the two shapes drift apart.\n\n```ts\nexport function toServerFilterColumns(\n filters: GridFilterState,\n): Record<\n string,\n { operator: string; value: string; valueTo?: string; selectedValues?: Array<string> }\n```\n"
8129
+ "markdown": "# `@svgrid/grid` · `row-model.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\row-model.ts`.\n\n### `type GridFilterState`\n\nThe filter state as the grid reports it, straight from `onFiltersChange`.\n\n```ts\nexport type GridFilterState = {\n global: string\n columns: Array<{\n id: string\n operator: FilterOperator\n value: string\n valueTo?: string\n selectedValues?: Array<string>\n }>\n /** Active `customFilter` models keyed by column id, when any is active. */\n custom?: Record<string, unknown>\n}\n```\n\n### `type GridRowModelSort`\n\nThe sort the grid hands a row model: column id and direction, in priority order.\n\n```ts\nexport type GridRowModelSort = Array<{ id: string; desc: boolean }>\n```\n\n### `type GridRowModel`\n\nWhat `<SvGrid rowModel>` consumes: rows, a loading flag, a change\nsubscription, and whichever optional parts the model implements - sort,\nfilter, viewport, placeholders, group accessors, selection, filter\nvalues, paging, pinned rows and pivot columns. `createServerDataSource`\nand the Enterprise `createServerRowModel` both satisfy it.\n\n```ts\nexport type GridRowModel<TData> = {\n /**\n * Register a callback for \"something changed, re-read me\". Returns an\n * unsubscribe function, which the grid calls on unmount.\n */\n subscribe(onChange: () => void): () => void\n /** The rows to render, including any placeholders for unloaded ones. */\n getRows(): ReadonlyArray<TData>\n /** True while a fetch is in flight, for the loading overlay. */\n isLoading(): boolean\n /** Stable row id. Required once selection or editing is involved. */\n getRowId?(row: TData, index: number): string\n /** Sort on the server. Present means \"do not sort locally\". */\n setSort?(sort: GridRowModelSort): void\n /** Filter on the server. Present means \"do not filter locally\". */\n setFilter?(filters: GridFilterState): void\n /** Which rows are on screen, so a block-loading model knows what to fetch. */\n setViewport?(startIndex: number, endIndex: number): void\n /** Why a row has no data yet, or null when it does. */\n rowPlaceholder?(row: TData, rowIndex: number): 'loading' | 'failed' | null\n /** Retry the failed block a placeholder row belongs to. */\n retryRow?(row: TData, rowIndex: number): void\n /** Group / tree accessors, for the grid's treegrid keyboard and ARIA. */\n group?: {\n isGroup: (row: TData) => boolean\n level: (row: TData) => number\n expanded?: (row: TData) => boolean\n onToggle: (row: TData) => void\n /** Open or close the detail panel under a leaf. Ctrl+Enter on a row calls it when `renderDetailRow` is set, and so does the `showDetailToggle` chevron. */\n toggleDetail?: (row: TData) => void\n /** Whether the detail under a leaf is open: the chevron's direction. */\n detailOpen?: (row: TData) => boolean\n /** Whether a row can open a detail; the chevron is left out where this is false. */\n hasDetail?: (row: TData) => boolean\n }\n /** Selection the grid does not own - see the `rowSelectionModel` prop. */\n selection?: {\n isSelected: (rowId: string, row: TData) => boolean\n headerState: () => 'none' | 'some' | 'all'\n toggle: (rowId: string, row: TData, next: boolean) => void\n toggleAll: (next: boolean) => void\n selectedCount?: () => number | null\n bulkUpdate?: (patch: Record<string, unknown>) => Promise<number>\n }\n /** Distinct values for a column's set filter, fetched from the server. */\n filterValues?(columnId: string): Promise<Array<string>>\n /** Server-side paging. Omit it for infinite scrolling. */\n pagination?: {\n pageIndex: number\n pageSize: number\n rowCount: number\n setPage(pageIndex: number): void\n setPageSize(pageSize: number): void\n /** Choices for the footer's page-size selector. */\n pageSizes?: number[]\n /**\n * Ask the grid for as many rows as its body fits: it measures and calls\n * `setPageSize` whenever the fit changes.\n */\n autoPageSize?: boolean\n }\n /** Rows to pin above / below the scrolling body - a grand total, say. */\n readonly pinnedTopRows?: ReadonlyArray<TData>\n readonly pinnedBottomRows?: ReadonlyArray<TData>\n /**\n * Columns that replace the grid's `columns` while the model is in pivot\n * mode, or null. Read after every change notification.\n */\n readonly pivotResultColumns?: ReadonlyArray<unknown> | null\n}\n```\n\n### `function toServerFilterColumns`\n\nTurn the grid's filter payload into the column-keyed map a `ServerRequest`\ncarries. Exported because a hand-written `GridRowModel` needs exactly this\nconversion, and copying it is how the two shapes drift apart.\n\nA registered operator with a `toServer` (the Enterprise relative date\noperators) goes out as the built-in filter it means now, so a backend never\nmeets an operator it cannot know.\n\n```ts\nexport function toServerFilterColumns(\n filters: GridFilterState,\n): Record<\n string,\n { operator: string; value: string; valueTo?: string; selectedValues?: Array<string> }\n```\n"
8059
8130
  },
8060
8131
  {
8061
8132
  "slug": "reference/auto/svgrid-grid-row-predicate",
8062
8133
  "path": "docs/reference/auto/svgrid-grid-row-predicate.md",
8063
8134
  "title": "@svgrid/grid · filtering/row-predicate.ts",
8064
8135
  "section": "API reference",
8065
- "markdown": "# `@svgrid/grid` · `filtering/row-predicate.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\filtering\\row-predicate.ts`.\n\n### `function applyRowPredicate`\n\nApply `keep` to leaf rows, dropping banners left with no surviving child.\n\n```ts\nexport function applyRowPredicate<TRow>(\n rows: ReadonlyArray<TRow>,\n keep: (row: TRow) => boolean,\n isGroup: (row: TRow) => boolean,\n): TRow[] {\n // Fast path: no grouping in play, so every row is a leaf.\n let hasGroup = false\n for (const row of rows) {\n if (isGroup(row)) {\n hasGroup = true\n break\n }\n }\n if (!hasGroup) return rows.filter(keep)\n\n // Any leaf under a banner, through its subRows (the banner is collapsed).\n const anyLeaf = (row: TRow): boolean =>\n ((row as Tree<TRow>).subRows ?? []).some((sub) => (isGroup(sub) ? anyLeaf(sub) : keep(sub)))\n\n // One forward pass. `open` holds the banners above the current row; a kept\n // row keeps every one of them, and only them.\n const keepFlags = new Array<boolean>(rows.length).fill(false)\n const open: number[] = []\n const keepOpen = () => {\n for (let k = open.length - 1; k >= 0 && !keepFlags[open[k]!]; k -= 1) keepFlags[open[k]!] = true\n }\n for (let i = 0; i < rows.length; i += 1) {\n const row = rows[i]!\n const depth = depthOf(row)\n while (open.length && depthOf(rows[open[open.length - 1]!]) >= depth) open.pop()\n if (isGroup(row)) {\n open.push(i)\n const next = rows[i + 1]\n const collapsed = next === undefined || depthOf(next) <= depth\n if (collapsed && anyLeaf(row)) keepOpen()\n } else if (keep(row)) {\n keepFlags[i] = true\n keepOpen()\n }\n }\n\n const out: TRow[] = []\n for (let i = 0; i < rows.length; i += 1) if (keepFlags[i]) out.push(rows[i]!)\n return out\n}\n```\n"
8136
+ "markdown": "# `@svgrid/grid` · `filtering/row-predicate.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\filtering\\row-predicate.ts`.\n\n### `function applyRowPredicate`\n\nApply `keep` to leaf rows, dropping banners left with no surviving child.\n\n```ts\nexport function applyRowPredicate<TRow>(\n rows: ReadonlyArray<TRow>,\n keep: (row: TRow) => boolean,\n isGroup: (row: TRow) => boolean,\n): TRow[]\n```\n"
8066
8137
  },
8067
8138
  {
8068
8139
  "slug": "reference/auto/svgrid-grid-scheduler-ical",
8069
8140
  "path": "docs/reference/auto/svgrid-grid-scheduler-ical.md",
8070
8141
  "title": "@svgrid/grid · scheduler-ical.ts",
8071
8142
  "section": "API reference",
8072
- "markdown": "# `@svgrid/grid` · `scheduler-ical.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\scheduler-ical.ts`.\n\n### `type ICalEvent`\n\nOne VEVENT: the fields SvGrid reads from and writes to an iCalendar feed.\n\n```ts\nexport type ICalEvent = {\n uid?: string\n title: string\n description?: string\n location?: string\n start: Date\n end: Date\n allDay?: boolean\n status?: 'confirmed' | 'tentative' | 'cancelled'\n rrule?: RecurrenceRule | null\n}\n```\n\n### `function ruleToRRule`\n\nA {@link RecurrenceRule} -> an iCal `RRULE` value (without the `RRULE:` name).\n\n```ts\nexport function ruleToRRule(rule: RecurrenceRule): string {\n const parts = [`FREQ=${rule.freq.toUpperCase()}`]\n if (rule.interval && rule.interval > 1) parts.push(`INTERVAL=${rule.interval}`)\n if (rule.weekdays?.length) {\n if (rule.weekOfMonth != null && rule.weekdays.length === 1) {\n parts.push(`BYDAY=${rule.weekOfMonth}${WD[rule.weekdays[0]!]}`)\n } else {\n parts.push(`BYDAY=${rule.weekdays.map((w) => WD[w]).join(',')}`)\n }\n }\n if (rule.day != null && rule.weekOfMonth == null) parts.push(`BYMONTHDAY=${rule.day}`)\n if (rule.month != null) parts.push(`BYMONTH=${rule.month + 1}`)\n if (rule.count != null) parts.push(`COUNT=${rule.count}`)\n if (rule.until != null) parts.push(`UNTIL=${utcStamp(new Date(rule.until as string))}`)\n return parts.join(';')\n}\n```\n\n### `function rruleToRule`\n\nAn iCal `RRULE` value -> a {@link RecurrenceRule}.\n\n```ts\nexport function rruleToRule(value: string): RecurrenceRule | null {\n const map: Record<string, string> = {}\n for (const kv of value.split(';')) {\n const [k, v] = kv.split('=')\n if (k && v) map[k.toUpperCase()] = v\n }\n const freq = (map.FREQ ?? '').toLowerCase()\n if (!['daily', 'weekly', 'monthly', 'yearly'].includes(freq)) return null\n const rule: RecurrenceRule = { freq: freq as RecurrenceRule['freq'] }\n if (map.INTERVAL) rule.interval = Number(map.INTERVAL)\n if (map.BYDAY) {\n const parts = map.BYDAY.split(',')\n const m = parts[0]!.match(/^(-?\\d+)?([A-Z]{2})$/)\n if (parts.length === 1 && m && m[1]) {\n rule.weekOfMonth = Number(m[1])\n rule.weekdays = [WD.indexOf(m[2] as (typeof WD)[number])]\n } else {\n rule.weekdays = parts.map((p) => WD.indexOf(p.replace(/^-?\\d+/, '') as (typeof WD)[number])).filter((n) => n >= 0)\n }\n }\n if (map.BYMONTHDAY) rule.day = Number(map.BYMONTHDAY)\n if (map.BYMONTH) rule.month = Number(map.BYMONTH) - 1\n if (map.COUNT) rule.count = Number(map.COUNT)\n if (map.UNTIL) rule.until = parseICalDate(map.UNTIL).date.toISOString()\n return rule\n}\n```\n\n### `function toICS`\n\nSerialize events to an iCalendar string. `stamp` sets DTSTAMP (default epoch).\n\n```ts\nexport function toICS(events: ReadonlyArray<ICalEvent>, opts: { prodId?: string; stamp?: Date } = {}): string {\n const stamp = utcStamp(opts.stamp ?? new Date(0))\n const lines = ['BEGIN:VCALENDAR', 'VERSION:2.0', `PRODID:${opts.prodId ?? '-//SvGrid//Scheduler//EN'}`]\n events.forEach((e, i) => {\n lines.push('BEGIN:VEVENT')\n lines.push(`UID:${e.uid ?? `svgrid-${i}-${e.start.getTime()}`}`)\n lines.push(`DTSTAMP:${stamp}`)\n if (e.allDay) {\n lines.push(`DTSTART;VALUE=DATE:${dateOnly(e.start)}`)\n lines.push(`DTEND;VALUE=DATE:${dateOnly(e.end)}`)\n } else {\n lines.push(`DTSTART:${utcStamp(e.start)}`)\n lines.push(`DTEND:${utcStamp(e.end)}`)\n }\n lines.push(`SUMMARY:${escText(e.title)}`)\n if (e.description) lines.push(`DESCRIPTION:${escText(e.description)}`)\n if (e.location) lines.push(`LOCATION:${escText(e.location)}`)\n if (e.status) lines.push(`STATUS:${e.status.toUpperCase()}`)\n if (e.rrule) lines.push(`RRULE:${ruleToRRule(e.rrule)}`)\n lines.push('END:VEVENT')\n })\n lines.push('END:VCALENDAR')\n return lines.map(fold).join('\\r\\n')\n}\n```\n\n### `function fromICS`\n\nParse an iCalendar string into events (unfolds lines, reads VEVENT blocks).\n\n```ts\nexport function fromICS(text: string): ICalEvent[] {\n // Unfold: a line starting with space/tab continues the previous one.\n const raw = text.replace(/\\r\\n/g, '\\n').split('\\n')\n const unfolded: string[] = []\n for (const line of raw) {\n if ((line.startsWith(' ') || line.startsWith('\\t')) && unfolded.length) {\n unfolded[unfolded.length - 1] += line.slice(1)\n } else unfolded.push(line)\n }\n const out: ICalEvent[] = []\n let cur: Partial<ICalEvent> & { _allDayStart?: boolean } = {}\n let inEvent = false\n for (const line of unfolded) {\n if (line === 'BEGIN:VEVENT') {\n inEvent = true\n cur = {}\n continue\n }\n if (line === 'END:VEVENT') {\n if (cur.title && cur.start && cur.end) out.push({ title: cur.title, start: cur.start, end: cur.end, allDay: cur.allDay, uid: cur.uid, description: cur.description, location: cur.location, status: cur.status, rrule: cur.rrule ?? null })\n inEvent = false\n continue\n }\n if (!inEvent) continue\n const ci = line.indexOf(':')\n if (ci < 0) continue\n const nameAndParams = line.slice(0, ci)\n const value = line.slice(ci + 1)\n const name = nameAndParams.split(';')[0]!.toUpperCase()\n if (name === 'UID') cur.uid = value\n else if (name === 'SUMMARY') cur.title = unescText(value)\n else if (name === 'DESCRIPTION') cur.description = unescText(value)\n else if (name === 'LOCATION') cur.location = unescText(value)\n else if (name === 'STATUS') cur.status = value.toLowerCase() as ICalEvent['status']\n else if (name === 'DTSTART') {\n const { date, allDay } = parseICalDate(value)\n cur.start = date\n cur.allDay = allDay\n } else if (name === 'DTEND') {\n cur.end = parseICalDate(value).date\n } else if (name === 'RRULE') {\n cur.rrule = rruleToRule(value) ?? undefined\n }\n }\n return out\n}\n```\n"
8143
+ "markdown": "# `@svgrid/grid` · `scheduler-ical.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\scheduler-ical.ts`.\n\n### `type ICalEvent`\n\nOne VEVENT: the fields SvGrid reads from and writes to an iCalendar feed.\n\n```ts\nexport type ICalEvent = {\n uid?: string\n title: string\n description?: string\n location?: string\n start: Date\n end: Date\n allDay?: boolean\n status?: 'confirmed' | 'tentative' | 'cancelled'\n rrule?: RecurrenceRule | null\n}\n```\n\n### `function ruleToRRule`\n\nA {@link RecurrenceRule} -> an iCal `RRULE` value (without the `RRULE:` name).\n\n```ts\nexport function ruleToRRule(rule: RecurrenceRule): string\n```\n\n### `function rruleToRule`\n\nAn iCal `RRULE` value -> a {@link RecurrenceRule}.\n\n```ts\nexport function rruleToRule(value: string): RecurrenceRule | null\n```\n\n### `function toICS`\n\nSerialize events to an iCalendar string. `stamp` sets DTSTAMP (default epoch).\n\n```ts\nexport function toICS(events: ReadonlyArray<ICalEvent>, opts: { prodId?: string; stamp?: Date } = {}): string\n```\n\n### `function fromICS`\n\nParse an iCalendar string into events (unfolds lines, reads VEVENT blocks).\n\n```ts\nexport function fromICS(text: string): ICalEvent[]\n```\n"
8073
8144
  },
8074
8145
  {
8075
8146
  "slug": "reference/auto/svgrid-grid-scheduler-model",
8076
8147
  "path": "docs/reference/auto/svgrid-grid-scheduler-model.md",
8077
8148
  "title": "@svgrid/grid · scheduler-model.ts",
8078
8149
  "section": "API reference",
8079
- "markdown": "# `@svgrid/grid` · `scheduler-model.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\scheduler-model.ts`.\n\n### `type ResolvedEvent`\n\nA concrete event instance placed on the calendar (one row may yield many when\n it recurs). `key` is unique per instance; `rowKey` ties it back to its row.\n\n```ts\nexport type ResolvedEvent<TData = unknown> = {\n key: string\n rowKey: string\n row: TData\n title: string\n start: Date\n end: Date\n allDay: boolean\n color?: string\n /** Optional secondary accent (e.g. a category) shown as a left strip, distinct\n * from the main `color`. */\n color2?: string\n /** Free/busy status (busy | free | tentative | oof) for a distinct visual. */\n status?: string\n resourceId?: string\n /** True when this instance came from expanding a recurrence rule. */\n recurring: boolean\n /** For a recurring instance, its canonical (pre-override) occurrence start -\n * the identity used to key {@link RecurrenceException} overrides. */\n occurrenceStart?: Date\n /** True when a recurring instance carries a per-occurrence override. */\n isException?: boolean\n}\n```\n\n### `type RecurrenceException`\n\nA per-occurrence override of a recurring event (the model's shape; the\n component maps the consumer's `SchedulerException` onto this).\n\n```ts\nexport type RecurrenceException = {\n occurrenceStart: DateLike\n deleted?: boolean\n start?: DateLike | null\n end?: DateLike | null\n title?: string\n allDay?: boolean\n /** Per-occurrence overrides for any other field, merged over the row for just\n * this occurrence (attendees, calendar, color, resource, ...). */\n fields?: Record<string, unknown>\n}\n```\n\n### `type EventSpec`\n\nField accessors the model uses to read an event off a row. The component\n builds this from `SchedulerConfig`, applying its move/edit overlay first so\n a dragged event resolves at its new time without mutating the source row.\n\n```ts\nexport type EventSpec<TData> = {\n getKey: (row: TData) => string\n getStart: (row: TData) => DateLike | null | undefined\n getEnd?: (row: TData) => DateLike | null | undefined\n getAllDay?: (row: TData) => boolean\n getTitle?: (row: TData) => string\n getColor?: (row: TData) => string | undefined\n /** Optional secondary accent color (rendered as a left strip). */\n getSecondaryColor?: (row: TData) => string | undefined\n /** Optional free/busy status. */\n getStatus?: (row: TData) => string | undefined\n getResource?: (row: TData) => string | undefined\n getRecurrence?: (\n row: TData,\n ) => RecurrenceRule | ReadonlyArray<RecurrenceRule> | null | undefined\n /** Per-occurrence overrides for a recurring row (deleted / moved / edited). */\n getExceptions?: (row: TData) => ReadonlyArray<RecurrenceException> | null | undefined\n /** Fallback event length (minutes) when a row has a start but no end. Default 60. */\n defaultDurationMin?: number\n}\n```\n\n### `type WorkingWindow`\n\nOne working window: `[start, end)` hours, optionally limited to `days`\n (weekday 0 = Sun … 6 = Sat). Omitting `days` applies it to every day.\n\n```ts\nexport type WorkingWindow = {\n days?: ReadonlyArray<number>\n start: number\n end: number\n}\n```\n\n### `function workingIntervals`\n\nThe working `[startMin, endMin]` intervals for `weekday`, from `windows`,\nclamped to `[bandStartMin, bandEndMin]` and merged. Empty = the whole day is\noff. Pure; used for per-resource availability shading + enforcement.\n\n```ts\nexport function workingIntervals(\n weekday: number,\n windows: ReadonlyArray<WorkingWindow>,\n bandStartMin: number,\n bandEndMin: number,\n): Array<[number, number]> {\n const raw: Array<[number, number]> = []\n for (const w of windows) {\n if (w.days && !w.days.includes(weekday)) continue\n const s = Math.max(bandStartMin, w.start * 60)\n const e = Math.min(bandEndMin, w.end * 60)\n if (e > s) raw.push([s, e])\n }\n raw.sort((a, b) => a[0] - b[0])\n const merged: Array<[number, number]> = []\n for (const iv of raw) {\n const last = merged[merged.length - 1]\n if (last && iv[0] <= last[1]) last[1] = Math.max(last[1], iv[1])\n else merged.push([iv[0], iv[1]])\n }\n return merged\n}\n```\n\n### `function withinWorking`\n\nTrue when `[startMin, endMin]` lies wholly inside one working interval.\n\n```ts\nexport function withinWorking(\n startMin: number,\n endMin: number,\n intervals: ReadonlyArray<readonly [number, number]>,\n): boolean {\n return intervals.some(([a, b]) => startMin >= a && endMin <= b)\n}\n```\n\n### `function hasConflict`\n\nTrue when placing `[start,end]` on `resourceId` would overlap another event on\nthe SAME resource (ignoring the event identified by `excludeRowKey`). Used to\nenforce `disableConflicts` (no double-booking). All-day/timed both count.\n\n```ts\nexport function hasConflict<TData>(\n start: Date,\n end: Date,\n resourceId: string | undefined,\n events: ReadonlyArray<ResolvedEvent<TData>>,\n excludeRowKey?: string,\n): boolean {\n for (const e of events) {\n if (e.rowKey === excludeRowKey) continue\n if ((e.resourceId ?? undefined) !== (resourceId ?? undefined)) continue\n if (rangesOverlap(start, end, e.start, e.end)) return true\n }\n return false\n}\n```\n\n### `function overlapCount`\n\nHow many events on the SAME resource overlap `[start,end]` (excluding\n`excludeRowKey`). Used to enforce `maxEventsPerSlot` (resource capacity): a\nmove/create is blocked when this count would reach the cap.\n\n```ts\nexport function overlapCount<TData>(\n start: Date,\n end: Date,\n resourceId: string | undefined,\n events: ReadonlyArray<ResolvedEvent<TData>>,\n excludeRowKey?: string,\n): number {\n let n = 0\n for (const e of events) {\n if (e.rowKey === excludeRowKey) continue\n if ((e.resourceId ?? undefined) !== (resourceId ?? undefined)) continue\n if (rangesOverlap(start, end, e.start, e.end)) n++\n }\n return n\n}\n```\n\n### `function overlapsBands`\n\nTrue when the minute range `[sMin,eMin)` overlaps any of the given hour bands.\n\n```ts\nexport function overlapsBands(\n sMin: number,\n eMin: number,\n bands: ReadonlyArray<{ start: number; end: number }>,\n): boolean {\n for (const b of bands) {\n if (sMin < b.end * 60 && eMin > b.start * 60) return true\n }\n return false\n}\n```\n\n### `function resolveEvents`\n\nResolve `rows` into the event instances visible in `[rangeStart, rangeEnd]`.\nRecurring rows are expanded to one instance per matching day (keeping the base\nevent's time-of-day and duration); single rows are included when they overlap\nthe window. Result is sorted by start (all-day first within a start).\n\n```ts\nexport function resolveEvents<TData>(\n rows: ReadonlyArray<TData>,\n spec: EventSpec<TData>,\n rangeStart: Date,\n rangeEnd: Date,\n): ResolvedEvent<TData>[] {\n const defDur = Math.max(1, spec.defaultDurationMin ?? 60)\n const out: ResolvedEvent<TData>[] = []\n\n for (const row of rows) {\n const start = toDate(spec.getStart(row))\n if (!start) continue\n const rawEnd = spec.getEnd ? toDate(spec.getEnd(row)) : null\n const end =\n rawEnd && rawEnd.getTime() > start.getTime()\n ? rawEnd\n : new Date(start.getTime() + defDur * MS_MIN)\n const durationMs = end.getTime() - start.getTime()\n\n const rowKey = spec.getKey(row)\n const title = spec.getTitle?.(row) ?? ''\n const allDay = spec.getAllDay?.(row) ?? false\n const color = spec.getColor?.(row)\n const color2 = spec.getSecondaryColor?.(row)\n const status = spec.getStatus?.(row)\n const resourceId = spec.getResource?.(row)\n const rule = spec.getRecurrence?.(row)\n\n if (rule) {\n // One instance per matching day, carrying the base time-of-day + duration.\n // Recurrence begins at the event's OWN start - never emit an occurrence\n // before it, so clip the expansion's lower bound to the start date (a rule\n // like \"weekly on Mon-Fri\" must not back-fill days before the event began).\n const from = start.getTime() > rangeStart.getTime() ? start : rangeStart\n const days = expandRecurrence(rule, from, rangeEnd)\n // Per-occurrence overrides keyed by the occurrence's canonical start time.\n const exs = spec.getExceptions?.(row)\n const exMap = exs?.length\n ? new Map(exs.map((e) => [toDate(e.occurrenceStart)?.getTime() ?? NaN, e]))\n : null\n for (const day of days) {\n const occStart = allDay ? startOfDay(day) : withTime(day, start)\n const ex = exMap?.get(occStart.getTime())\n if (ex?.deleted) continue // this occurrence was removed\n let iStart = occStart\n let iEnd = new Date(occStart.getTime() + durationMs)\n let iTitle = title\n let iAllDay = allDay\n // Per-occurrence overrides of ANY other field: merge onto a copy of the\n // row for this instance, then re-derive the surfaced props from it so a\n // \"This event\" change to attendees / calendar / color / resource shows.\n let iRow = row\n let iColor = color\n let iColor2 = color2\n let iStatus = status\n let iResource = resourceId\n if (ex) {\n const exS = toDate(ex.start)\n const exE = toDate(ex.end)\n if (exS) {\n iStart = exS\n iEnd = exE && exE.getTime() > exS.getTime() ? exE : new Date(exS.getTime() + durationMs)\n } else if (exE) {\n iEnd = exE\n }\n if (ex.title != null) iTitle = ex.title\n if (ex.allDay != null) iAllDay = ex.allDay\n if (ex.fields) {\n iRow = { ...(row as Record<string, unknown>), ...ex.fields } as TData\n iColor = spec.getColor?.(iRow) ?? color\n iColor2 = spec.getSecondaryColor?.(iRow) ?? color2\n iStatus = spec.getStatus?.(iRow) ?? status\n iResource = spec.getResource?.(iRow) ?? resourceId\n if (ex.title == null) iTitle = spec.getTitle?.(iRow) ?? iTitle\n }\n }\n if (!rangesOverlap(iStart, iEnd, rangeStart, rangeEnd)) continue\n out.push({\n // Key on the CANONICAL occurrence start so a moved occurrence keeps its identity.\n key: `${rowKey}#${occStart.getFullYear()}-${occStart.getMonth() + 1}-${occStart.getDate()}T${occStart.getHours()}:${occStart.getMinutes()}`,\n rowKey,\n row: iRow,\n title: iTitle,\n start: iStart,\n end: iEnd,\n allDay: iAllDay,\n color: iColor,\n color2: iColor2,\n status: iStatus,\n resourceId: iResource,\n recurring: true,\n occurrenceStart: occStart,\n isException: !!ex,\n })\n }\n } else if (rangesOverlap(start, end, rangeStart, rangeEnd)) {\n out.push({\n key: rowKey,\n rowKey,\n row,\n title,\n start,\n end,\n allDay,\n color,\n color2,\n status,\n resourceId,\n recurring: false,\n })\n }\n }\n\n out.sort((a, b) => {\n const d = a.start.getTime() - b.start.getTime()\n if (d !== 0) return d\n if (a.allDay !== b.allDay) return a.allDay ? -1 : 1\n return a.end.getTime() - b.end.getTime()\n })\n return out\n}\n```\n\n### `function eventsOnDay`\n\nEvents that touch `day` (any calendar day the event spans), timed + all-day.\n\n```ts\nexport function eventsOnDay<TData>(\n events: ReadonlyArray<ResolvedEvent<TData>>,\n day: Date,\n): ResolvedEvent<TData>[] {\n const dayStart = startOfDay(day)\n const dayEnd = addDays(dayStart, 1)\n return events.filter((e) => rangesOverlap(e.start, e.end, dayStart, dayEnd))\n}\n```\n\n### `type MonthSegment`\n\nA continuous month-view bar for one event within one week row: the columns it\nspans (`startCol`..`endCol`, 0-6) and the `lane` (stack row) it sits in. Events\nthat cross a week boundary are split into one segment per week (with\n`continuesLeft`/`continuesRight` flags so the view can flatten that edge).\n\n```ts\nexport type MonthSegment<TData = unknown> = {\n event: ResolvedEvent<TData>\n startCol: number\n endCol: number\n lane: number\n continuesLeft: boolean\n continuesRight: boolean\n}\n```\n\n### `function monthWeekSegments`\n\nLay out one week row of the month grid as continuous spanning bars. `weekStart`\nis the local-midnight first day of the 7-day row. Returns each overlapping\nevent as a {@link MonthSegment} clipped to the week, with greedy lane packing\nso bars never overlap, plus the total `laneCount`.\n\n```ts\nexport function monthWeekSegments<TData>(\n events: ReadonlyArray<ResolvedEvent<TData>>,\n weekStart: Date,\n): { segments: MonthSegment<TData>[]; laneCount: number } {\n const ws = startOfDay(weekStart)\n const we = addDays(ws, 7)\n const colOf = (d: Date) => Math.floor((startOfDay(d).getTime() - ws.getTime()) / MS_DAY)\n\n const out: MonthSegment<TData>[] = []\n for (const e of events) {\n const firstDay = startOfDay(e.start)\n // Last covered day: the day of (end - 1ms), so an end at exact midnight does\n // not spill onto the next day. Guard against zero/negative-length events.\n const lastDay = startOfDay(new Date(Math.max(e.start.getTime(), e.end.getTime() - 1)))\n if (lastDay.getTime() < ws.getTime() || firstDay.getTime() >= we.getTime()) continue\n const startCol = Math.max(0, colOf(firstDay))\n const endCol = Math.min(6, colOf(lastDay))\n if (endCol < startCol) continue\n out.push({\n event: e,\n startCol,\n endCol,\n lane: 0,\n continuesLeft: firstDay.getTime() < ws.getTime(),\n continuesRight: lastDay.getTime() >= we.getTime(),\n })\n }\n\n // Order: earliest start, then longest, then all-day before timed, then start time.\n out.sort(\n (a, b) =>\n a.startCol - b.startCol ||\n b.endCol - b.startCol - (a.endCol - a.startCol) ||\n (a.event.allDay === b.event.allDay\n ? a.event.start.getTime() - b.event.start.getTime()\n : a.event.allDay\n ? -1\n : 1),\n )\n\n // Greedy lane packing: a lane tracks the last column it is occupied through.\n const laneEnd: number[] = []\n for (const seg of out) {\n let lane = 0\n for (; lane < laneEnd.length; lane++) if (seg.startCol > (laneEnd[lane] ?? -1)) break\n laneEnd[lane] = seg.endCol\n seg.lane = lane\n }\n return { segments: out, laneCount: laneEnd.length }\n}\n```\n\n### `type PositionedEvent`\n\nA timed event positioned within a time-grid column. `topPct`/`heightPct` are\n 0-100 of the visible day; `leftPct`/`widthPct`/`zIndex` place it horizontally\n among overlapping peers (already resolved for the chosen collision mode).\n\n```ts\nexport type PositionedEvent<TData = unknown> = {\n event: ResolvedEvent<TData>\n topPct: number\n heightPct: number\n col: number\n colCount: number\n leftPct: number\n widthPct: number\n zIndex: number\n}\n```\n\n### `type OverflowMarker`\n\nA `+N more` tile emitted by `cap` mode for the events that didn't fit.\n\n```ts\nexport type OverflowMarker<TData = unknown> = {\n topPct: number\n heightPct: number\n leftPct: number\n widthPct: number\n /** Number of hidden events this tile stands for. */\n count: number\n /** The hidden events (chronological), for the \"+N more\" popover. */\n events: ResolvedEvent<TData>[]\n}\n```\n\n### `type DayLayout`\n\nThe full time-grid layout for one day: positioned events + any overflow tiles.\n\n```ts\nexport type DayLayout<TData = unknown> = {\n events: PositionedEvent<TData>[]\n overflows: OverflowMarker<TData>[]\n}\n```\n\n### `type LayoutOptions`\n\nTuning for event layout: how overlapping events share horizontal space.\n\n```ts\nexport type LayoutOptions = {\n dayStartHour?: number\n dayEndHour?: number\n /** Collision layout mode. Default `split`. */\n mode?: SchedulerCollisionMode\n /** `cap` mode: max columns before overflow (min 2). Default 3. */\n maxColumns?: number\n /** `stack` mode: horizontal offset per overlapping event, in % of column. */\n stackOffsetPct?: number\n /** `stack` mode: the narrowest a stacked event may get, in % of column. */\n stackMinWidthPct?: number\n}\n```\n\n### `function layoutDayEvents`\n\nLay out the timed events of a single day for the time-grid, resolving\ncollisions per {@link SchedulerCollisionMode}. `dayStartHour`/`dayEndHour`\nbound the visible band (e.g. 8..18); events are clamped to it. All-day events\nare ignored here (the view renders them in a separate all-day row).\n\n```ts\nexport function layoutDayEvents<TData>(\n dayEvents: ReadonlyArray<ResolvedEvent<TData>>,\n day: Date,\n opts: LayoutOptions = {},\n): DayLayout<TData> {\n const dayStartHour = opts.dayStartHour ?? 0\n const dayEndHour = opts.dayEndHour ?? 24\n const mode = opts.mode ?? 'split'\n const maxColumns = Math.max(2, Math.floor(opts.maxColumns ?? 3))\n const stackOffset = opts.stackOffsetPct ?? 14\n const stackMinWidth = opts.stackMinWidthPct ?? 42\n\n const base = startOfDay(day)\n const bandStartMin = dayStartHour * 60\n const bandEndMin = dayEndHour * 60\n const bandLen = Math.max(1, bandEndMin - bandStartMin)\n\n type Item = { event: ResolvedEvent<TData>; startMin: number; endMin: number; col: number }\n const items: Item[] = []\n for (const e of dayEvents) {\n if (e.allDay) continue\n const s = Math.max(bandStartMin, (e.start.getTime() - base.getTime()) / MS_MIN)\n const en = Math.min(bandEndMin, (e.end.getTime() - base.getTime()) / MS_MIN)\n if (en <= bandStartMin || s >= bandEndMin) continue\n items.push({ event: e, startMin: s, endMin: Math.max(s + 1, en), col: 0 })\n }\n items.sort((a, b) => a.startMin - b.startMin || a.endMin - b.endMin)\n\n const events: PositionedEvent<TData>[] = []\n const overflows: OverflowMarker<TData>[] = []\n const topOf = (min: number) => ((min - bandStartMin) / bandLen) * 100\n const heightOf = (a: number, b: number) => ((b - a) / bandLen) * 100\n const maxStackShift = Math.max(0, Math.floor((100 - stackMinWidth) / stackOffset))\n\n // Walk clusters of transitively-overlapping events; within each cluster assign\n // greedy columns, then resolve horizontal geometry for the chosen mode.\n let cluster: Item[] = []\n let clusterEnd = -Infinity\n const flush = () => {\n if (!cluster.length) return\n const colEnds: number[] = []\n for (const it of cluster) {\n let c = 0\n for (; c < colEnds.length; c++) if (it.startMin >= (colEnds[c] ?? Infinity)) break\n colEnds[c] = it.endMin\n it.col = c\n }\n const colCount = colEnds.length\n\n if (mode === 'stack' && colCount > 1) {\n for (const it of cluster) {\n const shift = Math.min(it.col, maxStackShift) * stackOffset\n events.push({\n event: it.event,\n topPct: topOf(it.startMin),\n heightPct: heightOf(it.startMin, it.endMin),\n col: it.col,\n colCount,\n leftPct: shift,\n widthPct: 100 - shift,\n zIndex: it.col + 1,\n })\n }\n } else if (mode === 'cap' && colCount > maxColumns) {\n const realCols = maxColumns - 1 // reserve the last visible slot for overflow\n const hidden: Item[] = []\n for (const it of cluster) {\n if (it.col < realCols) {\n events.push({\n event: it.event,\n topPct: topOf(it.startMin),\n heightPct: heightOf(it.startMin, it.endMin),\n col: it.col,\n colCount: maxColumns,\n leftPct: (it.col / maxColumns) * 100,\n widthPct: 100 / maxColumns,\n zIndex: 1,\n })\n } else {\n hidden.push(it)\n }\n }\n if (hidden.length) {\n const start = Math.min(...hidden.map((h) => h.startMin))\n const end = Math.max(...hidden.map((h) => h.endMin))\n overflows.push({\n topPct: topOf(start),\n heightPct: heightOf(start, end),\n leftPct: (realCols / maxColumns) * 100,\n widthPct: 100 / maxColumns,\n count: hidden.length,\n events: hidden.map((h) => h.event),\n })\n }\n } else {\n // split (and cap when the cluster fits within maxColumns): each event\n // starts in its greedy column, then EXPANDS rightward across any columns\n // that hold no event overlapping it in time - so an event with free space\n // beside it fills the gap instead of staying a narrow 1/colCount sliver.\n for (const it of cluster) {\n let span = 1\n for (let c = it.col + 1; c < colCount; c++) {\n const blocked = cluster.some(\n (o) => o !== it && o.col === c && o.startMin < it.endMin && o.endMin > it.startMin,\n )\n if (blocked) break\n span++\n }\n events.push({\n event: it.event,\n topPct: topOf(it.startMin),\n heightPct: heightOf(it.startMin, it.endMin),\n col: it.col,\n colCount,\n leftPct: (it.col / colCount) * 100,\n widthPct: (span / colCount) * 100,\n zIndex: 1,\n })\n }\n }\n\n cluster = []\n clusterEnd = -Infinity\n }\n for (const it of items) {\n if (cluster.length && it.startMin >= clusterEnd) flush()\n cluster.push(it)\n clusterEnd = Math.max(clusterEnd, it.endMin)\n }\n flush()\n return { events, overflows }\n}\n```\n\n### `type AgendaGroup`\n\nOne day's bucket of events for the agenda (list) view.\n\n```ts\nexport type AgendaGroup<TData = unknown> = {\n day: Date\n events: ResolvedEvent<TData>[]\n}\n```\n\n### `function agendaGroups`\n\nGroup resolved events by calendar day for the agenda view (days with no\n events are omitted; groups and their events are in chronological order).\n\n```ts\nexport function agendaGroups<TData>(\n events: ReadonlyArray<ResolvedEvent<TData>>,\n): AgendaGroup<TData>[] {\n const groups: AgendaGroup<TData>[] = []\n for (const e of [...events].sort((a, b) => a.start.getTime() - b.start.getTime())) {\n const last = groups[groups.length - 1]\n if (last && isSameDay(last.day, e.start)) last.events.push(e)\n else groups.push({ day: startOfDay(e.start), events: [e] })\n }\n return groups\n}\n```\n\n### `function rangeForView`\n\nThe visible date window for a view anchored on `anchor`. Used both to size the\ngrid and to bound event resolution (recurrence expansion clips to it).\n`agendaDays` controls the agenda span (default 30).\n\n```ts\nexport function rangeForView(\n view: SchedulerView,\n anchor: Date,\n weekStartsOn = 0,\n agendaDays = 30,\n): { start: Date; end: Date } {\n switch (view) {\n case 'month': {\n const start = startOfWeek(startOfMonth(anchor), weekStartsOn)\n return { start, end: addDays(start, 42) } // fixed 6-week grid\n }\n case 'week': {\n const start = startOfWeek(anchor, weekStartsOn)\n return { start, end: addDays(start, 7) }\n }\n case 'day': {\n const start = startOfDay(anchor)\n return { start, end: addDays(start, 1) }\n }\n case 'agenda': {\n const start = startOfDay(anchor)\n return { start, end: addDays(start, Math.max(1, agendaDays)) }\n }\n case 'timelineDay':\n return { start: startOfDay(anchor), end: addDays(startOfDay(anchor), 1) }\n case 'timelineWeek': {\n const start = startOfWeek(anchor, weekStartsOn)\n return { start, end: addDays(start, 7) }\n }\n case 'timelineMonth': {\n const start = startOfMonth(anchor)\n return { start, end: startOfMonth(addMonths(anchor, 1)) }\n }\n case 'timelineYear': {\n const start = new Date(anchor.getFullYear(), 0, 1)\n return { start, end: new Date(anchor.getFullYear() + 1, 0, 1) }\n }\n }\n}\n```\n\n### `function daysForView`\n\nThe 7 (or fewer) day columns rendered for the week / day views.\n\n```ts\nexport function daysForView(view: SchedulerView, anchor: Date, weekStartsOn = 0): Date[] {\n if (view === 'day') return [startOfDay(anchor)]\n const start = startOfWeek(anchor, weekStartsOn)\n return Array.from({ length: 7 }, (_, i) => addDays(start, i))\n}\n```\n\n### `function navigateAnchor`\n\nMove the anchor one view-unit in `dir` (-1 back, +1 forward).\n\n```ts\nexport function navigateAnchor(view: SchedulerView, anchor: Date, dir: number): Date {\n switch (view) {\n case 'month':\n return addMonths(anchor, dir)\n case 'week':\n return addDays(anchor, 7 * dir)\n case 'day':\n return addDays(anchor, dir)\n case 'agenda':\n return addDays(anchor, 30 * dir)\n case 'timelineDay':\n return addDays(anchor, dir)\n case 'timelineWeek':\n return addDays(anchor, 7 * dir)\n case 'timelineMonth':\n return addMonths(anchor, dir)\n case 'timelineYear':\n return new Date(anchor.getFullYear() + dir, anchor.getMonth(), anchor.getDate())\n }\n}\n```\n\n### `type TimelineTick`\n\nOne column of the timeline's minor (tick) header row.\n\n```ts\nexport type TimelineTick = {\n start: Date\n end: Date\n leftPct: number\n widthPct: number\n label: string\n today: boolean\n}\n```\n\n### `type TimelineMajor`\n\nOne cell of the timeline's major (grouping) header row, spanning several ticks.\n\n```ts\nexport type TimelineMajor = { label: string; leftPct: number; widthPct: number }\n```\n\n### `type TimelineAxis`\n\nThe horizontal axis: its window [start, end] (the day band for `timelineDay`),\n the minor `ticks`, and the coarser `majors` above them.\n\n```ts\nexport type TimelineAxis = {\n start: Date\n end: Date\n totalMs: number\n ticks: TimelineTick[]\n majors: TimelineMajor[]\n}\n```\n\n### `function timelineAxis`\n\nBuild the timeline header axis for `view` over `[rangeStart, rangeEnd]`. For\n`timelineDay` the axis is clamped to the `dayStartHour..dayEndHour` band (so\nevents outside it clip, matching the vertical day view). Ticks are hours (day),\ndays (week / month) or months (year); majors are the date, the month(s), or\nquarters. All geometry is percentage of the axis window.\n\n```ts\nexport function timelineAxis(\n view: SchedulerView,\n rangeStart: Date,\n rangeEnd: Date,\n opts: { dayStartHour?: number; dayEndHour?: number; today?: Date | null } = {},\n): TimelineAxis {\n const dayStartHour = opts.dayStartHour ?? 0\n const dayEndHour = opts.dayEndHour ?? 24\n const today = opts.today ? startOfDay(opts.today) : null\n const isToday = (d: Date) => (today ? isSameDay(d, today) : false)\n\n let start = rangeStart\n let end = rangeEnd\n if (view === 'timelineDay') {\n start = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate(), dayStartHour)\n end = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate(), 0, 0, 0, 0)\n end = new Date(end.getTime() + dayEndHour * 3_600_000)\n }\n const total = Math.max(1, end.getTime() - start.getTime())\n const base = start.getTime()\n const mk = (s: Date, e: Date, label: string): TimelineTick => ({\n start: s,\n end: e,\n leftPct: ((s.getTime() - base) / total) * 100,\n widthPct: ((e.getTime() - s.getTime()) / total) * 100,\n label,\n today: isToday(s),\n })\n\n const ticks: TimelineTick[] = []\n let majors: TimelineMajor[] = []\n\n if (view === 'timelineDay') {\n for (let h = dayStartHour; h < dayEndHour; h++) {\n const s = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate(), h)\n ticks.push(mk(s, new Date(s.getTime() + 3_600_000), tlHourLabel(h)))\n }\n majors = [\n { label: `${TL_WD[rangeStart.getDay()]}, ${TL_MO[rangeStart.getMonth()]} ${rangeStart.getDate()}`, leftPct: 0, widthPct: 100 },\n ]\n } else if (view === 'timelineWeek' || view === 'timelineMonth') {\n let cur = startOfDay(start)\n while (cur.getTime() < end.getTime()) {\n const nxt = addDays(cur, 1)\n const label = view === 'timelineWeek' ? `${TL_WD[cur.getDay()]} ${cur.getDate()}` : `${cur.getDate()}`\n ticks.push(mk(cur, nxt, label))\n cur = nxt\n }\n majors = groupMajors(\n ticks,\n (t) => `${t.start.getFullYear()}-${t.start.getMonth()}`,\n (t) => `${TL_MO[t.start.getMonth()]} ${t.start.getFullYear()}`,\n )\n } else if (view === 'timelineYear') {\n const y = rangeStart.getFullYear()\n for (let m = 0; m < 12; m++) {\n ticks.push(mk(new Date(y, m, 1), new Date(y, m + 1, 1), TL_MO[m]!))\n }\n majors = groupMajors(\n ticks,\n (t) => `${Math.floor(t.start.getMonth() / 3)}`,\n (t) => `Q${Math.floor(t.start.getMonth() / 3) + 1} ${t.start.getFullYear()}`,\n )\n }\n\n return { start, end, totalMs: total, ticks, majors }\n}\n```\n\n### `function timelineGeom`\n\nAn event's horizontal geometry within the axis window, or `null` when it\n falls entirely outside it. `continuesLeft/Right` flag a clipped edge.\n\n```ts\nexport function timelineGeom(\n start: Date,\n end: Date,\n axisStart: Date,\n axisMs: number,\n): { leftPct: number; widthPct: number; continuesLeft: boolean; continuesRight: boolean } | null {\n const a = axisStart.getTime()\n const b = a + axisMs\n const s = Math.max(start.getTime(), a)\n const e = Math.min(end.getTime(), b)\n if (e <= a || s >= b || e <= s) return null\n return {\n leftPct: ((s - a) / axisMs) * 100,\n widthPct: ((e - s) / axisMs) * 100,\n continuesLeft: start.getTime() < a,\n continuesRight: end.getTime() > b,\n }\n}\n```\n\n### `type TimelineRow`\n\nOne resource's timeline row: its events lane-packed so overlaps stack.\n\n```ts\nexport type TimelineRow<TData = unknown> = {\n resource: SchedulerResource | null\n laneCount: number\n items: { event: ResolvedEvent<TData>; lane: number }[]\n}\n```\n\n### `function timelineRows`\n\nBucket `events` by resource into rows (a single `null` row when there are no\nresources), then greedily lane-pack each row so overlapping events stack. An\nevent whose `resourceId` matches no resource is dropped.\n\n```ts\nexport function timelineRows<TData>(\n resources: ReadonlyArray<SchedulerResource> | null | undefined,\n events: ReadonlyArray<ResolvedEvent<TData>>,\n): TimelineRow<TData>[] {\n const hasRes = !!(resources && resources.length)\n const rows = hasRes\n ? resources!.map((r) => ({ resource: r as SchedulerResource | null, evs: [] as ResolvedEvent<TData>[] }))\n : [{ resource: null as SchedulerResource | null, evs: [] as ResolvedEvent<TData>[] }]\n const byId = new Map<string | null, (typeof rows)[number]>()\n for (const r of rows) byId.set(r.resource?.id ?? null, r)\n\n for (const ev of events) {\n const row = hasRes ? byId.get(ev.resourceId ?? '') : rows[0]\n if (row) row.evs.push(ev)\n }\n\n return rows.map((r) => {\n const sorted = [...r.evs].sort((a, b) => a.start.getTime() - b.start.getTime() || a.end.getTime() - b.end.getTime())\n const laneEnd: number[] = []\n const items = sorted.map((event) => {\n let lane = 0\n for (; lane < laneEnd.length; lane++) if (event.start.getTime() >= (laneEnd[lane] ?? -Infinity)) break\n laneEnd[lane] = event.end.getTime()\n return { event, lane }\n })\n return { resource: r.resource, laneCount: Math.max(1, laneEnd.length), items }\n })\n}\n```\n"
8150
+ "markdown": "# `@svgrid/grid` · `scheduler-model.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\scheduler-model.ts`.\n\n### `type ResolvedEvent`\n\nA concrete event instance placed on the calendar (one row may yield many when\n it recurs). `key` is unique per instance; `rowKey` ties it back to its row.\n\n```ts\nexport type ResolvedEvent<TData = unknown> = {\n key: string\n rowKey: string\n row: TData\n title: string\n start: Date\n end: Date\n allDay: boolean\n color?: string\n /** Optional secondary accent (e.g. a category) shown as a left strip, distinct\n * from the main `color`. */\n color2?: string\n /** Free/busy status (busy | free | tentative | oof) for a distinct visual. */\n status?: string\n resourceId?: string\n /** True when this instance came from expanding a recurrence rule. */\n recurring: boolean\n /** For a recurring instance, its canonical (pre-override) occurrence start -\n * the identity used to key {@link RecurrenceException} overrides. */\n occurrenceStart?: Date\n /** True when a recurring instance carries a per-occurrence override. */\n isException?: boolean\n}\n```\n\n### `type RecurrenceException`\n\nA per-occurrence override of a recurring event (the model's shape; the\n component maps the consumer's `SchedulerException` onto this).\n\n```ts\nexport type RecurrenceException = {\n occurrenceStart: DateLike\n deleted?: boolean\n start?: DateLike | null\n end?: DateLike | null\n title?: string\n allDay?: boolean\n /** Per-occurrence overrides for any other field, merged over the row for just\n * this occurrence (attendees, calendar, color, resource, ...). */\n fields?: Record<string, unknown>\n}\n```\n\n### `type EventSpec`\n\nField accessors the model uses to read an event off a row. The component\n builds this from `SchedulerConfig`, applying its move/edit overlay first so\n a dragged event resolves at its new time without mutating the source row.\n\n```ts\nexport type EventSpec<TData> = {\n getKey: (row: TData) => string\n getStart: (row: TData) => DateLike | null | undefined\n getEnd?: (row: TData) => DateLike | null | undefined\n getAllDay?: (row: TData) => boolean\n getTitle?: (row: TData) => string\n getColor?: (row: TData) => string | undefined\n /** Optional secondary accent color (rendered as a left strip). */\n getSecondaryColor?: (row: TData) => string | undefined\n /** Optional free/busy status. */\n getStatus?: (row: TData) => string | undefined\n getResource?: (row: TData) => string | undefined\n getRecurrence?: (\n row: TData,\n ) => RecurrenceRule | ReadonlyArray<RecurrenceRule> | null | undefined\n /** Per-occurrence overrides for a recurring row (deleted / moved / edited). */\n getExceptions?: (row: TData) => ReadonlyArray<RecurrenceException> | null | undefined\n /** Fallback event length (minutes) when a row has a start but no end. Default 60. */\n defaultDurationMin?: number\n}\n```\n\n### `type WorkingWindow`\n\nOne working window: `[start, end)` hours, optionally limited to `days`\n (weekday 0 = Sun … 6 = Sat). Omitting `days` applies it to every day.\n\n```ts\nexport type WorkingWindow = {\n days?: ReadonlyArray<number>\n start: number\n end: number\n}\n```\n\n### `function workingIntervals`\n\nThe working `[startMin, endMin]` intervals for `weekday`, from `windows`,\nclamped to `[bandStartMin, bandEndMin]` and merged. Empty = the whole day is\noff. Pure; used for per-resource availability shading + enforcement.\n\n```ts\nexport function workingIntervals(\n weekday: number,\n windows: ReadonlyArray<WorkingWindow>,\n bandStartMin: number,\n bandEndMin: number,\n): Array<[number, number]>\n```\n\n### `function withinWorking`\n\nTrue when `[startMin, endMin]` lies wholly inside one working interval.\n\n```ts\nexport function withinWorking(\n startMin: number,\n endMin: number,\n intervals: ReadonlyArray<readonly [number, number]>,\n): boolean\n```\n\n### `function hasConflict`\n\nTrue when placing `[start,end]` on `resourceId` would overlap another event on\nthe SAME resource (ignoring the event identified by `excludeRowKey`). Used to\nenforce `disableConflicts` (no double-booking). All-day/timed both count.\n\n```ts\nexport function hasConflict<TData>(\n start: Date,\n end: Date,\n resourceId: string | undefined,\n events: ReadonlyArray<ResolvedEvent<TData>>,\n excludeRowKey?: string,\n): boolean\n```\n\n### `function overlapCount`\n\nHow many events on the SAME resource overlap `[start,end]` (excluding\n`excludeRowKey`). Used to enforce `maxEventsPerSlot` (resource capacity): a\nmove/create is blocked when this count would reach the cap.\n\n```ts\nexport function overlapCount<TData>(\n start: Date,\n end: Date,\n resourceId: string | undefined,\n events: ReadonlyArray<ResolvedEvent<TData>>,\n excludeRowKey?: string,\n): number\n```\n\n### `function overlapsBands`\n\nTrue when the minute range `[sMin,eMin)` overlaps any of the given hour bands.\n\n```ts\nexport function overlapsBands(\n sMin: number,\n eMin: number,\n bands: ReadonlyArray<{ start: number; end: number }>,\n): boolean\n```\n\n### `function resolveEvents`\n\nResolve `rows` into the event instances visible in `[rangeStart, rangeEnd]`.\nRecurring rows are expanded to one instance per matching day (keeping the base\nevent's time-of-day and duration); single rows are included when they overlap\nthe window. Result is sorted by start (all-day first within a start).\n\n```ts\nexport function resolveEvents<TData>(\n rows: ReadonlyArray<TData>,\n spec: EventSpec<TData>,\n rangeStart: Date,\n rangeEnd: Date,\n): ResolvedEvent<TData>[]\n```\n\n### `function eventsOnDay`\n\nEvents that touch `day` (any calendar day the event spans), timed + all-day.\n\n```ts\nexport function eventsOnDay<TData>(\n events: ReadonlyArray<ResolvedEvent<TData>>,\n day: Date,\n): ResolvedEvent<TData>[]\n```\n\n### `type MonthSegment`\n\nA continuous month-view bar for one event within one week row: the columns it\nspans (`startCol`..`endCol`, 0-6) and the `lane` (stack row) it sits in. Events\nthat cross a week boundary are split into one segment per week (with\n`continuesLeft`/`continuesRight` flags so the view can flatten that edge).\n\n```ts\nexport type MonthSegment<TData = unknown> = {\n event: ResolvedEvent<TData>\n startCol: number\n endCol: number\n lane: number\n continuesLeft: boolean\n continuesRight: boolean\n}\n```\n\n### `function monthWeekSegments`\n\nLay out one week row of the month grid as continuous spanning bars. `weekStart`\nis the local-midnight first day of the 7-day row. Returns each overlapping\nevent as a {@link MonthSegment} clipped to the week, with greedy lane packing\nso bars never overlap, plus the total `laneCount`.\n\n```ts\nexport function monthWeekSegments<TData>(\n events: ReadonlyArray<ResolvedEvent<TData>>,\n weekStart: Date,\n): { segments: MonthSegment<TData>[]; laneCount: number }\n```\n\n### `type PositionedEvent`\n\nA timed event positioned within a time-grid column. `topPct`/`heightPct` are\n 0-100 of the visible day; `leftPct`/`widthPct`/`zIndex` place it horizontally\n among overlapping peers (already resolved for the chosen collision mode).\n\n```ts\nexport type PositionedEvent<TData = unknown> = {\n event: ResolvedEvent<TData>\n topPct: number\n heightPct: number\n col: number\n colCount: number\n leftPct: number\n widthPct: number\n zIndex: number\n}\n```\n\n### `type OverflowMarker`\n\nA `+N more` tile emitted by `cap` mode for the events that didn't fit.\n\n```ts\nexport type OverflowMarker<TData = unknown> = {\n topPct: number\n heightPct: number\n leftPct: number\n widthPct: number\n /** Number of hidden events this tile stands for. */\n count: number\n /** The hidden events (chronological), for the \"+N more\" popover. */\n events: ResolvedEvent<TData>[]\n}\n```\n\n### `type DayLayout`\n\nThe full time-grid layout for one day: positioned events + any overflow tiles.\n\n```ts\nexport type DayLayout<TData = unknown> = {\n events: PositionedEvent<TData>[]\n overflows: OverflowMarker<TData>[]\n}\n```\n\n### `type LayoutOptions`\n\nTuning for event layout: how overlapping events share horizontal space.\n\n```ts\nexport type LayoutOptions = {\n dayStartHour?: number\n dayEndHour?: number\n /** Collision layout mode. Default `split`. */\n mode?: SchedulerCollisionMode\n /** `cap` mode: max columns before overflow (min 2). Default 3. */\n maxColumns?: number\n /** `stack` mode: horizontal offset per overlapping event, in % of column. */\n stackOffsetPct?: number\n /** `stack` mode: the narrowest a stacked event may get, in % of column. */\n stackMinWidthPct?: number\n}\n```\n\n### `function layoutDayEvents`\n\nLay out the timed events of a single day for the time-grid, resolving\ncollisions per {@link SchedulerCollisionMode}. `dayStartHour`/`dayEndHour`\nbound the visible band (e.g. 8..18); events are clamped to it. All-day events\nare ignored here (the view renders them in a separate all-day row).\n\n```ts\nexport function layoutDayEvents<TData>(\n dayEvents: ReadonlyArray<ResolvedEvent<TData>>,\n day: Date,\n opts: LayoutOptions = {},\n): DayLayout<TData>\n```\n\n### `type AgendaGroup`\n\nOne day's bucket of events for the agenda (list) view.\n\n```ts\nexport type AgendaGroup<TData = unknown> = {\n day: Date\n events: ResolvedEvent<TData>[]\n}\n```\n\n### `function agendaGroups`\n\nGroup resolved events by calendar day for the agenda view (days with no\n events are omitted; groups and their events are in chronological order).\n\n```ts\nexport function agendaGroups<TData>(\n events: ReadonlyArray<ResolvedEvent<TData>>,\n): AgendaGroup<TData>[]\n```\n\n### `function rangeForView`\n\nThe visible date window for a view anchored on `anchor`. Used both to size the\ngrid and to bound event resolution (recurrence expansion clips to it).\n`agendaDays` controls the agenda span (default 30).\n\n```ts\nexport function rangeForView(\n view: SchedulerView,\n anchor: Date,\n weekStartsOn = 0,\n agendaDays = 30,\n): { start: Date; end: Date }\n```\n\n### `function daysForView`\n\nThe 7 (or fewer) day columns rendered for the week / day views.\n\n```ts\nexport function daysForView(view: SchedulerView, anchor: Date, weekStartsOn = 0): Date[]\n```\n\n### `function navigateAnchor`\n\nMove the anchor one view-unit in `dir` (-1 back, +1 forward).\n\n```ts\nexport function navigateAnchor(view: SchedulerView, anchor: Date, dir: number): Date\n```\n\n### `type TimelineTick`\n\nOne column of the timeline's minor (tick) header row.\n\n```ts\nexport type TimelineTick = {\n start: Date\n end: Date\n leftPct: number\n widthPct: number\n label: string\n today: boolean\n}\n```\n\n### `type TimelineMajor`\n\nOne cell of the timeline's major (grouping) header row, spanning several ticks.\n\n```ts\nexport type TimelineMajor = { label: string; leftPct: number; widthPct: number }\n```\n\n### `type TimelineAxis`\n\nThe horizontal axis: its window [start, end] (the day band for `timelineDay`),\n the minor `ticks`, and the coarser `majors` above them.\n\n```ts\nexport type TimelineAxis = {\n start: Date\n end: Date\n totalMs: number\n ticks: TimelineTick[]\n majors: TimelineMajor[]\n}\n```\n\n### `function timelineAxis`\n\nBuild the timeline header axis for `view` over `[rangeStart, rangeEnd]`. For\n`timelineDay` the axis is clamped to the `dayStartHour..dayEndHour` band (so\nevents outside it clip, matching the vertical day view). Ticks are hours (day),\ndays (week / month) or months (year); majors are the date, the month(s), or\nquarters. All geometry is percentage of the axis window.\n\n```ts\nexport function timelineAxis(\n view: SchedulerView,\n rangeStart: Date,\n rangeEnd: Date,\n opts: { dayStartHour?: number; dayEndHour?: number; today?: Date | null } = {},\n): TimelineAxis\n```\n\n### `function timelineGeom`\n\nAn event's horizontal geometry within the axis window, or `null` when it\n falls entirely outside it. `continuesLeft/Right` flag a clipped edge.\n\n```ts\nexport function timelineGeom(\n start: Date,\n end: Date,\n axisStart: Date,\n axisMs: number,\n): { leftPct: number; widthPct: number; continuesLeft: boolean; continuesRight: boolean } | null\n```\n\n### `type TimelineRow`\n\nOne resource's timeline row: its events lane-packed so overlaps stack.\n\n```ts\nexport type TimelineRow<TData = unknown> = {\n resource: SchedulerResource | null\n laneCount: number\n items: { event: ResolvedEvent<TData>; lane: number }[]\n}\n```\n\n### `function timelineRows`\n\nBucket `events` by resource into rows (a single `null` row when there are no\nresources), then greedily lane-pack each row so overlapping events stack. An\nevent whose `resourceId` matches no resource is dropped.\n\n```ts\nexport function timelineRows<TData>(\n resources: ReadonlyArray<SchedulerResource> | null | undefined,\n events: ReadonlyArray<ResolvedEvent<TData>>,\n): TimelineRow<TData>[]\n```\n"
8080
8151
  },
8081
8152
  {
8082
8153
  "slug": "reference/auto/svgrid-grid-server-block-cache",
8083
8154
  "path": "docs/reference/auto/svgrid-grid-server-block-cache.md",
8084
8155
  "title": "@svgrid/grid · server-block-cache.ts",
8085
8156
  "section": "API reference",
8086
- "markdown": "# `@svgrid/grid` · `server-block-cache.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\server-block-cache.ts`.\n\n### `function rowPlaceholderState`\n\nWhy a row is not real data, or `null` when it is.\n\nDeliberately NOT an identity check. The sentinels are shared objects, so\n`row === LOADING_ROW` looks like the obvious test - but rows routinely\narrive here through something that wrapped them. Svelte is the everyday\ncase: assigning the controller state into `$state` makes the row array\ndeeply reactive, and every row read back out is a proxy of the original.\nIdentity fails, every placeholder reads as real data, and the grid renders\na screen of blank rows instead of skeletons. Reading the mark works through\nany wrapper that forwards property access, which is all of them.\n\n```ts\nexport function rowPlaceholderState(row: unknown): 'loading' | 'failed' | null {\n if (row == null || typeof row !== 'object') return null\n const mark = (row as Record<symbol, unknown>)[PLACEHOLDER]\n return mark === 'loading' || mark === 'failed' ? mark : null\n}\n```\n\n### `function createRowPlaceholder`\n\nMint a frozen placeholder the grid will recognise, carrying whatever\nother fields the caller wants on it. The row model uses this to give its\nplaceholders a `kind`, so code reading display rows and code reading grid\nrows agree on what they are looking at.\n\n```ts\nexport function createRowPlaceholder<T extends object>(\n state: 'loading' | 'failed',\n fields: T,\n): Readonly<T & { readonly [PLACEHOLDER]: 'loading' | 'failed' }> {\n return Object.freeze({ ...fields, [PLACEHOLDER]: state })\n}\n```\n\n### `type BlockFetchResult`\n\nWhat a block fetch has to answer with. `rowCount` is optional: see {@link BlockCacheOptions}.\n\n```ts\nexport type BlockFetchResult<TData> = {\n rows: ReadonlyArray<TData>\n /**\n * Total rows after filtering. Omit it (or send `-1`) when the backend cannot\n * count cheaply - the cache then discovers the end from the first short\n * block, and `lastRowKnown()` stays false until it does.\n */\n rowCount?: number\n}\n```\n\n### `type BlockCacheOptions`\n\nWhat a block cache is built from: block size, caps, debounce and the fetch.\n\n```ts\nexport type BlockCacheOptions<TData> = {\n /**\n * Rows per request. Bigger blocks mean fewer round trips and more wasted\n * rows when the user scrolls past; 100 is the usual compromise.\n */\n blockSize?: number\n /**\n * Keep at most this many loaded blocks. Blocks outside the viewport are\n * evicted least-recently-seen first, and scrolling back re-fetches them.\n * Unlimited by default, which is right until the dataset is big enough that\n * holding every visited block matters.\n */\n maxBlocksInCache?: number\n /** Requests open at once. Default 2. */\n maxConcurrentRequests?: number\n /**\n * Wait this long after the viewport settles before fetching. Non-zero values\n * stop a drag of the scrollbar from requesting every block it flies past.\n */\n blockLoadDebounceMs?: number\n /**\n * Rows to claim before anything is loaded, so the grid has a scrollbar (and\n * `scrollToRow` has somewhere to land) on the first paint. Default 1.\n */\n initialRowCount?: number\n /**\n * While the total is unknown, how many unloaded rows to keep past the last\n * loaded one. Scrolling into them is what asks for the next block. Default 1.\n */\n overflowRows?: number\n /** Fetch one block. Reject, or throw, to mark it failed. */\n fetch: (\n startRow: number,\n endRow: number,\n signal: AbortSignal,\n ) => Promise<BlockFetchResult<TData>>\n /** Called after any change to the rows, the count, or a block's state. */\n onChange: (cache: BlockCacheState) => void\n /**\n * How to coalesce `onChange`. Defaults to a microtask, so a burst of block\n * arrivals rebuilds the row array once. Pass `(fn) => fn()` in tests to make\n * every change synchronous.\n */\n schedule?: (flush: () => void) => void\n}\n```\n\n### `type BlockState`\n\nOne block's place in the world, for diagnostics and for tests.\n\n```ts\nexport type BlockState = {\n blockIndex: number\n startRow: number\n endRow: number\n status: 'loading' | 'loaded' | 'failed'\n /** Monotonic counter of when the viewport last covered this block. */\n lastTouched: number\n}\n```\n\n### `type BlockCacheState`\n\nOne block as `getCacheState()` reports it.\n\n```ts\nexport type BlockCacheState = {\n /** Rows after filtering, or `null` while the backend has not said. */\n rowCount: number | null\n /** False while the end of the data is still being discovered. */\n lastRowKnown: boolean\n /** True while at least one block is in flight. */\n loading: boolean\n /** Blocks whose fetch rejected. Empty unless something went wrong. */\n failedBlocks: number[]\n}\n```\n\n### `type BlockCache`\n\nA block cache: rows arrive in blocks as the viewport reaches them,\nplaceholders stand in until then, and blocks far from the viewport are\nevicted past the cap.\n\n```ts\nexport type BlockCache<TData> = {\n /**\n * Tell the cache which rows are on screen. Fetches what is missing (after\n * `blockLoadDebounceMs`) and marks those blocks as recently seen so eviction\n * spares them. Safe to call on every scroll frame.\n */\n setViewport(startIndex: number, endIndex: number): void\n /** The dense row array to hand the grid. Placeholders fill unloaded slots. */\n rows(): ReadonlyArray<TData>\n /**\n * The same rows as windowed data (see windowed-data.ts): `length` is the\n * row count and each entry is read through `getRow` when the grid asks for\n * it, so handing it over costs O(1) whatever the count. A new array per\n * change, like `rows()`.\n */\n windowedRows(): ReadonlyArray<TData>\n /** One row, without building the array. Returns a placeholder when unloaded. */\n getRow(index: number): TData | typeof LOADING_ROW | typeof FAILED_ROW\n rowCount(): number | null\n lastRowKnown(): boolean\n /** Re-fetch the blocks that failed. */\n retryFailed(): void\n /**\n * Re-fetch the failed block holding `rowIndex`, and only that one; the\n * Retry on a failed row. A row whose block has not failed is a no-op.\n */\n retryFailedAt(rowIndex: number): void\n /**\n * Re-fetch the loaded blocks in place, keeping the row count and scroll\n * position. What you want after a mutation lands on the server.\n */\n refresh(): void\n /** Drop everything and start over from the current viewport. */\n purge(): void\n /** Override the total, e.g. from a count endpoint that answered separately. */\n setRowCount(count: number | null, known?: boolean): void\n /**\n * Write rows straight into the cache from `startRow`, as if a fetch had\n * returned them, bypassing the datasource, the debounce and the\n * concurrency cap. `startRow` must sit on a block boundary. An explicit\n * `rowCount` settles the total; without one a short final slice does.\n */\n applyRows(startRow: number, rows: ReadonlyArray<TData>, rowCount?: number): void\n /** Replace one loaded row. No-op when its block is not loaded. */\n patch(index: number, row: TData): boolean\n /**\n * The index of the first LOADED row matching `predicate`, or -1. Rows\n * that are not loaded are not visited - a transaction addressed by id\n * can only touch what is in the cache.\n */\n findIndex(predicate: (row: TData, index: number) => boolean): number\n /**\n * Insert rows at an index and grow the count. Works within whichever\n * run of loaded blocks contains `index`; loaded blocks AFTER that run\n * are dropped, because their rows have shifted and will be re-fetched at\n * their new offsets. An index in an unloaded region grows the count\n * only (the rows exist; they arrive when scrolled to). Returns whether\n * the rows were placed in the cache.\n */\n insert(index: number, rows: ReadonlyArray<TData>): boolean\n /**\n * Remove `count` rows at an index and shrink the count, with the same\n * run semantics as `insert`. Returns how many rows were actually\n * removed from the cache.\n */\n remove(index: number, count?: number): number\n /** Every block the cache is holding, for `debug` output and tests. */\n getCacheState(): BlockState[]\n /** Abort what is in flight and stop emitting. Call on unmount. */\n dispose(): void\n}\n```\n\n### `function createBlockCache`\n\nBuild a block cache over a `fetch(startRow, endRow, signal)`. The free\ninfinite row model and the Enterprise server-side row model both run on\nit, one per level.\n\n```ts\nexport function createBlockCache<TData>(options: BlockCacheOptions<TData>): BlockCache<TData> {\n const blockSize = Math.max(1, options.blockSize ?? 100)\n const maxBlocks = options.maxBlocksInCache ?? Infinity\n const maxConcurrent = Math.max(1, options.maxConcurrentRequests ?? 2)\n const debounceMs = Math.max(0, options.blockLoadDebounceMs ?? 0)\n const initialRowCount = Math.max(0, options.initialRowCount ?? 1)\n const overflowRows = Math.max(0, options.overflowRows ?? 1)\n const schedule = options.schedule ?? defaultSchedule\n\n const blocks = new Map<number, Block<TData>>()\n /** Block indices waiting for a slot, in the order the viewport asked for them. */\n const queue: number[] = []\n let inFlight = 0\n let touchClock = 0\n let count: number | null = null\n let countKnown = false\n let disposed = false\n\n let viewStart = 0\n let viewEnd = 0\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n let emitScheduled = false\n let rowsCache: TData[] | null = null\n let windowedCache: TData[] | null = null\n\n const blockOf = (rowIndex: number): number => Math.floor(rowIndex / blockSize)\n const startOf = (blockIndex: number): number => blockIndex * blockSize\n\n /**\n * How many rows to claim we have.\n *\n * With a known count that is simply the count. Without one it is the last row\n * we have touched plus `overflowRows`, so there is always somewhere to scroll\n * that will ask for the next block - this is what makes the list grow as you\n * go rather than ending at the first unloaded row.\n */\n function currentLength(): number {\n if (countKnown && count != null) return count\n let highestEnd = 0\n let anySettled = false\n for (const b of blocks.values()) if (b.status !== 'loading') anySettled = true\n for (const [index, block] of blocks) {\n // A block in flight extends the list only once some block has settled.\n // Before that the list is `initialRowCount` long: the few skeleton\n // rows a level shows while it waits, not a hundred of them. The first\n // block failing says nothing about how long the list is either, so it\n // keeps those few rows (its Retry sits on them); a failed block further\n // in was scrolled to, so its slots stay and the scrollbar holds still.\n const end = block.status === 'loaded'\n ? startOf(index) + block.rows.length\n : block.status === 'failed'\n ? index === 0 ? 0 : startOf(index) + blockSize\n : anySettled\n ? startOf(index) + blockSize\n : 0\n if (end > highestEnd) highestEnd = end\n }\n if (!anySettled) return initialRowCount\n return Math.max(initialRowCount, highestEnd + overflowRows)\n }\n\n function state(): BlockCacheState {\n const failed: number[] = []\n for (const [index, block] of blocks) if (block.status === 'failed') failed.push(index)\n return {\n rowCount: countKnown ? count : null,\n lastRowKnown: countKnown,\n loading: inFlight > 0,\n failedBlocks: failed.sort((a, b) => a - b),\n }\n }\n\n /**\n * Something changed: forget the row array NOW, so a synchronous read after\n * a mutation sees the new state, and notify on the next tick, so a burst of\n * mutations notifies once. Every mutating path ends here.\n */\n function emit(): void {\n rowsCache = windowedCache = null // rebuilt lazily, on the next read\n if (disposed || emitScheduled) return\n emitScheduled = true\n schedule(() => {\n emitScheduled = false\n if (disposed) return\n options.onChange(state())\n })\n }\n\n function ensureBlock(blockIndex: number): void {\n if (disposed) return\n const existing = blocks.get(blockIndex)\n // Loading or loaded blocks are left alone; a failed one only retries when\n // asked, so a broken backend is not hammered once per scroll frame.\n if (existing) return\n if (queue.includes(blockIndex)) return\n queue.push(blockIndex)\n pump()\n }\n\n function pump(): void {\n while (!disposed && inFlight < maxConcurrent && queue.length > 0) {\n const blockIndex = queue.shift()!\n if (blocks.has(blockIndex)) continue\n void load(blockIndex)\n }\n }\n\n async function load(blockIndex: number): Promise<void> {\n const controller = new AbortController()\n const block: Block<TData> = {\n status: 'loading',\n rows: [],\n lastTouched: (touchClock += 1),\n controller,\n }\n blocks.set(blockIndex, block)\n inFlight += 1\n emit()\n\n const startRow = startOf(blockIndex)\n const endRow = startRow + blockSize\n try {\n const result = await options.fetch(startRow, endRow, controller.signal)\n if (disposed || controller.signal.aborted || blocks.get(blockIndex) !== block) return\n block.rows = [...result.rows]\n block.status = 'loaded'\n block.controller = null\n applyCountFrom(blockIndex, block.rows.length, result.rowCount)\n evictIfNeeded()\n } catch {\n if (disposed || controller.signal.aborted || blocks.get(blockIndex) !== block) return\n block.status = 'failed'\n block.rows = []\n block.controller = null\n } finally {\n if (!disposed && !controller.signal.aborted) {\n inFlight -= 1\n emit()\n pump()\n }\n }\n }\n\n /**\n * Learn the total from a block that just landed.\n *\n * An explicit non-negative `rowCount` settles it. Otherwise a SHORT block is\n * the proof that we hit the end: fewer rows came back than were asked for, so\n * the data stops where they stop.\n */\n function applyCountFrom(blockIndex: number, received: number, reported: number | undefined): void {\n if (typeof reported === 'number' && reported >= 0) {\n count = reported\n countKnown = true\n return\n }\n if (received < blockSize) {\n count = startOf(blockIndex) + received\n countKnown = true\n }\n }\n\n /**\n * Evict loaded blocks over the limit, least-recently-seen first, never one\n * the viewport is currently on - dropping a visible block would swap real\n * rows for skeletons under the user's eyes and immediately re-fetch them.\n */\n function evictIfNeeded(): void {\n if (!Number.isFinite(maxBlocks)) return\n const firstVisible = blockOf(viewStart)\n const lastVisible = blockOf(Math.max(viewStart, viewEnd))\n const evictable = [...blocks.entries()]\n .filter(([index, b]) => b.status === 'loaded' && (index < firstVisible || index > lastVisible))\n .sort((a, b) => a[1].lastTouched - b[1].lastTouched)\n\n let loaded = 0\n for (const b of blocks.values()) if (b.status === 'loaded') loaded += 1\n\n for (const [index] of evictable) {\n if (loaded <= maxBlocks) break\n blocks.delete(index)\n loaded -= 1\n }\n }\n\n function fetchViewport(): void {\n if (disposed) return\n const first = blockOf(viewStart)\n const last = blockOf(Math.max(viewStart, viewEnd))\n for (let i = first; i <= last; i += 1) {\n const block = blocks.get(i)\n if (block) block.lastTouched = touchClock += 1\n else ensureBlock(i)\n }\n }\n\n function rowAt(index: number): TData | typeof LOADING_ROW | typeof FAILED_ROW {\n const block = blocks.get(blockOf(index))\n if (!block) return LOADING_ROW\n if (block.status === 'failed') return FAILED_ROW\n const row = block.rows[index - startOf(blockOf(index))]\n return row ?? LOADING_ROW\n }\n\n function abortAll(): void {\n for (const block of blocks.values()) block.controller?.abort()\n inFlight = 0\n queue.length = 0\n }\n\n return {\n setViewport(startIndex, endIndex) {\n if (disposed) return\n viewStart = Math.max(0, startIndex)\n viewEnd = Math.max(viewStart, endIndex)\n if (debounceMs === 0) {\n fetchViewport()\n return\n }\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n debounceTimer = null\n fetchViewport()\n }, debounceMs)\n },\n\n rows() {\n if (rowsCache) return rowsCache\n const length = currentLength()\n const out = new Array<TData>(length)\n // Fill from the blocks we have, then pad the rest with placeholders. One\n // pass per block beats one lookup per row: at a million rows the\n // difference is the frame budget.\n out.fill(LOADING_ROW as unknown as TData)\n for (const [index, block] of blocks) {\n const start = startOf(index)\n if (start >= length) continue\n if (block.status === 'failed') {\n const end = Math.min(start + blockSize, length)\n for (let i = start; i < end; i += 1) out[i] = FAILED_ROW as unknown as TData\n continue\n }\n for (let i = 0; i < block.rows.length && start + i < length; i += 1) {\n out[start + i] = block.rows[i]!\n }\n }\n rowsCache = out\n return out\n },\n\n windowedRows() {\n if (windowedCache) return windowedCache\n windowedCache = createWindowedData<TData>(currentLength(), (i) => rowAt(i) as TData)\n return windowedCache\n },\n\n getRow: rowAt,\n\n rowCount: () => (countKnown ? count : null),\n lastRowKnown: () => countKnown,\n\n retryFailed() {\n let any = false\n for (const [index, block] of [...blocks]) {\n if (block.status !== 'failed') continue\n blocks.delete(index)\n ensureBlock(index)\n any = true\n }\n if (any) emit()\n },\n\n retryFailedAt(rowIndex) {\n const index = blockOf(Math.max(0, rowIndex))\n if (blocks.get(index)?.status !== 'failed') return\n blocks.delete(index)\n ensureBlock(index)\n emit()\n },\n\n refresh() {\n // Keep the count and the scroll position: drop the DATA, re-request the\n // same blocks. The user sees skeletons where they were, not a jump home.\n for (const [index, block] of [...blocks]) {\n block.controller?.abort()\n blocks.delete(index)\n ensureBlock(index)\n }\n emit()\n },\n\n purge() {\n abortAll()\n blocks.clear()\n count = null\n countKnown = false\n rowsCache = windowedCache = null\n fetchViewport()\n emit()\n },\n\n setRowCount(next, known = next != null) {\n count = next\n countKnown = known && next != null\n emit()\n },\n\n applyRows(startRow, rows, rowCount) {\n if (startRow % blockSize !== 0) {\n throw new Error(\n `createBlockCache.applyRows: startRow ${startRow} is not a multiple of blockSize ${blockSize}`,\n )\n }\n const firstBlock = blockOf(startRow)\n const blockCount = Math.ceil(rows.length / blockSize)\n for (let i = 0; i < blockCount; i += 1) {\n const index = firstBlock + i\n blocks.get(index)?.controller?.abort() // ours now, whatever was in flight\n blocks.set(index, {\n status: 'loaded',\n rows: rows.slice(i * blockSize, (i + 1) * blockSize),\n lastTouched: (touchClock += 1),\n controller: null,\n })\n }\n const lastBlock = blocks.get(firstBlock + blockCount - 1)\n if (lastBlock) applyCountFrom(firstBlock + blockCount - 1, lastBlock.rows.length, rowCount)\n else if (typeof rowCount === 'number' && rowCount >= 0) {\n count = rowCount\n countKnown = true\n }\n emit()\n },\n\n patch(index, row) {\n const block = blocks.get(blockOf(index))\n if (!block || block.status !== 'loaded') return false\n const offset = index - startOf(blockOf(index))\n if (offset < 0 || offset >= block.rows.length) return false\n block.rows[offset] = row\n emit()\n return true\n },\n\n findIndex(predicate) {\n for (const [blockIndex, block] of blocks) {\n if (block.status !== 'loaded') continue\n const start = startOf(blockIndex)\n for (let i = 0; i < block.rows.length; i += 1) {\n if (predicate(block.rows[i]!, start + i)) return start + i\n }\n }\n return -1\n },\n\n insert(index, rows) {\n if (rows.length === 0) return false\n const clamped = Math.max(0, Math.min(index, currentLength()))\n const run = loadedRunAt(clamped)\n if (run) {\n // Rows shift across block boundaries, so re-slice the run from its\n // first block; everything loaded past it is dropped (offsets moved).\n run.flat.splice(clamped - startOf(run.startBlock), 0, ...rows)\n reseat(run.startBlock, run.flat)\n } else {\n dropLoadedFrom(blockOf(clamped))\n }\n if (countKnown && count != null) count += rows.length\n emit()\n return run != null\n },\n\n remove(index, removeCount = 1) {\n if (removeCount <= 0) return 0\n const run = loadedRunAt(index)\n if (!run) return 0\n const removed = run.flat.splice(index - startOf(run.startBlock), removeCount).length\n reseat(run.startBlock, run.flat)\n if (countKnown && count != null) count = Math.max(0, count - removed)\n emit()\n return removed\n },\n\n getCacheState() {\n return [...blocks.entries()]\n .map(([blockIndex, block]) => ({\n blockIndex,\n startRow: startOf(blockIndex),\n endRow: startOf(blockIndex) + blockSize,\n status: block.status,\n lastTouched: block.lastTouched,\n }))\n .sort((a, b) => a.blockIndex - b.blockIndex)\n },\n\n dispose() {\n disposed = true\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = null\n abortAll()\n blocks.clear()\n },\n }\n\n /**\n * The run of consecutive loaded blocks containing `index`, flattened, with\n * the block it starts at. Null when the block at `index` is not loaded -\n * an index-shifting edit there would have nothing to shift.\n */\n function loadedRunAt(index: number): { startBlock: number; flat: TData[] } | null {\n const at = blockOf(index)\n if (blocks.get(at)?.status !== 'loaded') return null\n let startBlock = at\n while (blocks.get(startBlock - 1)?.status === 'loaded') startBlock -= 1\n const flat: TData[] = []\n for (let i = startBlock; ; i += 1) {\n const block = blocks.get(i)\n if (!block || block.status !== 'loaded') break\n flat.push(...block.rows)\n if (block.rows.length < blockSize) break // the last block, by definition\n }\n return { startBlock, flat }\n }\n\n /**\n * Lay a flat run back out into blocks from `startBlock`, and drop every\n * block after the run: their rows have shifted, and re-fetching them at\n * the new offsets is the honest outcome. Blocks before it are untouched.\n */\n function reseat(startBlock: number, flat: TData[]): void {\n const blockCount = Math.ceil(flat.length / blockSize)\n dropLoadedFrom(startBlock)\n for (let i = 0; i < blockCount; i += 1) {\n blocks.set(startBlock + i, {\n status: 'loaded',\n rows: flat.slice(i * blockSize, (i + 1) * blockSize),\n lastTouched: (touchClock += 1),\n controller: null,\n })\n }\n rowsCache = windowedCache = null\n }\n\n /** Forget every block from `fromBlock` on, aborting any in flight. */\n function dropLoadedFrom(fromBlock: number): void {\n for (const [index, block] of [...blocks]) {\n if (index < fromBlock) continue\n block.controller?.abort()\n blocks.delete(index)\n }\n rowsCache = windowedCache = null\n }\n}\n```\n"
8157
+ "markdown": "# `@svgrid/grid` · `server-block-cache.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\server-block-cache.ts`.\n\n### `function rowPlaceholderState`\n\nWhy a row is not real data, or `null` when it is.\n\nDeliberately NOT an identity check. The sentinels are shared objects, so\n`row === LOADING_ROW` looks like the obvious test - but rows routinely\narrive here through something that wrapped them. Svelte is the everyday\ncase: assigning the controller state into `$state` makes the row array\ndeeply reactive, and every row read back out is a proxy of the original.\nIdentity fails, every placeholder reads as real data, and the grid renders\na screen of blank rows instead of skeletons. Reading the mark works through\nany wrapper that forwards property access, which is all of them.\n\n```ts\nexport function rowPlaceholderState(row: unknown): 'loading' | 'failed' | null\n```\n\n### `function createRowPlaceholder`\n\nMint a frozen placeholder the grid will recognise, carrying whatever\nother fields the caller wants on it. The row model uses this to give its\nplaceholders a `kind`, so code reading display rows and code reading grid\nrows agree on what they are looking at.\n\n```ts\nexport function createRowPlaceholder<T extends object>(\n state: 'loading' | 'failed',\n fields: T,\n): Readonly<T & { readonly [PLACEHOLDER]: 'loading' | 'failed' }>\n```\n\n### `type BlockFetchResult`\n\nWhat a block fetch has to answer with. `rowCount` is optional: see {@link BlockCacheOptions}.\n\n```ts\nexport type BlockFetchResult<TData> = {\n rows: ReadonlyArray<TData>\n /**\n * Total rows after filtering. Omit it (or send `-1`) when the backend cannot\n * count cheaply - the cache then discovers the end from the first short\n * block, and `lastRowKnown()` stays false until it does.\n */\n rowCount?: number\n}\n```\n\n### `type BlockCacheOptions`\n\nWhat a block cache is built from: block size, caps, debounce and the fetch.\n\n```ts\nexport type BlockCacheOptions<TData> = {\n /**\n * Rows per request. Bigger blocks mean fewer round trips and more wasted\n * rows when the user scrolls past; 100 is the usual compromise.\n */\n blockSize?: number\n /**\n * Keep at most this many loaded blocks. Blocks outside the viewport are\n * evicted least-recently-seen first, and scrolling back re-fetches them.\n * Unlimited by default, which is right until the dataset is big enough that\n * holding every visited block matters.\n */\n maxBlocksInCache?: number\n /** Requests open at once. Default 2. */\n maxConcurrentRequests?: number\n /**\n * Wait this long after the viewport settles before fetching. Non-zero values\n * stop a drag of the scrollbar from requesting every block it flies past.\n */\n blockLoadDebounceMs?: number\n /**\n * Rows to claim before anything is loaded, so the grid has a scrollbar (and\n * `scrollToRow` has somewhere to land) on the first paint. Default 1.\n */\n initialRowCount?: number\n /**\n * While the total is unknown, how many unloaded rows to keep past the last\n * loaded one. Scrolling into them is what asks for the next block. Default 1.\n */\n overflowRows?: number\n /** Fetch one block. Reject, or throw, to mark it failed. */\n fetch: (\n startRow: number,\n endRow: number,\n signal: AbortSignal,\n ) => Promise<BlockFetchResult<TData>>\n /** Called after any change to the rows, the count, or a block's state. */\n onChange: (cache: BlockCacheState) => void\n /**\n * How to coalesce `onChange`. Defaults to a microtask, so a burst of block\n * arrivals rebuilds the row array once. Pass `(fn) => fn()` in tests to make\n * every change synchronous.\n */\n schedule?: (flush: () => void) => void\n}\n```\n\n### `type BlockState`\n\nOne block's place in the world, for diagnostics and for tests.\n\n```ts\nexport type BlockState = {\n blockIndex: number\n startRow: number\n endRow: number\n status: 'loading' | 'loaded' | 'failed'\n /** Monotonic counter of when the viewport last covered this block. */\n lastTouched: number\n}\n```\n\n### `type BlockCacheState`\n\nOne block as `getCacheState()` reports it.\n\n```ts\nexport type BlockCacheState = {\n /** Rows after filtering, or `null` while the backend has not said. */\n rowCount: number | null\n /** False while the end of the data is still being discovered. */\n lastRowKnown: boolean\n /** True while at least one block is in flight. */\n loading: boolean\n /** Blocks whose fetch rejected. Empty unless something went wrong. */\n failedBlocks: number[]\n}\n```\n\n### `type BlockCache`\n\nA block cache: rows arrive in blocks as the viewport reaches them,\nplaceholders stand in until then, and blocks far from the viewport are\nevicted past the cap.\n\n```ts\nexport type BlockCache<TData> = {\n /**\n * Tell the cache which rows are on screen. Fetches what is missing (after\n * `blockLoadDebounceMs`) and marks those blocks as recently seen so eviction\n * spares them. Safe to call on every scroll frame.\n */\n setViewport(startIndex: number, endIndex: number): void\n /** The dense row array to hand the grid. Placeholders fill unloaded slots. */\n rows(): ReadonlyArray<TData>\n /**\n * The same rows as windowed data (see windowed-data.ts): `length` is the\n * row count and each entry is read through `getRow` when the grid asks for\n * it, so handing it over costs O(1) whatever the count. A new array per\n * change, like `rows()`.\n */\n windowedRows(): ReadonlyArray<TData>\n /** One row, without building the array. Returns a placeholder when unloaded. */\n getRow(index: number): TData | typeof LOADING_ROW | typeof FAILED_ROW\n rowCount(): number | null\n lastRowKnown(): boolean\n /** Re-fetch the blocks that failed. */\n retryFailed(): void\n /**\n * Re-fetch the failed block holding `rowIndex`, and only that one; the\n * Retry on a failed row. A row whose block has not failed is a no-op.\n */\n retryFailedAt(rowIndex: number): void\n /**\n * Re-fetch the loaded blocks in place, keeping the row count and scroll\n * position. What you want after a mutation lands on the server.\n */\n refresh(): void\n /** Drop everything and start over from the current viewport. */\n purge(): void\n /** Override the total, e.g. from a count endpoint that answered separately. */\n setRowCount(count: number | null, known?: boolean): void\n /**\n * Write rows straight into the cache from `startRow`, as if a fetch had\n * returned them, bypassing the datasource, the debounce and the\n * concurrency cap. `startRow` must sit on a block boundary. An explicit\n * `rowCount` settles the total; without one a short final slice does.\n */\n applyRows(startRow: number, rows: ReadonlyArray<TData>, rowCount?: number): void\n /** Replace one loaded row. No-op when its block is not loaded. */\n patch(index: number, row: TData): boolean\n /**\n * The index of the first LOADED row matching `predicate`, or -1. Rows\n * that are not loaded are not visited - a transaction addressed by id\n * can only touch what is in the cache.\n */\n findIndex(predicate: (row: TData, index: number) => boolean): number\n /**\n * Insert rows at an index and grow the count. Works within whichever\n * run of loaded blocks contains `index`; loaded blocks AFTER that run\n * are dropped, because their rows have shifted and will be re-fetched at\n * their new offsets. An index in an unloaded region grows the count\n * only (the rows exist; they arrive when scrolled to). Returns whether\n * the rows were placed in the cache.\n */\n insert(index: number, rows: ReadonlyArray<TData>): boolean\n /**\n * Remove `count` rows at an index and shrink the count, with the same\n * run semantics as `insert`. Returns how many rows were actually\n * removed from the cache.\n */\n remove(index: number, count?: number): number\n /** Every block the cache is holding, for `debug` output and tests. */\n getCacheState(): BlockState[]\n /** Abort what is in flight and stop emitting. Call on unmount. */\n dispose(): void\n}\n```\n\n### `function createBlockCache`\n\nBuild a block cache over a `fetch(startRow, endRow, signal)`. The free\ninfinite row model and the Enterprise server-side row model both run on\nit, one per level.\n\n```ts\nexport function createBlockCache<TData>(options: BlockCacheOptions<TData>): BlockCache<TData>\n```\n"
8087
8158
  },
8088
8159
  {
8089
8160
  "slug": "reference/auto/svgrid-grid-server-data-source",
8090
8161
  "path": "docs/reference/auto/svgrid-grid-server-data-source.md",
8091
8162
  "title": "@svgrid/grid · server-data-source.ts",
8092
8163
  "section": "API reference",
8093
- "markdown": "# `@svgrid/grid` · `server-data-source.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\server-data-source.ts`.\n\n### `type ServerSortModel`\n\nSort clauses in priority order; `id` is the column id.\n\n```ts\nexport type ServerSortModel = Array<{ id: string; desc: boolean }>\n```\n\n### `type ServerFilterModel`\n\nWhat a request carries for filtering: the global search, the per-column\noperator filters, and the advanced-filter expression.\n\n```ts\nexport type ServerFilterModel = {\n /** Free-text global search. */\n global?: string\n /**\n * Per-column filters, keyed by column id. `value` (+ `valueTo`) carry the\n * operator-style filter; `selectedValues` carries a facet/checklist\n * selection (set-filter). Either or both may be present.\n */\n columns?: Record<\n string,\n { operator: string; value: string; valueTo?: string; selectedValues?: string[] }\n >\n /**\n * Advanced-filter predicate (Pro), as a JSON AST. Expresses what `columns`\n * cannot: OR across columns, nesting, negation, two conditions on one\n * column, cross-column comparison, and aggregates.\n *\n * CONTRACT - all or nothing. A backend that receives this MUST either:\n *\n * (a) translate the WHOLE expression into its query, make `rowCount`\n * reflect it, and set `appliedExpression: true` on the result; or\n * (b) apply none of it and leave `appliedExpression` unset.\n *\n * Partial application is a contract violation, not a degraded mode: it\n * returns a SUPERSET of the requested rows while the UI says the filter is\n * on. That is strictly worse than not filtering, because nothing about the\n * result looks wrong. When the ack is missing the grid says so rather than\n * filtering the loaded page itself - see `ServerState.expressionUnapplied`.\n */\n expression?: GridPredicateExpr\n}\n```\n\n### `type ServerAggFn`\n\nThe aggregate functions every backend helper understands.\n\n```ts\nexport type ServerAggFn = 'sum' | 'avg' | 'min' | 'max' | 'count'\n```\n\n### `type ServerAggregation`\n\nOne value column to roll up per group. `fn` is one of the five built-ins\nor any name your backend knows (`median`, `countDistinct`, a domain\naggregate): the request carries it untouched. The SvelteKit planner emits\nonly the built-ins plus the names it was told to allow, since `fn` ends\nup in SQL.\n\n```ts\nexport type ServerAggregation = { col: string; fn: ServerAggFn | (string & {}) }\n```\n\n### `type ServerRequest`\n\nOne range of rows as the grid asks for it. A flat request carries the\nrange, the sort and the filter; a grouped request adds `groupBy`,\n`groupKeys` and `aggregations`; a pivoted one `pivotBy` and `pivotMode`.\n\n```ts\nexport type ServerRequest = {\n /** Zero-based index of the first row wanted (inclusive). */\n startRow: number\n /** Index just past the last row wanted (exclusive). */\n endRow: number\n pageIndex: number\n pageSize: number\n sortModel: ServerSortModel\n filterModel: ServerFilterModel\n /**\n * Server-side grouping / tree: the columns being grouped on, outer to inner.\n * Omitted / empty for a flat request.\n */\n groupBy?: string[]\n /**\n * The path of group keys the grid is expanding, e.g. `['Germany', 'Berlin']`.\n * Empty (`[]`) asks for the top level. When `groupKeys.length < groupBy.length`\n * the server returns **group rows** (one per distinct key at this level,\n * carrying the group key + aggregates); when they are equal it returns the\n * **leaf rows** under that path.\n */\n groupKeys?: string[]\n /** Value columns to aggregate per group. */\n aggregations?: ServerAggregation[]\n /**\n * Server-side pivot: the columns whose distinct values become columns.\n * With `pivotMode` on, a group row carries one value per (pivot key x\n * aggregation) under a field named `<key>_<col>` (the separator is the\n * row model's `pivotFieldSeparator`), and the response lists those\n * fields in `pivotResultFields`. Only the Enterprise row model sets it.\n */\n pivotBy?: string[]\n pivotMode?: boolean\n /**\n * True on a top-level request when the grid wants a grand-total row and\n * does not have one cached. Answer with `ServerResult.grandTotal`. Only\n * the Enterprise server row model sets it.\n */\n needsGrandTotal?: boolean\n /**\n * The group (or tree node) row being expanded, when this request is for\n * its children. Handy for backends that key children off something on\n * the parent rather than off `groupKeys`. Absent at the top level.\n */\n parentRow?: unknown\n /**\n * Whatever the app passed as `context` to its controller, forwarded\n * untouched on every request. Keep it JSON-serialisable: the SvelteKit\n * transport posts the whole request to your endpoint.\n */\n context?: unknown\n /**\n * Aborted when the grid no longer wants the answer: the block was purged\n * or evicted, the sort or filter changed, a group was collapsed, the\n * controller was disposed. Hand it to `fetch` and a query the user has\n * scrolled past is cancelled at the server instead of completing for\n * nothing; a rejection carrying the abort is ignored by the grid. Not\n * serialisable - the SvelteKit transport reads it and leaves it out of\n * the body.\n */\n signal?: AbortSignal\n}\n```\n\n### `type ServerGroupRow`\n\nA group row in the server-side group/tree model - one distinct key at a\nlevel, with its rolled-up aggregates. The grid renders it with an expander;\nexpanding it fetches its children through the same `getRows`.\n\n```ts\nexport type ServerGroupRow<TData> = {\n kind: 'group'\n /** Stable id (the group path). */\n id: string\n /** Group keys from the root to this node, e.g. `['Germany', 'Berlin']`. */\n path: string[]\n /** The column this group is on (the `groupBy` entry for this level). */\n field: string\n /** This group's key value. */\n key: string\n /** Zero-based depth (0 = top level). */\n level: number\n expanded: boolean\n loading: boolean\n /** Aggregate values keyed by column id, read from the group's response row. */\n aggregates: Record<string, unknown>\n /**\n * How many rows this group holds, when the backend said (see the row\n * model's `childCount` option). Drawn next to the key by `SvGroupCell`,\n * and used to size the group's scrollbar before its first block lands.\n */\n childCount?: number\n /**\n * `false` when nothing can open beneath this row: the innermost group\n * level under a server-side pivot, whose rows are the result itself.\n * The group cell then draws no expander.\n */\n expandable?: boolean\n /** The raw response row for this group (key + aggregates), for cell rendering. */\n data: TData\n}\n```\n\n### `type ServerLeafRow`\n\nA data row in the display list.\n\n```ts\nexport type ServerLeafRow<TData> = {\n kind: 'leaf'\n id: string\n level: number\n /** The group path this leaf sits under. Set by the block-cached row model. */\n route?: string[]\n data: TData\n}\n```\n\n### `type ServerMoreRow`\n\nA \"load more\" affordance emitted at the end of a group whose children are\nonly partially loaded (intra-group paging). Trigger `loadMoreChildren(path)`\nto fetch the next block.\n\n```ts\nexport type ServerMoreRow = {\n kind: 'more'\n id: string\n level: number\n /** Path of the parent group whose children to load more of. */\n path: string[]\n /** How many children remain unloaded. */\n remaining: number\n loading: boolean\n}\n```\n\n### `type ServerFooterRow`\n\nA subtotal / footer row emitted after an expanded group's children when\n`groupFooters` is on. Carries the group's aggregates a second time so a\n\"Total\" line sits under the detail.\n\n```ts\nexport type ServerFooterRow<TData> = {\n kind: 'footer'\n id: string\n level: number\n path: string[]\n /** The group this footer totals (its key). */\n key: string\n aggregates: Record<string, unknown>\n /** The group's response row (key + aggregates), so value columns show totals. */\n data: TData\n}\n```\n\n### `type ServerSkeletonRow`\n\nA placeholder row shown while a block of children is being fetched.\n\n```ts\nexport type ServerSkeletonRow = {\n kind: 'skeleton'\n id: string\n level: number\n}\n```\n\n### `type ServerGrandTotalRow`\n\nA grand-total row across the whole result. One per grid, at the top or\nthe bottom, with the fixed id `sv-grand-total` so a transaction can\naddress it.\n\n```ts\nexport type ServerGrandTotalRow<TData> = {\n kind: 'grandTotal'\n id: 'sv-grand-total'\n level: 0\n aggregates: Record<string, unknown>\n data: TData\n}\n```\n\n### `type ServerPlaceholderRow`\n\nA row whose data has not arrived: `loading` while its block is in\nflight, `failed` when the fetch rejected. Shared, frozen objects - one\nper state, not one per row - so a million unloaded rows cost nothing to\nrepresent. They also carry the grid's placeholder mark, so\n`rowPlaceholderState()` recognises them and the grid draws them itself.\n\n```ts\nexport type ServerPlaceholderRow = {\n readonly kind: 'placeholder'\n readonly state: 'loading' | 'failed'\n}\n```\n\n### `type ServerDetailRow`\n\nThe detail panel under a leaf whose detail is open: master-detail on a\nserver-side row model. The grid draws it through `renderDetailRow`\n(mark it with `isDetailRow`); `master` is the leaf it belongs to.\n\n```ts\nexport type ServerDetailRow<TData> = {\n kind: 'detail'\n id: string\n level: number\n route?: string[]\n /** The leaf's id, as `getRowId` names it. */\n masterId: string\n master: TData\n}\n```\n\n### `type ServerDisplayRow`\n\nEvery row a server row model can put on screen. Each carries an `id` and\na `level`. The block-cached model adds {@link ServerPlaceholderRow} for\nrows not yet loaded - see its own `ServerRowModelDisplayRow`.\n\n```ts\nexport type ServerDisplayRow<TData> =\n | ServerGroupRow<TData>\n | ServerLeafRow<TData>\n | ServerDetailRow<TData>\n | ServerMoreRow\n | ServerFooterRow<TData>\n | ServerSkeletonRow\n | ServerGrandTotalRow<TData>\n```\n\n### `type ServerResult`\n\nWhat `getRows` answers with: the rows for the requested range and the\ncount after filtering, plus the grand total and the pivot fields when\nasked for.\n\n```ts\nexport type ServerResult<TData> = {\n rows: ReadonlyArray<TData>\n /**\n * Total row count after filtering, for the pager and the scrollbar.\n *\n * Paging needs it. Infinite scrolling does not: send `-1` (or, from a\n * source typed loosely, omit it) when counting is expensive, and the grid\n * discovers the end from the first short block instead. See\n * `mode: 'infinite'` on {@link ServerControllerOptions}.\n */\n rowCount: number\n /**\n * Set `true` ONLY when `filterModel.expression` was applied in full. Leave it\n * unset if you ignored the expression; the grid then warns rather than\n * pretending the filter ran. See the contract on `ServerFilterModel.expression`.\n */\n appliedExpression?: boolean\n /**\n * The grand-total row, in reply to `ServerRequest.needsGrandTotal`: an\n * object sets it, `null` removes it, and leaving it out keeps whatever the\n * grid already had. Shaped like a group row: the aggregate values live\n * under their column ids.\n */\n grandTotal?: TData | null\n /**\n * Pivot mode: the fields the group rows carry for the pivoted values,\n * e.g. `[\"2024_amount\", \"2025_amount\"]`, from which the grid builds one\n * column per field under a header group per pivot key. Send the full\n * list on every pivoted response; the grid keeps the union. Every group\n * row carries every listed field, `null` where no rows fall in that\n * cell.\n */\n pivotResultFields?: string[]\n /**\n * Pivot mode, the long way: full column definitions instead of field\n * names, for a backend that wants to name and format them itself. Wins\n * over `pivotResultFields` when both are present.\n */\n pivotResultColumns?: ReadonlyArray<unknown>\n}\n```\n\n### `type ServerSelectionRule`\n\nA selection expressed as a rule rather than a list, for `updateWhere`.\nThe flat shape is \"these ids\" or \"everything except these\"; the nested\nshape is the same idea per group, keyed by group key or leaf id, as the\nEnterprise row model keeps it under `groupSelects: 'descendants'`.\n\n```ts\nexport type ServerSelectionRule =\n | { selectAll: boolean; toggled: string[] }\n | {\n selectAllChildren: boolean\n toggled: Record<string, { selectAllChildren: boolean; toggled: Record<string, unknown>; group?: boolean }>\n group?: boolean\n /** The group columns the tree's levels are keyed by, outer to inner. */\n groupBy?: string[]\n }\n```\n\n### `type ServerDataSource`\n\nThe contract a backend implements: `getRows`, and optionally the write\nmethods, a bulk edit by rule and `destroy`.\n\n```ts\nexport type ServerDataSource<TData> = {\n getRows(request: ServerRequest): Promise<ServerResult<TData>>\n /**\n * Optional write side. Implement whichever your backend supports; the\n * controller exposes matching `createRow` / `updateRow` / `deleteRow`\n * methods that call through and then `refresh()` the current page.\n * Calling a controller method whose source counterpart is missing throws.\n */\n createRow?(input: Partial<TData>): Promise<TData>\n updateRow?(id: string, patch: Partial<TData>): Promise<TData>\n deleteRow?(id: string): Promise<void>\n /**\n * Apply one patch to every row a selection RULE names, server-side - the\n * write behind a bulk edit of rows the grid never loaded. `filterModel`\n * scopes the rows exactly as `getRows` does; `selection` is the rule:\n * either \"these ids\" (`selectAll: false`) or \"everything but these\"\n * (`selectAll: true`), or the per-group tree the Enterprise row model\n * keeps under `groupSelects: 'descendants'`. Resolve with how many rows\n * changed. Optional: without it, a bulk edit under select-all is refused\n * rather than silently applied to the loaded rows only.\n */\n updateWhere?(\n filterModel: ServerFilterModel,\n patch: Partial<TData>,\n selection: ServerSelectionRule,\n ): Promise<number>\n /**\n * Called once, from the controller's `dispose()`, for a source with\n * something to close: a socket, a subscription, a worker.\n */\n destroy?(): void\n}\n```\n\n### `type ServerState`\n\nWhat `createServerDataSource` emits on every change: the rows on hand,\nthe counts, the loading and saving flags, the last error, and the\ncurrent sort and filter.\n\n```ts\nexport type ServerState<TData> = {\n rows: ReadonlyArray<TData>\n total: number\n loading: boolean\n /** True while a create / update / delete mutation is in flight. */\n saving: boolean\n error: unknown\n pageIndex: number\n pageSize: number\n pageCount: number\n sortModel: ServerSortModel\n filterModel: ServerFilterModel\n /**\n * True when an advanced-filter expression was sent but the source did not\n * acknowledge applying it - so `rows` is unfiltered and the UI should say so.\n * Surface this rather than hiding it: the rows look perfectly normal.\n *\n * Optional so existing code that builds a `ServerState` literal keeps\n * compiling; the controller always sets it.\n */\n expressionUnapplied?: boolean\n /**\n * Rows after filtering, or `null` when the backend has not said and the\n * end has not been found yet. Only ever null in `infinite` mode; `total`\n * carries the best current guess either way.\n */\n rowCount?: number | null\n /** False while the end of an infinite list is still being discovered. */\n lastRowKnown?: boolean\n /** Blocks whose fetch failed, in `infinite` mode. Empty when all is well. */\n failedBlocks?: number[]\n}\n```\n\n### `type ServerController`\n\nEverything a controller can do, plus the {@link GridRowModel} surface, so\none object can be driven by hand OR handed to `<SvGrid rowModel>` and wire\nitself up.\n\n```ts\nexport type ServerController<TData> = GridRowModel<TData> & {\n /** Re-fetch the current page (e.g. after a mutation). */\n refresh(): void\n /**\n * The rows on screen, so `infinite` mode knows which blocks to fetch and\n * which to spare from eviction. Wire it to the grid's\n * `onVisibleRangeChange` - or pass the controller as `rowModel` and the\n * grid wires it for you. No-op in `page` mode.\n */\n setViewport(startIndex: number, endIndex: number): void\n /** Re-fetch the blocks that failed. No-op in `page` mode. */\n retryLoads(): void\n /**\n * Throw away every cached block and reload from the current viewport.\n * `refresh()` is the gentler option: it keeps the row count and the scroll\n * position. No-op in `page` mode, where there is only ever one page held.\n */\n purge(): void\n /** Cached blocks and their state, for logging and tests. Empty in `page` mode. */\n getCacheState(): BlockState[]\n setSort(sortModel: ServerSortModel): void\n /**\n * Replace the filter. Takes the `ServerFilterModel` a request carries, or\n * the payload the grid's own `onFiltersChange` hands you - which is a\n * list of columns rather than a map, and is converted here so that every\n * app does not write the same `Object.fromEntries` by hand.\n */\n setFilter(filterModel: ServerFilterModel | GridFilterState): void\n setPage(pageIndex: number): void\n setPageSize(pageSize: number): void\n /**\n * Create a row through the source, then refresh the current page. Resolves\n * with the created row. Rejects if the source has no `createRow` (or if the\n * create itself fails - the read state is left untouched on failure).\n */\n createRow(input: Partial<TData>): Promise<TData>\n /**\n * Update a row by id through the source. Non-optimistic: refreshes the page.\n * Optimistic (see `optimistic` + `getRowId` options): patches the local row\n * immediately, then reconciles with the server result, rolling back on error.\n */\n updateRow(id: string, patch: Partial<TData>): Promise<TData>\n /**\n * Delete a row by id through the source. Non-optimistic: refreshes the page.\n * Optimistic: removes the local row immediately, restoring it on error.\n */\n deleteRow(id: string): Promise<void>\n getState(): ServerState<TData>\n /** Stop accepting in-flight responses (call on unmount). */\n dispose(): void\n}\n```\n\n### `type ServerControllerOptions`\n\nOptions for `createServerDataSource`: the page size, or the block\nsettings in `infinite` mode, optimistic writes and the change callback.\n\n```ts\nexport type ServerControllerOptions<TData> = {\n pageSize?: number\n /** Called whenever any of `rows` / `total` / `loading` / page changes. */\n onChange?: (state: ServerState<TData>) => void\n /**\n * Apply `updateRow` / `deleteRow` to the local rows immediately (before the\n * server confirms) and roll back on error - so edits feel instant and no\n * refetch is needed. Requires `getRowId` to locate rows; ignored without it.\n * A subsequent `refresh()` reconciles ordering/filtering. Default false.\n */\n optimistic?: boolean\n /** Resolve a row's stable id, so optimistic update/delete can find it in `rows`. */\n getRowId?: (row: TData) => string\n /**\n * How rows reach the grid.\n *\n * - `page` (default): one page at a time. `state.rows` is that page, and\n * `setPage` moves between them.\n * - `infinite`: one long scrollable list. `state.rows` spans the whole\n * result, with placeholder rows standing in for blocks nobody has\n * scrolled to yet; blocks load as the viewport reaches them.\n */\n mode?: 'page' | 'infinite'\n /** `infinite` mode: rows per request. Default 100. */\n blockSize?: number\n /**\n * `infinite` mode: keep at most this many loaded blocks, evicting the\n * least recently seen. Unlimited by default.\n */\n maxBlocksInCache?: number\n /** `infinite` mode: requests open at once. Default 2. */\n maxConcurrentRequests?: number\n /** `infinite` mode: wait for the scroll to settle this long before fetching. */\n blockLoadDebounceMs?: number\n /**\n * `infinite` mode: rows to claim before anything has loaded, so there is a\n * scrollbar on first paint. Default 1.\n */\n initialRowCount?: number\n}\n```\n\n### `function createServerDataSource`\n\nThe free server row model over a `ServerDataSource`: one page at a time,\nor one block-cached list in `infinite` mode, with sort, filter, race\nsafety and writes. The result is a `GridRowModel`, so\n`<SvGrid rowModel={ctl} />` wires every seam.\n\n```ts\nexport function createServerDataSource<TData>(\n source: ServerDataSource<TData>,\n options: ServerControllerOptions<TData>,\n): ServerController<TData> {\n const state: ServerState<TData> = {\n rows: [],\n total: 0,\n loading: false,\n saving: false,\n error: null,\n pageIndex: 0,\n pageSize: options.pageSize ?? 50,\n pageCount: 1,\n sortModel: [],\n filterModel: {},\n expressionUnapplied: false,\n }\n\n const infinite = options.mode === 'infinite'\n // `onChange` is the one-callback API this controller shipped with;\n // `subscribe` is the many-listener one `GridRowModel` needs. Both fire\n // from `emit`, so a grid driven by `rowModel` and an app reading\n // `onChange` stay in step.\n const subscribers = new Set<() => void>()\n let cache: BlockCache<TData> | null = null\n\n // Monotonic request id: only the latest fetch is allowed to land, so a slow\n // response for an old sort/filter can't clobber a newer one.\n let requestSeq = 0\n /** The page fetch in flight; a newer one, or dispose, aborts it. */\n let pageAbort: AbortController | null = null\n let disposed = false\n // Once per controller: a misconfigured backend would otherwise log on every\n // page, scroll and filter change.\n let warnedExpressionUnapplied = false\n\n const emit = () => {\n state.pageCount = Math.max(1, Math.ceil(state.total / state.pageSize))\n options.onChange?.({ ...state })\n for (const notify of subscribers) notify()\n }\n\n /**\n * Pull the block cache's view of the world into `state` and emit.\n *\n * `total` stays a plain number because the pager and the footer have\n * always read it as one; while the end is undiscovered it holds the\n * current optimistic length, which is exactly what the scrollbar needs.\n * `rowCount` is the honest answer, null and all.\n */\n function emitFromCache(): void {\n if (!cache || disposed) return\n // Windowed: the grid reads only the rows it shows, so a block landing\n // costs the same at 100M rows as at 10K.\n const rows = cache.windowedRows()\n state.rows = rows\n state.rowCount = cache.rowCount()\n state.lastRowKnown = cache.lastRowKnown()\n state.total = cache.rowCount() ?? rows.length\n emit()\n }\n\n function buildCache(): BlockCache<TData> {\n return createBlockCache<TData>({\n blockSize: options.blockSize ?? 100,\n maxBlocksInCache: options.maxBlocksInCache,\n maxConcurrentRequests: options.maxConcurrentRequests,\n blockLoadDebounceMs: options.blockLoadDebounceMs,\n initialRowCount: options.initialRowCount,\n fetch: async (startRow, endRow, signal) => {\n const result = await source.getRows({\n startRow,\n endRow,\n // A block is a page of its own size, so a backend that only knows\n // how to page still works unchanged.\n pageIndex: Math.floor(startRow / Math.max(1, endRow - startRow)),\n pageSize: endRow - startRow,\n sortModel: state.sortModel,\n filterModel: state.filterModel,\n groupBy: [],\n groupKeys: [],\n aggregations: [],\n signal,\n })\n noteExpressionApplied(result)\n return { rows: result.rows, rowCount: result.rowCount }\n },\n onChange: (s) => {\n state.loading = s.loading\n state.failedBlocks = s.failedBlocks\n emitFromCache()\n },\n })\n }\n\n /** Reload from scratch: new sort, new filter, or an explicit purge. */\n function resetCache(): void {\n if (disposed) return\n cache?.dispose()\n cache = buildCache()\n cache.setViewport(viewStart, viewEnd)\n emitFromCache()\n }\n\n /**\n * An expression was sent but the backend did not acknowledge applying it,\n * so these rows are a SUPERSET of what was asked for. Say so instead of\n * filtering here: filtering one page would turn \"3 of 1,000,000 match\"\n * into a confident lie and make paging incoherent, since the next page\n * would re-filter a different slice.\n */\n function noteExpressionApplied(result: ServerResult<TData>): void {\n state.expressionUnapplied =\n state.filterModel.expression != null && result.appliedExpression !== true\n if (!state.expressionUnapplied || warnedExpressionUnapplied) return\n warnedExpressionUnapplied = true\n console.warn(\n '[svgrid] The data source was sent filterModel.expression but did not ' +\n 'return `appliedExpression: true`, so the advanced filter is NOT applied ' +\n 'and the rows shown are unfiltered. Apply the whole expression and ' +\n 'acknowledge it, or clear the advanced filter. ' +\n 'See https://svgrid.com/docs/help/server/server-filtering',\n )\n }\n\n async function fetchPage() {\n if (disposed) return\n const id = ++requestSeq\n pageAbort?.abort()\n const controller = new AbortController()\n pageAbort = controller\n state.loading = true\n state.error = null\n emit()\n const startRow = state.pageIndex * state.pageSize\n try {\n const result = await source.getRows({\n startRow,\n endRow: startRow + state.pageSize,\n pageIndex: state.pageIndex,\n pageSize: state.pageSize,\n sortModel: state.sortModel,\n filterModel: state.filterModel,\n // Flat mode: no grouping. Server-side grouping and tree data live in\n // `createServerGroupModel` from @svgrid/enterprise, which fills these in.\n groupBy: [],\n groupKeys: [],\n aggregations: [],\n signal: controller.signal,\n })\n if (disposed || id !== requestSeq) return // stale\n state.rows = result.rows\n state.total = result.rowCount\n state.rowCount = result.rowCount\n state.lastRowKnown = true\n noteExpressionApplied(result)\n state.loading = false\n emit()\n } catch (err) {\n if (disposed || id !== requestSeq) return\n state.rows = []\n state.error = err\n state.loading = false\n emit()\n }\n }\n\n // Shared mutation lifecycle: flip `saving`, run the write, refresh the\n // current page on success, and always clear `saving`. A missing source\n // method (or a disposed controller) rejects before anything is emitted.\n function mutate<T>(name: string, thunk: (() => Promise<T>) | null): Promise<T> {\n if (disposed) {\n return Promise.reject(new Error('createServerDataSource: controller is disposed'))\n }\n if (!thunk) {\n return Promise.reject(\n new Error(`createServerDataSource: the datasource does not implement ${name}()`),\n )\n }\n state.saving = true\n emit()\n return (async () => {\n try {\n const result = await thunk()\n // Page mode re-reads the page. Infinite mode re-reads the blocks it\n // holds, in place: the list keeps its length and its scroll.\n if (infinite) cache?.refresh()\n else await fetchPage()\n return result\n } finally {\n state.saving = false\n emit()\n }\n })()\n }\n\n const optimistic = !!options.optimistic && !!options.getRowId\n const getRowId = options.getRowId\n\n // The last range the grid reported, so a sort / filter / purge can\n // re-request what the user is actually looking at rather than row 0.\n let viewStart = 0\n let viewEnd = 0\n\n // Optimistic update: patch the local row, reconcile with the server result,\n // roll back on error. Falls back to the plain refresh path when the row\n // isn't on the current page (nothing local to update).\n async function optimisticUpdate(\n id: string,\n patch: Partial<TData>,\n fn: (id: string, patch: Partial<TData>) => Promise<TData>,\n ): Promise<TData> {\n if (disposed) throw new Error('createServerDataSource: controller is disposed')\n if (infinite && cache) {\n // The cache owns the rows here; patch it, not a copy the next block\n // to land would overwrite.\n const at = cache.findIndex((r) => !rowPlaceholderState(r) && getRowId!(r) === id)\n if (at < 0) return mutate('updateRow', () => fn(id, patch))\n const prev = cache.getRow(at) as TData\n cache.patch(at, { ...prev, ...patch })\n state.saving = true\n emit()\n try {\n const result = await fn(id, patch)\n cache.patch(at, result)\n return result\n } catch (err) {\n cache.patch(at, prev)\n throw err\n } finally {\n state.saving = false\n emit()\n }\n }\n const prevRows = state.rows\n const idx = prevRows.findIndex((r) => getRowId!(r) === id)\n if (idx < 0) return mutate('updateRow', () => fn(id, patch))\n\n state.rows = [...prevRows.slice(0, idx), { ...prevRows[idx]!, ...patch }, ...prevRows.slice(idx + 1)]\n state.saving = true\n emit()\n try {\n const result = await fn(id, patch)\n state.rows = state.rows.map((r) => (getRowId!(r) === id ? result : r))\n return result\n } catch (err) {\n state.rows = prevRows\n throw err\n } finally {\n state.saving = false\n emit()\n }\n }\n\n // Optimistic delete: drop the local row + decrement total, restore on error.\n async function optimisticDelete(\n id: string,\n fn: (id: string) => Promise<void>,\n ): Promise<void> {\n if (disposed) throw new Error('createServerDataSource: controller is disposed')\n if (infinite && cache) {\n const at = cache.findIndex((r) => !rowPlaceholderState(r) && getRowId!(r) === id)\n if (at < 0) return mutate('deleteRow', () => fn(id))\n const prev = cache.getRow(at) as TData\n cache.remove(at, 1)\n state.saving = true\n emit()\n try {\n await fn(id)\n } catch (err) {\n cache.insert(at, [prev])\n throw err\n } finally {\n state.saving = false\n emit()\n }\n return\n }\n const prevRows = state.rows\n const prevTotal = state.total\n const next = prevRows.filter((r) => getRowId!(r) !== id)\n if (next.length === prevRows.length) return mutate('deleteRow', () => fn(id))\n\n state.rows = next\n state.total = Math.max(0, prevTotal - (prevRows.length - next.length))\n state.saving = true\n emit()\n try {\n await fn(id)\n } catch (err) {\n state.rows = prevRows\n state.total = prevTotal\n throw err\n } finally {\n state.saving = false\n emit()\n }\n }\n\n // In infinite mode the first blocks are requested as soon as the grid\n // reports a viewport; `refresh()` is what arms the cache before that.\n if (infinite) cache = buildCache()\n\n return {\n refresh: () => {\n if (!infinite) return void fetchPage()\n // Keep the count and the scroll position, re-request what is held.\n cache?.refresh()\n },\n setViewport(startIndex, endIndex) {\n viewStart = startIndex\n viewEnd = endIndex\n cache?.setViewport(startIndex, endIndex)\n },\n retryLoads: () => cache?.retryFailed(),\n purge: () => cache?.purge(),\n getCacheState: () => cache?.getCacheState() ?? [],\n\n // --- GridRowModel -----------------------------------------------\n subscribe(onChange) {\n subscribers.add(onChange)\n return () => {\n subscribers.delete(onChange)\n }\n },\n getRows: () => state.rows,\n isLoading: () => state.loading,\n getRowId: options.getRowId ? (row: TData) => options.getRowId!(row) : undefined,\n // Only infinite mode has unloaded rows to stand in for.\n rowPlaceholder: infinite ? (row: TData) => rowPlaceholderState(row) : undefined,\n retryRow: infinite ? (_row: TData, rowIndex: number) => cache?.retryFailedAt(rowIndex) : undefined,\n /**\n * A getter, not a snapshot: the grid re-reads this after every change\n * notification, and a frozen object would leave the pager on page 1\n * forever. Absent in infinite mode, where there are no pages.\n */\n get pagination() {\n if (infinite) return undefined\n return {\n pageIndex: state.pageIndex,\n pageSize: state.pageSize,\n rowCount: state.total,\n setPage: (pageIndex: number) => this.setPage(pageIndex),\n setPageSize: (pageSize: number) => this.setPageSize(pageSize),\n }\n },\n createRow: (input) =>\n mutate('createRow', source.createRow ? () => source.createRow!(input) : null),\n updateRow: (id, patch) => {\n if (!source.updateRow) return mutate('updateRow', null)\n const fn = source.updateRow\n return optimistic ? optimisticUpdate(id, patch, fn) : mutate('updateRow', () => fn(id, patch))\n },\n deleteRow: (id) => {\n if (!source.deleteRow) return mutate('deleteRow', null)\n const fn = source.deleteRow\n return optimistic ? optimisticDelete(id, fn) : mutate('deleteRow', () => fn(id))\n },\n setSort(sortModel) {\n state.sortModel = sortModel\n state.pageIndex = 0\n if (infinite) return resetCache()\n void fetchPage()\n },\n setFilter(filterModel) {\n state.filterModel = Array.isArray(filterModel.columns)\n ? {\n global: filterModel.global,\n columns: toServerFilterColumns(filterModel as GridFilterState),\n }\n : (filterModel as ServerFilterModel)\n state.pageIndex = 0\n if (infinite) return resetCache()\n void fetchPage()\n },\n setPage(pageIndex) {\n // There are no pages to move between when the whole result is one\n // scrollable list; the grid scrolls instead.\n if (infinite) return\n const clamped = Math.max(0, pageIndex)\n if (clamped === state.pageIndex) return\n state.pageIndex = clamped\n void fetchPage()\n },\n setPageSize(pageSize) {\n state.pageSize = Math.max(1, pageSize)\n state.pageIndex = 0\n if (infinite) return\n void fetchPage()\n },\n getState: () => ({ ...state }),\n dispose() {\n disposed = true\n pageAbort?.abort()\n pageAbort = null\n cache?.dispose()\n cache = null\n // An in-flight fetch's resolution short-circuits on `disposed`, so it\n // never clears `loading`. Clear it here (and emit) so a disposed\n // controller doesn't report a permanent loading state.\n if (state.loading) {\n state.loading = false\n emit()\n }\n },\n }\n}\n```\n"
8164
+ "markdown": "# `@svgrid/grid` · `server-data-source.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\server-data-source.ts`.\n\n### `type ServerSortModel`\n\nSort clauses in priority order; `id` is the column id.\n\n```ts\nexport type ServerSortModel = Array<{ id: string; desc: boolean }>\n```\n\n### `type ServerFilterModel`\n\nWhat a request carries for filtering: the global search, the per-column\noperator filters, and the advanced-filter expression.\n\n```ts\nexport type ServerFilterModel = {\n /** Free-text global search. */\n global?: string\n /**\n * Per-column filters, keyed by column id. `value` (+ `valueTo`) carry the\n * operator-style filter; `selectedValues` carries a facet/checklist\n * selection (set-filter). Either or both may be present.\n */\n columns?: Record<\n string,\n { operator: string; value: string; valueTo?: string; selectedValues?: string[] }\n >\n /**\n * Advanced-filter predicate (Pro), as a JSON AST. Expresses what `columns`\n * cannot: OR across columns, nesting, negation, two conditions on one\n * column, cross-column comparison, and aggregates.\n *\n * CONTRACT - all or nothing. A backend that receives this MUST either:\n *\n * (a) translate the WHOLE expression into its query, make `rowCount`\n * reflect it, and set `appliedExpression: true` on the result; or\n * (b) apply none of it and leave `appliedExpression` unset.\n *\n * Partial application is a contract violation, not a degraded mode: it\n * returns a SUPERSET of the requested rows while the UI says the filter is\n * on. That is strictly worse than not filtering, because nothing about the\n * result looks wrong. When the ack is missing the grid says so rather than\n * filtering the loaded page itself - see `ServerState.expressionUnapplied`.\n */\n expression?: GridPredicateExpr\n /**\n * Models of the columns' `customFilter`s, keyed by column id, as the\n * grid's `onFiltersChange` reports them. The grid cannot turn a custom\n * model into a query; the backend translates each one itself.\n */\n custom?: Record<string, unknown>\n}\n```\n\n### `type ServerAggFn`\n\nThe aggregate functions every backend helper understands.\n\n```ts\nexport type ServerAggFn = 'sum' | 'avg' | 'min' | 'max' | 'count'\n```\n\n### `type ServerAggregation`\n\nOne value column to roll up per group. `fn` is one of the five built-ins\nor any name your backend knows (`median`, `countDistinct`, a domain\naggregate): the request carries it untouched. The SvelteKit planner emits\nonly the built-ins plus the names it was told to allow, since `fn` ends\nup in SQL.\n\n```ts\nexport type ServerAggregation = { col: string; fn: ServerAggFn | (string & {}) }\n```\n\n### `type ServerRequest`\n\nOne range of rows as the grid asks for it. A flat request carries the\nrange, the sort and the filter; a grouped request adds `groupBy`,\n`groupKeys` and `aggregations`; a pivoted one `pivotBy` and `pivotMode`.\n\n```ts\nexport type ServerRequest = {\n /** Zero-based index of the first row wanted (inclusive). */\n startRow: number\n /** Index just past the last row wanted (exclusive). */\n endRow: number\n pageIndex: number\n pageSize: number\n sortModel: ServerSortModel\n filterModel: ServerFilterModel\n /**\n * Server-side grouping / tree: the columns being grouped on, outer to inner.\n * Omitted / empty for a flat request.\n */\n groupBy?: string[]\n /**\n * The path of group keys the grid is expanding, e.g. `['Germany', 'Berlin']`.\n * Empty (`[]`) asks for the top level. When `groupKeys.length < groupBy.length`\n * the server returns **group rows** (one per distinct key at this level,\n * carrying the group key + aggregates); when they are equal it returns the\n * **leaf rows** under that path.\n */\n groupKeys?: string[]\n /** Value columns to aggregate per group. */\n aggregations?: ServerAggregation[]\n /**\n * Server-side pivot: the columns whose distinct values become columns.\n * With `pivotMode` on, a group row carries one value per (pivot key x\n * aggregation) under a field named `<key>_<col>` (the separator is the\n * row model's `pivotFieldSeparator`), and the response lists those\n * fields in `pivotResultFields`. Only the Enterprise row model sets it.\n */\n pivotBy?: string[]\n pivotMode?: boolean\n /**\n * True on a top-level request when the grid wants a grand-total row and\n * does not have one cached. Answer with `ServerResult.grandTotal`. Only\n * the Enterprise server row model sets it.\n */\n needsGrandTotal?: boolean\n /**\n * The group (or tree node) row being expanded, when this request is for\n * its children. Handy for backends that key children off something on\n * the parent rather than off `groupKeys`. Absent at the top level.\n */\n parentRow?: unknown\n /**\n * Whatever the app passed as `context` to its controller, forwarded\n * untouched on every request. Keep it JSON-serialisable: the SvelteKit\n * transport posts the whole request to your endpoint.\n */\n context?: unknown\n /**\n * Aborted when the grid no longer wants the answer: the block was purged\n * or evicted, the sort or filter changed, a group was collapsed, the\n * controller was disposed. Hand it to `fetch` and a query the user has\n * scrolled past is cancelled at the server instead of completing for\n * nothing; a rejection carrying the abort is ignored by the grid. Not\n * serialisable - the SvelteKit transport reads it and leaves it out of\n * the body.\n */\n signal?: AbortSignal\n}\n```\n\n### `type ServerGroupRow`\n\nA group row in the server-side group/tree model - one distinct key at a\nlevel, with its rolled-up aggregates. The grid renders it with an expander;\nexpanding it fetches its children through the same `getRows`.\n\n```ts\nexport type ServerGroupRow<TData> = {\n kind: 'group'\n /** Stable id (the group path). */\n id: string\n /** Group keys from the root to this node, e.g. `['Germany', 'Berlin']`. */\n path: string[]\n /** The column this group is on (the `groupBy` entry for this level). */\n field: string\n /** This group's key value. */\n key: string\n /** Zero-based depth (0 = top level). */\n level: number\n expanded: boolean\n loading: boolean\n /** Aggregate values keyed by column id, read from the group's response row. */\n aggregates: Record<string, unknown>\n /**\n * How many rows this group holds, when the backend said (see the row\n * model's `childCount` option). Drawn next to the key by `SvGroupCell`,\n * and used to size the group's scrollbar before its first block lands.\n */\n childCount?: number\n /**\n * `false` when nothing can open beneath this row: the innermost group\n * level under a server-side pivot, whose rows are the result itself.\n * The group cell then draws no expander.\n */\n expandable?: boolean\n /** The raw response row for this group (key + aggregates), for cell rendering. */\n data: TData\n}\n```\n\n### `type ServerLeafRow`\n\nA data row in the display list.\n\n```ts\nexport type ServerLeafRow<TData> = {\n kind: 'leaf'\n id: string\n level: number\n /** The group path this leaf sits under. Set by the block-cached row model. */\n route?: string[]\n data: TData\n}\n```\n\n### `type ServerMoreRow`\n\nA \"load more\" affordance emitted at the end of a group whose children are\nonly partially loaded (intra-group paging). Trigger `loadMoreChildren(path)`\nto fetch the next block.\n\n```ts\nexport type ServerMoreRow = {\n kind: 'more'\n id: string\n level: number\n /** Path of the parent group whose children to load more of. */\n path: string[]\n /** How many children remain unloaded. */\n remaining: number\n loading: boolean\n}\n```\n\n### `type ServerFooterRow`\n\nA subtotal / footer row emitted after an expanded group's children when\n`groupFooters` is on. Carries the group's aggregates a second time so a\n\"Total\" line sits under the detail.\n\n```ts\nexport type ServerFooterRow<TData> = {\n kind: 'footer'\n id: string\n level: number\n path: string[]\n /** The group this footer totals (its key). */\n key: string\n aggregates: Record<string, unknown>\n /** The group's response row (key + aggregates), so value columns show totals. */\n data: TData\n}\n```\n\n### `type ServerSkeletonRow`\n\nA placeholder row shown while a block of children is being fetched.\n\n```ts\nexport type ServerSkeletonRow = {\n kind: 'skeleton'\n id: string\n level: number\n}\n```\n\n### `type ServerGrandTotalRow`\n\nA grand-total row across the whole result. One per grid, at the top or\nthe bottom, with the fixed id `sv-grand-total` so a transaction can\naddress it.\n\n```ts\nexport type ServerGrandTotalRow<TData> = {\n kind: 'grandTotal'\n id: 'sv-grand-total'\n level: 0\n aggregates: Record<string, unknown>\n data: TData\n}\n```\n\n### `type ServerPlaceholderRow`\n\nA row whose data has not arrived: `loading` while its block is in\nflight, `failed` when the fetch rejected. Shared, frozen objects - one\nper state, not one per row - so a million unloaded rows cost nothing to\nrepresent. They also carry the grid's placeholder mark, so\n`rowPlaceholderState()` recognises them and the grid draws them itself.\n\n```ts\nexport type ServerPlaceholderRow = {\n readonly kind: 'placeholder'\n readonly state: 'loading' | 'failed'\n}\n```\n\n### `type ServerDetailRow`\n\nThe detail panel under a leaf whose detail is open: master-detail on a\nserver-side row model. The grid draws it through `renderDetailRow`\n(mark it with `isDetailRow`); `master` is the leaf it belongs to.\n\n```ts\nexport type ServerDetailRow<TData> = {\n kind: 'detail'\n id: string\n level: number\n route?: string[]\n /** The leaf's id, as `getRowId` names it. */\n masterId: string\n master: TData\n}\n```\n\n### `type ServerDisplayRow`\n\nEvery row a server row model can put on screen. Each carries an `id` and\na `level`. The block-cached model adds {@link ServerPlaceholderRow} for\nrows not yet loaded - see its own `ServerRowModelDisplayRow`.\n\n```ts\nexport type ServerDisplayRow<TData> =\n | ServerGroupRow<TData>\n | ServerLeafRow<TData>\n | ServerDetailRow<TData>\n | ServerMoreRow\n | ServerFooterRow<TData>\n | ServerSkeletonRow\n | ServerGrandTotalRow<TData>\n```\n\n### `type ServerResult`\n\nWhat `getRows` answers with: the rows for the requested range and the\ncount after filtering, plus the grand total and the pivot fields when\nasked for.\n\n```ts\nexport type ServerResult<TData> = {\n rows: ReadonlyArray<TData>\n /**\n * Total row count after filtering, for the pager and the scrollbar.\n *\n * Paging needs it. Infinite scrolling does not: send `-1` (or, from a\n * source typed loosely, omit it) when counting is expensive, and the grid\n * discovers the end from the first short block instead. See\n * `mode: 'infinite'` on {@link ServerControllerOptions}.\n */\n rowCount: number\n /**\n * Set `true` ONLY when `filterModel.expression` was applied in full. Leave it\n * unset if you ignored the expression; the grid then warns rather than\n * pretending the filter ran. See the contract on `ServerFilterModel.expression`.\n */\n appliedExpression?: boolean\n /**\n * The grand-total row, in reply to `ServerRequest.needsGrandTotal`: an\n * object sets it, `null` removes it, and leaving it out keeps whatever the\n * grid already had. Shaped like a group row: the aggregate values live\n * under their column ids.\n */\n grandTotal?: TData | null\n /**\n * Pivot mode: the fields the group rows carry for the pivoted values,\n * e.g. `[\"2024_amount\", \"2025_amount\"]`, from which the grid builds one\n * column per field under a header group per pivot key. Send the full\n * list on every pivoted response; the grid keeps the union. Every group\n * row carries every listed field, `null` where no rows fall in that\n * cell.\n */\n pivotResultFields?: string[]\n /**\n * Pivot mode, the long way: full column definitions instead of field\n * names, for a backend that wants to name and format them itself. Wins\n * over `pivotResultFields` when both are present.\n */\n pivotResultColumns?: ReadonlyArray<unknown>\n}\n```\n\n### `type ServerSelectionRule`\n\nA selection expressed as a rule rather than a list, for `updateWhere`.\nThe flat shape is \"these ids\" or \"everything except these\"; the nested\nshape is the same idea per group, keyed by group key or leaf id, as the\nEnterprise row model keeps it under `groupSelects: 'descendants'`.\n\n```ts\nexport type ServerSelectionRule =\n | { selectAll: boolean; toggled: string[] }\n | {\n selectAllChildren: boolean\n toggled: Record<string, { selectAllChildren: boolean; toggled: Record<string, unknown>; group?: boolean }>\n group?: boolean\n /** The group columns the tree's levels are keyed by, outer to inner. */\n groupBy?: string[]\n }\n```\n\n### `type ServerDataSource`\n\nThe contract a backend implements: `getRows`, and optionally the write\nmethods, a bulk edit by rule and `destroy`.\n\n```ts\nexport type ServerDataSource<TData> = {\n getRows(request: ServerRequest): Promise<ServerResult<TData>>\n /**\n * Optional write side. Implement whichever your backend supports; the\n * controller exposes matching `createRow` / `updateRow` / `deleteRow`\n * methods that call through and then `refresh()` the current page.\n * Calling a controller method whose source counterpart is missing throws.\n */\n createRow?(input: Partial<TData>): Promise<TData>\n updateRow?(id: string, patch: Partial<TData>): Promise<TData>\n deleteRow?(id: string): Promise<void>\n /**\n * Apply one patch to every row a selection RULE names, server-side - the\n * write behind a bulk edit of rows the grid never loaded. `filterModel`\n * scopes the rows exactly as `getRows` does; `selection` is the rule:\n * either \"these ids\" (`selectAll: false`) or \"everything but these\"\n * (`selectAll: true`), or the per-group tree the Enterprise row model\n * keeps under `groupSelects: 'descendants'`. Resolve with how many rows\n * changed. Optional: without it, a bulk edit under select-all is refused\n * rather than silently applied to the loaded rows only.\n */\n updateWhere?(\n filterModel: ServerFilterModel,\n patch: Partial<TData>,\n selection: ServerSelectionRule,\n ): Promise<number>\n /**\n * Called once, from the controller's `dispose()`, for a source with\n * something to close: a socket, a subscription, a worker.\n */\n destroy?(): void\n}\n```\n\n### `type ServerState`\n\nWhat `createServerDataSource` emits on every change: the rows on hand,\nthe counts, the loading and saving flags, the last error, and the\ncurrent sort and filter.\n\n```ts\nexport type ServerState<TData> = {\n rows: ReadonlyArray<TData>\n total: number\n loading: boolean\n /** True while a create / update / delete mutation is in flight. */\n saving: boolean\n error: unknown\n pageIndex: number\n pageSize: number\n pageCount: number\n sortModel: ServerSortModel\n filterModel: ServerFilterModel\n /**\n * True when an advanced-filter expression was sent but the source did not\n * acknowledge applying it - so `rows` is unfiltered and the UI should say so.\n * Surface this rather than hiding it: the rows look perfectly normal.\n *\n * Optional so existing code that builds a `ServerState` literal keeps\n * compiling; the controller always sets it.\n */\n expressionUnapplied?: boolean\n /**\n * Rows after filtering, or `null` when the backend has not said and the\n * end has not been found yet. Only ever null in `infinite` mode; `total`\n * carries the best current guess either way.\n */\n rowCount?: number | null\n /** False while the end of an infinite list is still being discovered. */\n lastRowKnown?: boolean\n /** Blocks whose fetch failed, in `infinite` mode. Empty when all is well. */\n failedBlocks?: number[]\n}\n```\n\n### `type ServerController`\n\nEverything a controller can do, plus the {@link GridRowModel} surface, so\none object can be driven by hand OR handed to `<SvGrid rowModel>` and wire\nitself up.\n\n```ts\nexport type ServerController<TData> = GridRowModel<TData> & {\n /** Re-fetch the current page (e.g. after a mutation). */\n refresh(): void\n /**\n * The rows on screen, so `infinite` mode knows which blocks to fetch and\n * which to spare from eviction. Wire it to the grid's\n * `onVisibleRangeChange` - or pass the controller as `rowModel` and the\n * grid wires it for you. No-op in `page` mode.\n */\n setViewport(startIndex: number, endIndex: number): void\n /** Re-fetch the blocks that failed. No-op in `page` mode. */\n retryLoads(): void\n /**\n * Throw away every cached block and reload from the current viewport.\n * `refresh()` is the gentler option: it keeps the row count and the scroll\n * position. No-op in `page` mode, where there is only ever one page held.\n */\n purge(): void\n /** Cached blocks and their state, for logging and tests. Empty in `page` mode. */\n getCacheState(): BlockState[]\n setSort(sortModel: ServerSortModel): void\n /**\n * Replace the filter. Takes the `ServerFilterModel` a request carries, or\n * the payload the grid's own `onFiltersChange` hands you - which is a\n * list of columns rather than a map, and is converted here so that every\n * app does not write the same `Object.fromEntries` by hand.\n */\n setFilter(filterModel: ServerFilterModel | GridFilterState): void\n setPage(pageIndex: number): void\n setPageSize(pageSize: number): void\n /**\n * Create a row through the source, then refresh the current page. Resolves\n * with the created row. Rejects if the source has no `createRow` (or if the\n * create itself fails - the read state is left untouched on failure).\n */\n createRow(input: Partial<TData>): Promise<TData>\n /**\n * Update a row by id through the source. Non-optimistic: refreshes the page.\n * Optimistic (see `optimistic` + `getRowId` options): patches the local row\n * immediately, then reconciles with the server result, rolling back on error.\n */\n updateRow(id: string, patch: Partial<TData>): Promise<TData>\n /**\n * Delete a row by id through the source. Non-optimistic: refreshes the page.\n * Optimistic: removes the local row immediately, restoring it on error.\n */\n deleteRow(id: string): Promise<void>\n getState(): ServerState<TData>\n /** Stop accepting in-flight responses (call on unmount). */\n dispose(): void\n}\n```\n\n### `type ServerControllerOptions`\n\nOptions for `createServerDataSource`: the page size, or the block\nsettings in `infinite` mode, optimistic writes and the change callback.\n\n```ts\nexport type ServerControllerOptions<TData> = {\n pageSize?: number\n /** Called whenever any of `rows` / `total` / `loading` / page changes. */\n onChange?: (state: ServerState<TData>) => void\n /**\n * Apply `updateRow` / `deleteRow` to the local rows immediately (before the\n * server confirms) and roll back on error - so edits feel instant and no\n * refetch is needed. Requires `getRowId` to locate rows; ignored without it.\n * A subsequent `refresh()` reconciles ordering/filtering. Default false.\n */\n optimistic?: boolean\n /** Resolve a row's stable id, so optimistic update/delete can find it in `rows`. */\n getRowId?: (row: TData) => string\n /**\n * How rows reach the grid.\n *\n * - `page` (default): one page at a time. `state.rows` is that page, and\n * `setPage` moves between them.\n * - `infinite`: one long scrollable list. `state.rows` spans the whole\n * result, with placeholder rows standing in for blocks nobody has\n * scrolled to yet; blocks load as the viewport reaches them.\n */\n mode?: 'page' | 'infinite'\n /** `infinite` mode: rows per request. Default 100. */\n blockSize?: number\n /**\n * `infinite` mode: keep at most this many loaded blocks, evicting the\n * least recently seen. Unlimited by default.\n */\n maxBlocksInCache?: number\n /** `infinite` mode: requests open at once. Default 2. */\n maxConcurrentRequests?: number\n /** `infinite` mode: wait for the scroll to settle this long before fetching. */\n blockLoadDebounceMs?: number\n /**\n * `infinite` mode: rows to claim before anything has loaded, so there is a\n * scrollbar on first paint. Default 1.\n */\n initialRowCount?: number\n}\n```\n\n### `function createServerDataSource`\n\nThe free server row model over a `ServerDataSource`: one page at a time,\nor one block-cached list in `infinite` mode, with sort, filter, race\nsafety and writes. The result is a `GridRowModel`, so\n`<SvGrid rowModel={ctl} />` wires every seam.\n\n```ts\nexport function createServerDataSource<TData>(\n source: ServerDataSource<TData>,\n options: ServerControllerOptions<TData>,\n): ServerController<TData>\n```\n"
8094
8165
  },
8095
8166
  {
8096
8167
  "slug": "reference/auto/svgrid-grid-spreadsheet",
8097
8168
  "path": "docs/reference/auto/svgrid-grid-spreadsheet.md",
8098
8169
  "title": "@svgrid/grid · spreadsheet.ts",
8099
8170
  "section": "API reference",
8100
- "markdown": "# `@svgrid/grid` · `spreadsheet.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\spreadsheet.ts`.\n\n### `type BorderSpec`\n\nA single edge of a cell border.\n\n```ts\nexport type BorderSpec = {\n /** Thickness in pixels. Default 2. */\n width?: number\n /** CSS border-style. Default 'solid'. */\n style?: 'solid' | 'dashed' | 'dotted' | 'double'\n /** CSS color. Falls back to currentColor (i.e. text color). */\n color?: string\n}\n```\n\n### `type MergeSpec`\n\nA merge declaration. The cell at (rowIndex, columnId) is the ORIGIN;\n it spans `colspan` columns to the right + `rowspan` rows downward.\n Covered cells are hidden so the origin visually fills the region.\n\n```ts\nexport type MergeSpec = {\n /** Display-row index — the same value the grid puts on\n * `data-svgrid-row`. After sorting/filtering, recompute the spec\n * against the new display order. */\n rowIndex: number\n columnId: string\n /** Default 1. */\n rowspan?: number\n /** Default 1. */\n colspan?: number\n}\n```\n\n### `type SpanColumn`\n\nA column with declarative spanning callbacks, as accepted by\n `spansToMerges`. Matches the relevant slice of `ColumnDef`.\n\n```ts\nexport type SpanColumn<TData = Record<string, unknown>> = {\n id: string\n field?: string\n colSpan?: (params: { data: TData; rowIndex: number; columnId: string; value: unknown }) => number\n rowSpan?: (params: { data: TData; rowIndex: number; columnId: string; value: unknown }) => number\n}\n```\n\n### `function spansToMerges`\n\nTurn declarative per-column `colSpan` / `rowSpan` callbacks into a\n`MergeSpec[]` you can hand to `spreadsheetLayout` - so value-driven,\nDeclarative spanning runs on the SAME real colspan/rowspan merge engine\ninstead of a second code path. Recompute after sort/filter (indexes are\ndisplay-row indexes). A common pattern is \"merge runs of equal values\":\n\n { field: 'region', rowSpan: ({ data, rowIndex }) =>\n rows.filter((r, i) => i >= rowIndex && r.region === data.region &&\n (i === rowIndex || rows[i-1].region === data.region)).length }\n\n```ts\nexport function spansToMerges<TData = Record<string, unknown>>(\n rows: ReadonlyArray<TData>,\n columns: ReadonlyArray<SpanColumn<TData>>,\n getValue?: (row: TData, columnId: string) => unknown,\n): MergeSpec[] {\n const merges: MergeSpec[] = []\n const covered = new Set<string>()\n for (let r = 0; r < rows.length; r += 1) {\n const row = rows[r]!\n for (let ci = 0; ci < columns.length; ci += 1) {\n const col = columns[ci]!\n if (!col.colSpan && !col.rowSpan) continue\n const key = `${r}:${ci}`\n if (covered.has(key)) continue\n const value = getValue\n ? getValue(row, col.id)\n : (row as Record<string, unknown>)[col.field ?? col.id]\n const params = { data: row, rowIndex: r, columnId: col.id, value }\n const cs = Math.max(1, Math.floor(col.colSpan?.(params) ?? 1))\n const rs = Math.max(1, Math.floor(col.rowSpan?.(params) ?? 1))\n if (cs <= 1 && rs <= 1) continue\n merges.push({\n rowIndex: r,\n columnId: col.id,\n colspan: cs > 1 ? cs : undefined,\n rowspan: rs > 1 ? rs : undefined,\n })\n for (let dr = 0; dr < rs; dr += 1) {\n for (let dc = 0; dc < cs; dc += 1) {\n if (dr === 0 && dc === 0) continue\n covered.add(`${r + dr}:${ci + dc}`)\n }\n }\n }\n }\n return merges\n}\n```\n\n### `type CellBorderSpec`\n\nBorders for one cell. Edges left unset render as the default\n cell border (i.e. no override).\n\n```ts\nexport type CellBorderSpec = {\n rowIndex: number\n columnId: string\n top?: BorderSpec\n right?: BorderSpec\n bottom?: BorderSpec\n left?: BorderSpec\n}\n```\n\n### `type SpreadsheetActionOptions`\n\nWhat the Svelte action receives. Pass new values to update; pass\n `null` / empty arrays to clear.\n\n```ts\nexport type SpreadsheetActionOptions = {\n merges?: ReadonlyArray<MergeSpec> | null\n borders?: ReadonlyArray<CellBorderSpec> | null\n /** Column id order the grid uses, in left-to-right order. Required\n * to translate `colspan` into the right set of covered column ids.\n * Pass `columns.map((c) => c.id)` from the consumer. */\n columnOrder: ReadonlyArray<string>\n}\n```\n\n### `function spreadsheetLayout`\n\nSvelte action. Attach to the element that hosts your `<SvGrid>` so\n the action can watch its DOM for re-renders.\n\n```svelte\n<div use:spreadsheetLayout={{ merges, borders, columnOrder }}>\n <SvGrid {data} {columns} ... />\n</div>\n```\n\nThe action re-applies the layout whenever the grid's body mutates\n(new rows, column reorder, virtualization scroll) and whenever the\noptions change.\n\n```ts\nexport function spreadsheetLayout(node: HTMLElement, opts: SpreadsheetActionOptions) {\n let current = opts\n let frame = 0\n const OBSERVE_OPTIONS: MutationObserverInit = {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [\n 'data-svgrid-row', 'data-col-id', 'style',\n // Watch selection-range attrs so we can transfer them from\n // hidden covered cells to merge origins.\n 'data-range-top', 'data-range-bottom', 'data-range-left',\n 'data-range-right', 'data-selected-range',\n ],\n }\n // The MutationObserver fires for EVERY DOM change inside the grid -\n // batch them into one rAF so a big virtualization scroll doesn't run\n // apply() dozens of times in a tick.\n function schedule() {\n if (frame) return\n frame = requestAnimationFrame(() => {\n frame = 0\n // Stop observing while apply() mutates the DOM itself (it writes cell\n // `style.display`/`position` and appends overlay children). Otherwise\n // those writes re-trigger this observer and loop at 60fps on merged\n // cells (#50). A full apply() recomputes from the live DOM, so discarding\n // the queued records here loses nothing.\n observer.disconnect()\n apply(node, current)\n observer.observe(node, OBSERVE_OPTIONS)\n })\n }\n const observer = new MutationObserver(schedule)\n observer.observe(node, OBSERVE_OPTIONS)\n // First-paint pass: schedule the same way so we don't run before the\n // grid's initial render landed.\n schedule()\n return {\n update(next: SpreadsheetActionOptions) {\n current = next\n schedule()\n },\n destroy() {\n observer.disconnect()\n if (frame) cancelAnimationFrame(frame)\n },\n }\n}\n```\n"
8171
+ "markdown": "# `@svgrid/grid` · `spreadsheet.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\spreadsheet.ts`.\n\n### `type BorderSpec`\n\nA single edge of a cell border.\n\n```ts\nexport type BorderSpec = {\n /** Thickness in pixels. Default 2. */\n width?: number\n /** CSS border-style. Default 'solid'. */\n style?: 'solid' | 'dashed' | 'dotted' | 'double'\n /** CSS color. Falls back to currentColor (i.e. text color). */\n color?: string\n}\n```\n\n### `type MergeSpec`\n\nA merge declaration. The cell at (rowIndex, columnId) is the ORIGIN;\n it spans `colspan` columns to the right + `rowspan` rows downward.\n Covered cells are hidden so the origin visually fills the region.\n\n```ts\nexport type MergeSpec = {\n /** Display-row index — the same value the grid puts on\n * `data-svgrid-row`. After sorting/filtering, recompute the spec\n * against the new display order. */\n rowIndex: number\n columnId: string\n /** Default 1. */\n rowspan?: number\n /** Default 1. */\n colspan?: number\n}\n```\n\n### `type SpanColumn`\n\nA column with declarative spanning callbacks, as accepted by\n `spansToMerges`. Matches the relevant slice of `ColumnDef`.\n\n```ts\nexport type SpanColumn<TData = Record<string, unknown>> = {\n id: string\n field?: string\n colSpan?: (params: { data: TData; rowIndex: number; columnId: string; value: unknown }) => number\n rowSpan?: (params: { data: TData; rowIndex: number; columnId: string; value: unknown }) => number\n}\n```\n\n### `function spansToMerges`\n\nTurn declarative per-column `colSpan` / `rowSpan` callbacks into a\n`MergeSpec[]` you can hand to `spreadsheetLayout` - so value-driven,\nDeclarative spanning runs on the SAME real colspan/rowspan merge engine\ninstead of a second code path. Recompute after sort/filter (indexes are\ndisplay-row indexes). A common pattern is \"merge runs of equal values\":\n\n { field: 'region', rowSpan: ({ data, rowIndex }) =>\n rows.filter((r, i) => i >= rowIndex && r.region === data.region &&\n (i === rowIndex || rows[i-1].region === data.region)).length }\n\n```ts\nexport function spansToMerges<TData = Record<string, unknown>>(\n rows: ReadonlyArray<TData>,\n columns: ReadonlyArray<SpanColumn<TData>>,\n getValue?: (row: TData, columnId: string) => unknown,\n): MergeSpec[]\n```\n\n### `type CellBorderSpec`\n\nBorders for one cell. Edges left unset render as the default\n cell border (i.e. no override).\n\n```ts\nexport type CellBorderSpec = {\n rowIndex: number\n columnId: string\n top?: BorderSpec\n right?: BorderSpec\n bottom?: BorderSpec\n left?: BorderSpec\n}\n```\n\n### `type SpreadsheetActionOptions`\n\nWhat the Svelte action receives. Pass new values to update; pass\n `null` / empty arrays to clear.\n\n```ts\nexport type SpreadsheetActionOptions = {\n merges?: ReadonlyArray<MergeSpec> | null\n borders?: ReadonlyArray<CellBorderSpec> | null\n /** Column id order the grid uses, in left-to-right order. Required\n * to translate `colspan` into the right set of covered column ids.\n * Pass `columns.map((c) => c.id)` from the consumer. */\n columnOrder: ReadonlyArray<string>\n}\n```\n\n### `function spreadsheetLayout`\n\nSvelte action. Attach to the element that hosts your `<SvGrid>` so\n the action can watch its DOM for re-renders.\n\n```svelte\n<div use:spreadsheetLayout={{ merges, borders, columnOrder }}>\n <SvGrid {data} {columns} ... />\n</div>\n```\n\nThe action re-applies the layout whenever the grid's body mutates\n(new rows, column reorder, virtualization scroll) and whenever the\noptions change.\n\n```ts\nexport function spreadsheetLayout(node: HTMLElement, opts: SpreadsheetActionOptions)\n```\n"
8101
8172
  },
8102
8173
  {
8103
8174
  "slug": "reference/auto/svgrid-grid-svgrid-wrapper.types",
8104
8175
  "path": "docs/reference/auto/svgrid-grid-svgrid-wrapper.types.md",
8105
8176
  "title": "@svgrid/grid · svgrid-wrapper.types.ts",
8106
8177
  "section": "API reference",
8107
- "markdown": "# `@svgrid/grid` · `svgrid-wrapper.types.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\svgrid-wrapper.types.ts`.\n\n### `type SvGridFilterOperator`\n\nThe comparisons a column filter can use, as shown in the filter menu.\n\n```ts\nexport type SvGridFilterOperator = FilterOperator\n```\n\n### `type SvGridViewState`\n\nA serializable snapshot of everything that makes up the current \"view\":\nsort, grouping, pagination, column layout (width / pinning / order /\nvisibility), and all filter surfaces. Round-trippable through\n`api.getState()` / `api.setState()` - persist it to a URL, localStorage, or\na server to implement \"save view\" / \"named views\".\n\n```ts\nexport type SvGridViewState = {\n sorting: Array<{ id: string; desc: boolean }>\n grouping: string[]\n pagination: { pageIndex: number; pageSize: number }\n columnWidths: Record<string, number>\n columnPinning: { left: string[]; right: string[] }\n columnOrder: string[]\n /** Ids of columns currently hidden via setColumnVisible. */\n hiddenColumns: string[]\n globalFilter: string\n columnFilters: Record<\n string,\n { operator: SvGridFilterOperator; value: string; valueTo?: string }\n >\n /** Facet (Excel-style value checklist) selections, keyed by column id. */\n facetFilters: Record<string, string[]>\n /**\n * Advanced-filter expression (Pro). OPTIONAL, and omitted entirely when no\n * advanced filter is set - so views saved before this feature existed, and\n * views from grids that never use it, round-trip byte-identical. An explicit\n * `null` clears the filter on `setState`.\n */\n advancedFilter?: GridPredicateExpr | null\n /** Built-in chart panel state (present only when `charting` is on): the\n * ACTIVE chart, for back-compat + spread-and-tweak. */\n chart?: {\n open: boolean\n type: ChartType\n dimension: string | null\n series: string | null\n measure: string | null\n reduce: 'sum' | 'avg' | 'count'\n stacked: boolean\n }\n /** All charts in the tab strip (multi-chart), plus the active index.\n * Every field the panel can change is here so a saved view restores the\n * chart exactly; `null` inherits the `charting` config. */\n charts?: ChartTabSnapshot[]\n chartActive?: number\n /** The named charts kept with `api.saveChart`; present only when there is one. */\n savedCharts?: SavedChart[]\n}\n```\n\n### `type ChartTabSnapshot`\n\nOne chart tab as the saved view carries it (`GridState.charts[i]`).\n\n```ts\nexport type ChartTabSnapshot = {\n title: string\n type: ChartType\n dimension: string | null\n series: string | null\n measure: string | null\n /** Scatter's y measure, a range's high, a bullet's target. */\n measure2?: string | null\n reduce: ChartReducer\n stacked: boolean | null\n stacked100?: boolean | null\n orientation?: 'vertical' | 'horizontal' | null\n donut?: boolean | null\n palette?: string[] | null\n dataLabels: boolean | null\n logScale: boolean | null\n timeAxis: boolean | null\n valueFormat: 'number' | 'currency' | 'percent' | 'compact' | null\n bucket?: ChartTimeBucket | null\n bins?: number | null\n funnelShape?: 'trapezoid' | 'pyramid' | 'cone' | null\n candleStyle?: 'classic' | 'hollow' | 'heikin-ashi' | null\n /** The zoom window as category indices, or null for the whole chart. */\n zoom?: ChartZoomWindow | null\n ohlc?: { open: string | null; high: string | null; low: string | null; close: string | null; volume: string | null } | null\n indicators?: string[]\n format?: ChartFormatState | null\n /** An unlinked chart carries the spec it was frozen with. */\n frozen?: { spec: ChartSpec; at: string } | null\n}\n```\n\n### `type SavedChart`\n\nA chart configuration kept under a name (`api.saveChart`).\n\n```ts\nexport type SavedChart = {\n name: string\n /** ISO timestamp of the save. */\n savedAt: string\n /** The tab's state at the time; `applySavedChart` puts it on the active tab. */\n tab: ChartTabSnapshot\n}\n```\n\n### `type SvGridCellCoords`\n\nOne cell, in the 0-based display coordinates every selection method uses.\n\n```ts\nexport type SvGridCellCoords = { row: number; col: number }\n```\n\n### `type SvGridSelectedRange`\n\nA selected rectangle with its orientation kept: `from` is where the\nselection was started (the anchor) and `to` where it ended (the focus),\nso a range dragged upwards has `from.row > to.row`. `highlight` is the\nactive cell inside it. The same three fields as Handsontable's CellRange,\nso code written against `getSelectedRange()` there reads the same here.\n\n```ts\nexport type SvGridSelectedRange = {\n from: SvGridCellCoords\n to: SvGridCellCoords\n highlight: SvGridCellCoords\n}\n```\n\n### `type SvGridTransaction`\n\nA batch of row mutations for `api.applyTransaction`. `update` / `remove`\n(by id) match on `getRowId`; `remove` also accepts row object references.\n\n```ts\nexport type SvGridTransaction<TData> = {\n add?: ReadonlyArray<TData>\n update?: ReadonlyArray<TData>\n remove?: ReadonlyArray<TData | string>\n}\n```\n\n### `type SvGridTransactionResult`\n\nWhat a batched `applyTransaction` did: how many rows were added, updated and removed.\n\n```ts\nexport type SvGridTransactionResult = {\n added: number\n updated: number\n removed: number\n}\n```\n\n### `type SvGridApi`\n\nImperative API exposed via the `<SvGrid onApiReady>` callback. Use it for\ndata, column, filter, sort, group, and visibility operations from outside\nthe component.\n\n```ts\nexport type SvGridApi<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = {\n // ----- DOM -----\n /**\n * The grid's root element (`.sv-grid-root`), or null before mount and\n * after unmount. For measuring, focusing, or reading the theme the grid\n * is drawn with - the PDF export takes its colours from here.\n */\n getElement(): HTMLElement | null\n\n // ----- Cells -----\n /** Read a cell value from the underlying data at `rowIndex`. */\n getCellValue(rowIndex: number, columnId: string): unknown\n /** Write a cell value through the column's field. */\n setCellValue(rowIndex: number, columnId: string, value: unknown): void\n /**\n * Programmatically begin editing a cell (as a double-click would). Returns\n * `true` if editing started (cell exists, editable, editing enabled).\n */\n startEditing(rowIndex: number, columnId: string): boolean\n /**\n * Commit (default) or, with `cancel: true`, discard the active edit.\n * Returns `true` if there was an edit in progress.\n */\n stopEditing(cancel?: boolean): boolean\n\n // ----- Cell selection -----\n /**\n * Programmatically select one or more rectangular cell ranges. Each\n * range is `[rowStart, colStart, rowEnd, colEnd]` in 0-indexed grid\n * coordinates. Pass an empty array to clear the selection.\n *\n * Every range is honoured: the last one becomes the active range and\n * the others stay highlighted beside it, as after a Ctrl+drag. The\n * active cell goes to the last range's start corner.\n */\n selectCells(ranges: ReadonlyArray<readonly [number, number, number, number]>): void\n /**\n * The current cell-selection rectangles in the same shape `selectCells`\n * accepts, each normalised to `[minRow, minCol, maxRow, maxCol]`, in the\n * order they were selected with the active one last. Empty array when no\n * range is active.\n *\n * Handsontable's method of the same name. Two differences, both on\n * purpose: an empty array rather than `undefined`, so `getSelected()[0]`\n * never throws; and normalised corners, so a loop from the first row to\n * the last cannot run zero times because the range was dragged upwards.\n * For the orientation, and the active cell inside a range, use\n * `getSelectedRange()`.\n *\n * With cell selection off (`selectable={false}`) no rectangle is ever\n * recorded and this stays `[]`; the focused cell is `getActiveCell()`.\n */\n getSelected(): Array<[number, number, number, number]>\n /**\n * The most recently selected rectangle as `[startRow, startCol, endRow,\n * endCol]`, start being where the selection began, or `undefined` when\n * nothing is selected. Handsontable's `getSelectedLast()`, orientation\n * included: a range dragged upwards has `startRow > endRow`.\n */\n getSelectedLast(): [number, number, number, number] | undefined\n /**\n * Every selected rectangle with its orientation and active cell, oldest\n * first, or `undefined` when nothing is selected. Handsontable's\n * `getSelectedRange()`.\n */\n getSelectedRange(): SvGridSelectedRange[] | undefined\n /** The most recently selected rectangle, or `undefined`. Handsontable's\n * `getSelectedRangeLast()`. */\n getSelectedRangeLast(): SvGridSelectedRange | undefined\n\n // ----- Integrated charting (requires the `charting` prop) -----\n /** Open the built-in chart panel. */\n openChart(): void\n /** Close the built-in chart panel. */\n closeChart(): void\n /** The live chart spec the panel is rendering, or `null`. */\n getChartSpec(): ChartSpec | null\n /** Select cell rectangles + open the chart panel (scopes to the range). */\n chartRange(ranges?: ReadonlyArray<readonly [number, number, number, number]>): void\n /**\n * Configure the built-in chart panel's ACTIVE chart. Column references\n * accept a column id OR field name. Opens the panel unless `open === false`.\n */\n configureChart(config: {\n open?: boolean\n type?: ChartType\n dimension?: string | null\n series?: string | null\n measure?: string | null\n reduce?: ChartReducer\n stacked?: boolean\n dataLabels?: boolean\n logScale?: boolean\n timeAxis?: boolean\n valueFormat?: 'number' | 'currency' | 'percent' | 'compact'\n /** Group a date dimension by calendar unit; `null` returns to exact values. */\n bucket?: ChartTimeBucket | null\n /** Second measure: a scatter's Y, a range's high end, a bullet's target. */\n measure2?: string | null\n /** Histogram bin count; `null` for Sturges' rule. */\n bins?: number | null\n funnelShape?: 'trapezoid' | 'pyramid' | 'cone' | null\n candleStyle?: 'classic' | 'hollow' | 'heikin-ashi' | null\n /** Candlestick / OHLC: the price columns (ids or fields); `null` goes\n * back to guessing them from the column names. */\n ohlc?: { open?: string | null; high?: string | null; low?: string | null; close?: string | null; volume?: string | null } | null\n /** Indicator panes under a price chart (`volume`, `rsi`, `macd`,\n * `stochastic`, `atr`, `obv`) and overlays on it (`sma`, `ema`,\n * `bb`, `vwap`). */\n indicators?: Array<'volume' | 'rsi' | 'macd' | 'stochastic' | 'atr' | 'obv' | 'sma' | 'ema' | 'bb' | 'vwap'>\n /** The builder's format state (titles, axes, legend, per-series style);\n * `null` resets it. */\n format?: ChartFormatState | null\n /** `true` unlinks the chart from the grid (it keeps the spec it has),\n * `false` links it back. */\n frozen?: boolean\n /** Apply a saved chart (by name) to the active tab before the other keys. */\n saved?: string\n }): void\n /**\n * Keep the active chart's whole configuration (type, columns, aggregate,\n * switches, indicators, format, zoom) under a name. A same-named entry is\n * replaced. Saved charts travel with `getState()` / `setState()` and show\n * in the panel's Saved charts popover.\n */\n saveChart(name: string): void\n /** Apply a saved chart to the active tab, which keeps its title. `false` when no chart has that name. */\n applySavedChart(name: string): boolean\n removeSavedChart(name: string): void\n getSavedCharts(): SavedChart[]\n /**\n * Register a natural-language \"chart this\" handler. When set, the chart\n * panel shows an AI button. `@svgrid/enterprise`'s `enableAiCharting(api)`\n * fills this. Pass `null` to remove it.\n */\n setChartAiHandler(\n handler: ((prompt: string) => Promise<Record<string, unknown> | null>) | null,\n ): void\n /**\n * Register an \"explain this chart\" handler. When set, the chart panel's AI\n * row shows an Explain button that reads the active chart and shows the\n * summary and insights it returns. `enableAiCharting(api)` fills this with\n * `aiExplainChart`. Pass `null` to remove it.\n */\n setChartExplainHandler(handler: (() => Promise<{ summary: string; insights: string[] } | null>) | null): void\n\n // ----- Rows -----\n /** Add one row. `position` defaults to `'bottom'`. */\n addRow(row: TData, position?: 'top' | 'bottom' | number): void\n addRows(rows: ReadonlyArray<TData>, position?: 'top' | 'bottom' | number): void\n /** Remove a row at the given data-array index. */\n removeRow(rowIndex: number): void\n removeRows(rowIndices: ReadonlyArray<number>): void\n /**\n * Apply a batch of add / update / remove mutations in a SINGLE data update\n * (one re-render, not one per row) - the high-frequency / streaming path.\n * `update` and `remove`-by-id match rows via `getRowId`, so set that prop\n * for those to work; `remove` also accepts row object references. Returns\n * the counts actually applied.\n */\n applyTransaction(tx: SvGridTransaction<TData>): SvGridTransactionResult\n\n // ----- Columns -----\n /** Add one column. `position` defaults to `'right'`. */\n addColumn(\n column: ColumnDef<TFeatures, TData>,\n position?: 'left' | 'right' | number,\n ): void\n addColumns(\n columns: ReadonlyArray<ColumnDef<TFeatures, TData>>,\n position?: 'left' | 'right' | number,\n ): void\n /** Remove a column by id (or field when no id was provided). */\n removeColumn(columnId: string): void\n\n // ----- Visibility -----\n setColumnVisible(columnId: string, visible: boolean): void\n isColumnVisible(columnId: string): boolean\n\n // ----- Sort / group / filter -----\n /** Sort by one column (replaces any existing sort). Pass `null` to clear. */\n setSort(columnId: string, direction: 'asc' | 'desc' | null): void\n clearSort(): void\n setGroupBy(columnIds: ReadonlyArray<string>): void\n\n // ----- Options (runtime prop overrides) -----\n /**\n * Change a grid prop at runtime, e.g. `api.setOption('sortable', true)`. The\n * override is merged over the incoming prop and the grid re-renders reactively -\n * identical to the parent passing a new prop value. Pass `undefined` to clear the\n * override and fall back to the prop.\n *\n * Note: seed-once props are NOT retroactive - `initialSorting`,\n * `initialColumnPinning`, `initialHiddenColumns`, `columnOrder`, the initial\n * `pageSize`, and the one-shot `externalSort` / `externalFilter` are read at mount,\n * so overriding them later has no effect. Prefer the dedicated data path for\n * `data` / `columns` (this works, but the sync effects are the idiomatic route).\n */\n setOption<K extends keyof Props<TFeatures, TData>>(key: K, value: Props<TFeatures, TData>[K] | undefined): void\n /** Read a prop's effective value: the runtime override if set, else the incoming prop. */\n getOption<K extends keyof Props<TFeatures, TData>>(key: K): Props<TFeatures, TData>[K]\n /** Clear every runtime override set via `setOption`, reverting to the incoming props. */\n resetOptions(): void\n\n /** Set the operator filter for a column. Pass `null` to clear. */\n setFilter(\n columnId: string,\n filter:\n | {\n operator: SvGridFilterOperator\n value?: string\n /** Upper bound for the `between` operator. Required when `operator === 'between'`. */\n valueTo?: string\n /**\n * Optional SECOND condition on the same column, joined by `join`\n * (multi-condition filtering, e.g. \"> 100 AND < 500\").\n */\n operator2?: SvGridFilterOperator\n value2?: string\n valueTo2?: string\n /** How to combine the two conditions. Defaults to `'AND'`. */\n join?: 'AND' | 'OR'\n }\n | null,\n ): void\n /**\n * Set the facet (set-list, Excel-style multi-select) filter for a column.\n * Pass an empty array or `null` to clear it. The values restore the\n * checked state of the column-menu's value list - the engine then filters\n * the data to rows whose cell value is in the set. Used to restore\n * snapshots captured via `onFiltersChange`'s `selectedValues`.\n */\n setFacetFilter(columnId: string, values: ReadonlyArray<string> | null): void\n clearFilter(columnId: string): void\n /**\n * Drop cached async `editorOptions` so the next render refetches them.\n * Omit `columnId` to clear every column. Only affects columns whose\n * `editorOptions` returns a Promise - static lists are never refetched.\n */\n refreshEditorOptions(columnId?: string): void\n /**\n * Open the `contextMenu` at the pointer, for the cell at (rowIndex,\n * colIndex), from an element of your own: a spreadsheet's column letters\n * and row numbers offer the cell menu for the column or row they select.\n * Does nothing without a `contextMenu` prop.\n */\n openContextMenu(event: MouseEvent, rowIndex: number, colIndex: number): void\n /**\n * Clear every active column filter (menu, filter-row, set-list, global, and\n * the advanced filter). Resets the grid to \"no filtering\" in a single call.\n */\n clearAllFilters(): void\n /**\n * Set the advanced-filter expression (Pro). `null` clears it. Composed with\n * AND after the global, column and facet filters.\n *\n * Rows are only removed once `@svgrid/enterprise`'s `enableAdvancedFilter()`\n * has registered a compiler. Without it the expression is stored but nothing\n * is filtered - use `isAdvancedFilterActive()` to tell the two apart.\n */\n setAdvancedFilter(expr: GridPredicateExpr | null): void\n /** The current advanced-filter expression, or `null`. */\n getAdvancedFilter(): GridPredicateExpr | null\n /** Clear the advanced filter, leaving other filter surfaces untouched. */\n clearAdvancedFilter(): void\n /** Whether an expression is set AND an engine is registered to run it. */\n isAdvancedFilterActive(): boolean\n /**\n * Read the active column-menu filters as a snapshot. Keyed by column id.\n * Returns an empty object when nothing is filtered. `valueTo` is only\n * present when `operator === 'between'`.\n */\n getFilters(): Record<\n string,\n { operator: SvGridFilterOperator; value: string; valueTo?: string }\n >\n\n /**\n * Snapshot of the DATA rows the grid is displaying right now - after\n * filtering, sorting, grouping and pagination. Use this when you need the\n * visible result set (e.g. to export it as CSV).\n *\n * Group banner rows are not included: the return type is `TData`, and a\n * banner is not one of your rows. That matters while grouping is on, because\n * with every group collapsed this returns an EMPTY array even though the\n * grid visibly shows a banner per group. Count banners from `getState()`\n * rather than from the length of this.\n */\n getDisplayedRows(): ReadonlyArray<TData>\n\n /** Snapshot of the current data array (pre-pipeline). */\n getData(): ReadonlyArray<TData>\n\n /**\n * The stable id the grid keys a row by: what the `getRowId` prop\n * computed, or the row's position when no `getRowId` is set. Pass a\n * display index (the space `getActiveCell`, `scrollToRow` and the cell\n * methods use) or a row object; returns null for an unknown index or a\n * row that is not in the data. Pair with `selectRows`, `toggleRowSelected`\n * or an `applyTransaction` remove, all of which take these ids.\n */\n getRowId(row: number | TData): string | null\n\n /**\n * Snapshot of every column the grid currently knows about, in visual\n * order, with the human-readable header label. Use this when exporting\n * or building a column-picker UI - the data is read once, no\n * subscription. Hidden columns are included; check `visible` to filter.\n */\n getColumns(): ReadonlyArray<{\n id: string\n field?: string\n header: string\n visible: boolean\n /** The column's `format` config, when set. Lets an exporter reproduce\n * the on-screen display value (currency, date pattern, etc.). */\n format?: CellFormatConfig\n /** Effective horizontal alignment ('left' | 'center' | 'right'). */\n align?: 'left' | 'center' | 'right'\n /** The column's data type: `cellDataType`, or the one a built-in\n * `editorType` implies. Lets a filter or expression UI offer\n * type-appropriate operators whatever edits the cell. */\n cellDataType?: 'text' | 'number' | 'boolean' | 'date' | 'dateString'\n /** The column's `editorType`, when set: what edits it. */\n editorType?: string\n }>\n\n // ----- Free data export (CSV / TSV / JSON + clipboard) -----\n /**\n * Export the grid to a **CSV** file. Free in the community grid; the\n * richer Excel / PDF / styled formats live in @svgrid/enterprise. Values\n * are formatted as shown on screen (pass `rawValues: true` for raw). Rows\n * default to the current view (`rows: 'selected' | 'all'` to change).\n * Resolves with the serialized text; pass `download: false` to skip the\n * browser download and just get the string.\n */\n exportCsv(options?: GridExportOptions): Promise<string>\n /** Export the grid to a **TSV** file (tab-separated). See `exportCsv`. */\n exportTsv(options?: GridExportOptions): Promise<string>\n /** Export the grid to a **JSON** file (array of `{ field: value }`). */\n exportJson(options?: GridExportOptions): Promise<string>\n /**\n * Copy the grid to the system clipboard. `format: 'tsv'` (default) pastes\n * straight into Excel / Sheets; `'csv'` / `'markdown'` also supported.\n * Resolves with the copied text.\n */\n copyToClipboard(options?: GridClipboardOptions): Promise<string>\n\n /** Clear every checked row. Emits `onRowSelectionChange({}, [])`. */\n clearRowSelection(): void\n\n // ----- Column layout (width + pinning) -----\n /**\n * Set the width of one column in pixels. Identical to dragging the\n * column's resize handle. Width is clamped to `MIN_COLUMN_WIDTH`.\n */\n setColumnWidth(columnId: string, width: number): void\n /**\n * Snapshot of every column's current width (in pixels), keyed by\n * column id. Columns the user has never resized AND that have no\n * explicit `width` on their ColumnDef are reported at the grid-wide\n * default. Useful for \"save view\" + URL persistence.\n */\n getColumnWidths(): Record<string, number>\n /**\n * Snap one column's width to its widest visible cell (header text +\n * any rendered body cell). Equivalent to double-clicking the column's\n * resize handle. The grid also exposes this through the column menu's\n * \"Autosize\" item.\n */\n autosizeColumn(columnId: string): void\n /**\n * The height of a row in px: the one it was dragged or set to, else the\n * declared `rowHeight` (30 when none). `rowIndex` is a display index.\n */\n getRowHeight(rowIndex: number): number\n /**\n * Give a row its own height, the way dragging its grip does with\n * `rowResize`; `null` takes it back to the declared height. The height\n * belongs to the row (its id), so it follows the row through a sort and\n * survives the data being replaced. Ignored under `autoRowHeight`, where\n * the content decides.\n */\n setRowHeight(rowIndex: number, height: number | null): void\n /**\n * Fold a column to nothing, the way a spreadsheet hides one: it keeps\n * its index, its cells and its width, and takes no room until it is\n * unfolded. Unlike `setColumnVisible(id, false)`, which takes the\n * column out of the model and shifts every index after it, references\n * by index stay valid, so a sheet's formulas and formats are untouched.\n * Arrow keys, Tab and Enter step over a collapsed column.\n */\n setColumnCollapsed(columnId: string, collapsed: boolean): void\n isColumnCollapsed(columnId: string): boolean\n /**\n * Fold a row to nothing, the row-side twin of `setColumnCollapsed`.\n * `rowIndex` is a display index; the fold belongs to the row (its id)\n * and follows it through a sort.\n */\n setRowCollapsed(rowIndex: number, collapsed: boolean): void\n isRowCollapsed(rowIndex: number): boolean\n /** The `mergedCells` in force, copied: origins with their spans. */\n getMergedCells(): Array<{ rowIndex: number; colIndex: number; rowSpan: number; colSpan: number }>\n /** Run `autosizeColumn` on every column. */\n autosizeAllColumns(): void\n /**\n * Replace the column-pinning state in one call. Each entry is a\n * column id; the order in the array becomes the visible order along\n * the pinned edge.\n */\n setColumnPinning(pinning: {\n left?: ReadonlyArray<string>\n right?: ReadonlyArray<string>\n }): void\n /** Snapshot of the current column-pinning state. */\n getColumnPinning(): { left: string[]; right: string[] }\n\n // ----- Column reorder -----\n /**\n * Replace the column order. Pass an array of column ids in the\n * desired visual order. Unknown ids are skipped; columns not in the\n * array keep their existing relative position after the listed ones.\n * Fires `onColumnOrderChange` once the new order is applied. Pin\n * groups (`columnPinning.left` / `right`) are still applied on top.\n */\n setColumnOrder(order: ReadonlyArray<string>): void\n /**\n * Snapshot of the current visual column order - the same shape the\n * `onColumnOrderChange` callback receives. Useful for saving and\n * restoring a view layout.\n */\n getColumnOrder(): string[]\n\n // ----- Row expansion -----\n /**\n * Set whether a row (group node or expandable leaf) is expanded.\n * The `id` is the engine's row id - for grouped rows that's the\n * synthetic group key, `group_<field>_<value>` (e.g.\n * `\"group_department_Engineering\"`; a second level appends\n * `_<field>_<value>`). An id that matches no row is ignored silently.\n */\n setRowExpanded(id: string, expanded: boolean): void\n /** Expand every group node in the current grouped row model. */\n expandAllGroups(): void\n /** Collapse every expansion - resets expanded state to {}. */\n collapseAllGroups(): void\n\n // ----- Undo / redo -----\n /** Undo the most recent inline-edit. Returns false when the history is empty. */\n undo(): boolean\n /** Redo the most recently undone edit. Returns false when the redo stack is empty. */\n redo(): boolean\n /** True when there's at least one step on the undo stack. */\n canUndo(): boolean\n /** True when there's at least one step on the redo stack. */\n canRedo(): boolean\n /** Wipe both stacks (e.g. after a server save commits the buffer). */\n clearHistory(): void\n /**\n * Mark every step recorded from now on with `tag`, until the next call;\n * `undefined` stops the marking. The grid never reads the tag. It is for a\n * consumer that shows one of several data sets through the grid (a\n * workbook's sheets, say) and has to know which one the next Ctrl+Z would\n * change before it lets the grid apply it: it tags the steps with the data\n * set they were made on and asks `peekUndo` first.\n */\n setHistoryTag(tag: unknown): void\n /** The step the next `undo()` would apply, or null when there is none. A\n * multi-cell action carries one tag, so it reports as one. */\n peekUndo(): { tag: unknown } | null\n /** The step the next `redo()` would apply, or null when there is none. */\n peekRedo(): { tag: unknown } | null\n\n // ----- Keyboard commands -----\n /**\n * The same `GridCommandContext` a registered shortcut handler receives.\n *\n * Keyboard commands are handed one on every keystroke, but a button in a\n * ribbon or a toolbar has no keystroke to ride in on, and re-implementing\n * \"bold the selection\" against the api would give the button and the key\n * two code paths that drift. Both go through this instead.\n *\n * Live, not a snapshot: the object reads through to the grid, so one built\n * once at mount still reports the current selection.\n */\n getCommandContext(): GridCommandContext\n\n // ----- Find in grid -----\n /** Open the built-in find overlay (Ctrl+F also opens it). */\n openFind(): void\n /** Close the find overlay and clear the query. */\n closeFind(): void\n /** Update the find query programmatically (useful for app-wide command palettes). */\n setFindQuery(q: string): void\n /** Snapshot of the current find hits (rowIndex / colIndex / columnId). */\n getFindHits(): Array<{ rowIndex: number; colIndex: number; columnId: string }>\n\n // ----- Row selection (read + write) -----\n /**\n * The currently selected data rows (group-header rows excluded), in row-model\n * order. Read once - no subscription. The push-based equivalent is\n * `onRowSelectionChange`.\n */\n getSelectedRows(): TData[]\n /** The engine row ids of the selected rows. Keys into the selection record. */\n getSelectedRowIds(): string[]\n /**\n * Select rows by engine row id. By default this REPLACES the selection;\n * pass `additive: true` to add to the existing selection instead.\n */\n selectRows(ids: ReadonlyArray<string>, additive?: boolean): void\n /** Select every selectable (non-group) row in the current row model. */\n selectAllRows(): void\n /** Flip one row's selected state by id. */\n toggleRowSelected(id: string): void\n\n // ----- Pagination -----\n /**\n * Current pagination snapshot. `total` is the post-filter row count;\n * `pageCount` is derived from it and `pageSize` (always >= 1).\n */\n getPageInfo(): {\n pageIndex: number\n pageSize: number\n pageCount: number\n total: number\n }\n /** Jump to a 0-based page. Clamped to [0, pageCount - 1]. */\n setPage(pageIndex: number): void\n /** Advance one page (no-op past the last page). */\n nextPage(): void\n /** Go back one page (no-op before the first page). */\n prevPage(): void\n /** Jump to the first page. */\n firstPage(): void\n /** Jump to the last page. */\n lastPage(): void\n /** Change the page size, keeping the first visible row in view. */\n setPageSize(pageSize: number): void\n\n // ----- Navigation / scrolling -----\n /**\n * Scroll the body so the given row index is at the top of the viewport.\n * Works with virtualization on. Index is clamped to the row count.\n */\n scrollToRow(rowIndex: number): void\n /** The active (focused) cell, or null when nothing is focused. */\n getActiveCell(): { rowIndex: number; colIndex: number; columnId: string } | null\n /** Move the active cell. Both coordinates are clamped to the grid bounds. */\n setActiveCell(rowIndex: number, colIndex: number): void\n\n // ----- View state (save / restore) -----\n /**\n * Serializable snapshot of the whole view - sort, grouping, pagination,\n * column layout, and every filter surface. Pair with `setState` for\n * \"save view\" / URL persistence / named views.\n */\n getState(): SvGridViewState\n /**\n * Restore a view from a (partial) snapshot produced by `getState`. Only the\n * keys present are applied, so you can restore just the columns, just the\n * filters, etc.\n */\n setState(state: Partial<SvGridViewState>): void\n /** Force a recompute of the row pipeline + a re-render. */\n refresh(): void\n}\n```\n\n### `type SvGridWrapperProps`\n\nThe props `<SvGrid>` accepts. See the SvGrid reference for the full list with defaults.\n\n```ts\nexport type SvGridWrapperProps<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = {\n data: ReadonlyArray<TData>\n columns: Array<ColumnDef<TFeatures, TData>>\n /**\n * Feature set from `tableFeatures({ ... })`. Optional - the `sortable` /\n * `filterable` / `groupable` shortcuts inject the matching feature, so a\n * grid can be configured from the boolean shortcuts alone.\n */\n features?: TFeatures\n /**\n * Capability shortcuts. Every capability is OFF by default (a bare grid is\n * a plain read-only table); set a shortcut `true` to opt in.\n *\n * `sortable` - column sorting (injects `rowSortingFeature`)\n * `filterable` - column filtering (injects `columnFilteringFeature`)\n * `editable` - inline editing (alias of `enableInlineEditing`)\n * `groupable` - grouping controls (alias of `showGroupingControls`)\n * `pageable` - pagination footer (alias of `showPagination`)\n */\n sortable?: boolean\n filterable?: boolean\n editable?: boolean\n groupable?: boolean\n pageable?: boolean\n options?: Partial<SvGridOptions<TFeatures, TData>>\n loading?: boolean\n error?: string | null\n emptyMessage?: string\n showGlobalFilter?: boolean\n showColumnFilters?: boolean\n showGroupingControls?: boolean\n showRowSelection?: boolean\n showPagination?: boolean\n virtualization?: boolean\n /** Row height in pixels. Pass a function `(rowIndex) => px` for per-row\n * variable heights (e.g. when wiring up an interactive row-resize). */\n rowHeight?: number | ((rowIndex: number) => number)\n overscan?: number\n containerHeight?: number\n columnVirtualization?: boolean\n columnOverscan?: number\n columnWidth?: number\n showFilterMenu?: boolean\n showFilterRow?: boolean\n enableCellSelection?: boolean\n enableInlineEditing?: boolean\n enableRowSummaries?: boolean\n /** Shortcut alias for `enableRowSummaries`; wins when both are set. */\n summary?: boolean\n /** Receives the imperative grid API when the component is ready. */\n onApiReady?: (api: SvGridApi<TFeatures, TData>) => void\n}\n```\n"
8178
+ "markdown": "# `@svgrid/grid` · `svgrid-wrapper.types.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\svgrid-wrapper.types.ts`.\n\n### `type SvGridFilterOperator`\n\nThe comparisons a column filter can use, as shown in the filter menu.\n\n```ts\nexport type SvGridFilterOperator = FilterOperator\n```\n\n### `type SvGridViewState`\n\nA serializable snapshot of everything that makes up the current \"view\":\nsort, grouping, pagination, column layout (width / pinning / order /\nvisibility), and all filter surfaces. Round-trippable through\n`api.getState()` / `api.setState()` - persist it to a URL, localStorage, or\na server to implement \"save view\" / \"named views\".\n\n```ts\nexport type SvGridViewState = {\n sorting: Array<{ id: string; desc: boolean }>\n grouping: string[]\n pagination: { pageIndex: number; pageSize: number }\n columnWidths: Record<string, number>\n columnPinning: { left: string[]; right: string[] }\n columnOrder: string[]\n /** Ids of columns currently hidden via setColumnVisible. */\n hiddenColumns: string[]\n globalFilter: string\n columnFilters: Record<\n string,\n { operator: SvGridFilterOperator; value: string; valueTo?: string }\n >\n /** Facet (Excel-style value checklist) selections, keyed by column id. */\n facetFilters: Record<string, string[]>\n /**\n * Advanced-filter expression (Pro). OPTIONAL, and omitted entirely when no\n * advanced filter is set - so views saved before this feature existed, and\n * views from grids that never use it, round-trip byte-identical. An explicit\n * `null` clears the filter on `setState`.\n */\n advancedFilter?: GridPredicateExpr | null\n /**\n * Models of columns with a `customFilter`, keyed by column id. Omitted when\n * no column has one, so older views round-trip unchanged. On `setState`,\n * present replaces every model and `null` clears them.\n */\n customFilters?: Record<string, unknown> | null\n /** Built-in chart panel state (present only when `charting` is on): the\n * ACTIVE chart, for back-compat + spread-and-tweak. */\n chart?: {\n open: boolean\n type: ChartType\n dimension: string | null\n series: string | null\n measure: string | null\n reduce: 'sum' | 'avg' | 'count'\n stacked: boolean\n }\n /** All charts in the tab strip (multi-chart), plus the active index.\n * Every field the panel can change is here so a saved view restores the\n * chart exactly; `null` inherits the `charting` config. */\n charts?: ChartTabSnapshot[]\n chartActive?: number\n /** The named charts kept with `api.saveChart`; present only when there is one. */\n savedCharts?: SavedChart[]\n}\n```\n\n### `type ChartTabSnapshot`\n\nOne chart tab as the saved view carries it (`GridState.charts[i]`).\n\n```ts\nexport type ChartTabSnapshot = {\n title: string\n type: ChartType\n dimension: string | null\n series: string | null\n measure: string | null\n /** Scatter's y measure, a range's high, a bullet's target. */\n measure2?: string | null\n reduce: ChartReducer\n stacked: boolean | null\n stacked100?: boolean | null\n orientation?: 'vertical' | 'horizontal' | null\n donut?: boolean | null\n palette?: string[] | null\n dataLabels: boolean | null\n logScale: boolean | null\n timeAxis: boolean | null\n valueFormat: 'number' | 'currency' | 'percent' | 'compact' | null\n bucket?: ChartTimeBucket | null\n bins?: number | null\n funnelShape?: 'trapezoid' | 'pyramid' | 'cone' | null\n candleStyle?: 'classic' | 'hollow' | 'heikin-ashi' | null\n /** The zoom window as category indices, or null for the whole chart. */\n zoom?: ChartZoomWindow | null\n ohlc?: { open: string | null; high: string | null; low: string | null; close: string | null; volume: string | null } | null\n indicators?: string[]\n format?: ChartFormatState | null\n /** An unlinked chart carries the spec it was frozen with. */\n frozen?: { spec: ChartSpec; at: string } | null\n}\n```\n\n### `type SavedChart`\n\nA chart configuration kept under a name (`api.saveChart`).\n\n```ts\nexport type SavedChart = {\n name: string\n /** ISO timestamp of the save. */\n savedAt: string\n /** The tab's state at the time; `applySavedChart` puts it on the active tab. */\n tab: ChartTabSnapshot\n}\n```\n\n### `type SvGridCellCoords`\n\nOne cell, in the 0-based display coordinates every selection method uses.\n\n```ts\nexport type SvGridCellCoords = { row: number; col: number }\n```\n\n### `type SvGridSelectedRange`\n\nA selected rectangle with its orientation kept: `from` is where the\nselection was started (the anchor) and `to` where it ended (the focus),\nso a range dragged upwards has `from.row > to.row`. `highlight` is the\nactive cell inside it. The same three fields as Handsontable's CellRange,\nso code written against `getSelectedRange()` there reads the same here.\n\n```ts\nexport type SvGridSelectedRange = {\n from: SvGridCellCoords\n to: SvGridCellCoords\n highlight: SvGridCellCoords\n}\n```\n\n### `type SvGridTransaction`\n\nA batch of row mutations for `api.applyTransaction`. `update` / `remove`\n(by id) match on `getRowId`; `remove` also accepts row object references.\n\n```ts\nexport type SvGridTransaction<TData> = {\n add?: ReadonlyArray<TData>\n update?: ReadonlyArray<TData>\n remove?: ReadonlyArray<TData | string>\n}\n```\n\n### `type SvGridTransactionResult`\n\nWhat a batched `applyTransaction` did: how many rows were added, updated and removed.\n\n```ts\nexport type SvGridTransactionResult = {\n added: number\n updated: number\n removed: number\n}\n```\n\n### `type SvGridApi`\n\nImperative API exposed via the `<SvGrid onApiReady>` callback. Use it for\ndata, column, filter, sort, group, and visibility operations from outside\nthe component.\n\n```ts\nexport type SvGridApi<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = {\n // ----- DOM -----\n /**\n * The grid's root element (`.sv-grid-root`), or null before mount and\n * after unmount. For measuring, focusing, or reading the theme the grid\n * is drawn with - the PDF export takes its colours from here.\n */\n getElement(): HTMLElement | null\n\n // ----- Cells -----\n /** Read a cell value from the underlying data at `rowIndex`. */\n getCellValue(rowIndex: number, columnId: string): unknown\n /** Write a cell value through the column's field. */\n setCellValue(rowIndex: number, columnId: string, value: unknown): void\n /**\n * Programmatically begin editing a cell (as a double-click would). Returns\n * `true` if editing started (cell exists, editable, editing enabled).\n */\n startEditing(rowIndex: number, columnId: string): boolean\n /**\n * Commit (default) or, with `cancel: true`, discard the active edit.\n * Returns `true` if there was an edit in progress.\n */\n stopEditing(cancel?: boolean): boolean\n\n // ----- Cell selection -----\n /**\n * Programmatically select one or more rectangular cell ranges. Each\n * range is `[rowStart, colStart, rowEnd, colEnd]` in 0-indexed grid\n * coordinates. Pass an empty array to clear the selection.\n *\n * Every range is honoured: the last one becomes the active range and\n * the others stay highlighted beside it, as after a Ctrl+drag. The\n * active cell goes to the last range's start corner.\n */\n selectCells(ranges: ReadonlyArray<readonly [number, number, number, number]>): void\n /**\n * The current cell-selection rectangles in the same shape `selectCells`\n * accepts, each normalised to `[minRow, minCol, maxRow, maxCol]`, in the\n * order they were selected with the active one last. Empty array when no\n * range is active.\n *\n * Handsontable's method of the same name. Two differences, both on\n * purpose: an empty array rather than `undefined`, so `getSelected()[0]`\n * never throws; and normalised corners, so a loop from the first row to\n * the last cannot run zero times because the range was dragged upwards.\n * For the orientation, and the active cell inside a range, use\n * `getSelectedRange()`.\n *\n * With cell selection off (`selectable={false}`) no rectangle is ever\n * recorded and this stays `[]`; the focused cell is `getActiveCell()`.\n */\n getSelected(): Array<[number, number, number, number]>\n /**\n * The most recently selected rectangle as `[startRow, startCol, endRow,\n * endCol]`, start being where the selection began, or `undefined` when\n * nothing is selected. Handsontable's `getSelectedLast()`, orientation\n * included: a range dragged upwards has `startRow > endRow`.\n */\n getSelectedLast(): [number, number, number, number] | undefined\n /**\n * Every selected rectangle with its orientation and active cell, oldest\n * first, or `undefined` when nothing is selected. Handsontable's\n * `getSelectedRange()`.\n */\n getSelectedRange(): SvGridSelectedRange[] | undefined\n /** The most recently selected rectangle, or `undefined`. Handsontable's\n * `getSelectedRangeLast()`. */\n getSelectedRangeLast(): SvGridSelectedRange | undefined\n\n // ----- Integrated charting (requires the `charting` prop) -----\n /** Open the built-in chart panel. */\n openChart(): void\n /** Close the built-in chart panel. */\n closeChart(): void\n /** The live chart spec the panel is rendering, or `null`. */\n getChartSpec(): ChartSpec | null\n /** Select cell rectangles + open the chart panel (scopes to the range). */\n chartRange(ranges?: ReadonlyArray<readonly [number, number, number, number]>): void\n /**\n * Configure the built-in chart panel's ACTIVE chart. Column references\n * accept a column id OR field name. Opens the panel unless `open === false`.\n */\n configureChart(config: {\n open?: boolean\n type?: ChartType\n dimension?: string | null\n series?: string | null\n measure?: string | null\n reduce?: ChartReducer\n stacked?: boolean\n dataLabels?: boolean\n logScale?: boolean\n timeAxis?: boolean\n valueFormat?: 'number' | 'currency' | 'percent' | 'compact'\n /** Group a date dimension by calendar unit; `null` returns to exact values. */\n bucket?: ChartTimeBucket | null\n /** Second measure: a scatter's Y, a range's high end, a bullet's target. */\n measure2?: string | null\n /** Histogram bin count; `null` for Sturges' rule. */\n bins?: number | null\n funnelShape?: 'trapezoid' | 'pyramid' | 'cone' | null\n candleStyle?: 'classic' | 'hollow' | 'heikin-ashi' | null\n /** Candlestick / OHLC: the price columns (ids or fields); `null` goes\n * back to guessing them from the column names. */\n ohlc?: { open?: string | null; high?: string | null; low?: string | null; close?: string | null; volume?: string | null } | null\n /** Indicator panes under a price chart (`volume`, `rsi`, `macd`,\n * `stochastic`, `atr`, `obv`) and overlays on it (`sma`, `ema`,\n * `bb`, `vwap`). */\n indicators?: Array<'volume' | 'rsi' | 'macd' | 'stochastic' | 'atr' | 'obv' | 'sma' | 'ema' | 'bb' | 'vwap'>\n /** The builder's format state (titles, axes, legend, per-series style);\n * `null` resets it. */\n format?: ChartFormatState | null\n /** `true` unlinks the chart from the grid (it keeps the spec it has),\n * `false` links it back. */\n frozen?: boolean\n /** Apply a saved chart (by name) to the active tab before the other keys. */\n saved?: string\n }): void\n /**\n * Keep the active chart's whole configuration (type, columns, aggregate,\n * switches, indicators, format, zoom) under a name. A same-named entry is\n * replaced. Saved charts travel with `getState()` / `setState()` and show\n * in the panel's Saved charts popover.\n */\n saveChart(name: string): void\n /** Apply a saved chart to the active tab, which keeps its title. `false` when no chart has that name. */\n applySavedChart(name: string): boolean\n removeSavedChart(name: string): void\n getSavedCharts(): SavedChart[]\n /**\n * Register a natural-language \"chart this\" handler. When set, the chart\n * panel shows an AI button. `@svgrid/enterprise`'s `enableAiCharting(api)`\n * fills this. Pass `null` to remove it.\n */\n setChartAiHandler(\n handler: ((prompt: string) => Promise<Record<string, unknown> | null>) | null,\n ): void\n /**\n * Register an \"explain this chart\" handler. When set, the chart panel's AI\n * row shows an Explain button that reads the active chart and shows the\n * summary and insights it returns. `enableAiCharting(api)` fills this with\n * `aiExplainChart`. Pass `null` to remove it.\n */\n setChartExplainHandler(handler: (() => Promise<{ summary: string; insights: string[] } | null>) | null): void\n\n // ----- Rows -----\n /** Add one row. `position` defaults to `'bottom'`. */\n addRow(row: TData, position?: 'top' | 'bottom' | number): void\n addRows(rows: ReadonlyArray<TData>, position?: 'top' | 'bottom' | number): void\n /** Remove a row at the given data-array index. */\n removeRow(rowIndex: number): void\n removeRows(rowIndices: ReadonlyArray<number>): void\n /**\n * Apply a batch of add / update / remove mutations in a SINGLE data update\n * (one re-render, not one per row) - the high-frequency / streaming path.\n * `update` and `remove`-by-id match rows via `getRowId`, so set that prop\n * for those to work; `remove` also accepts row object references. Returns\n * the counts actually applied.\n */\n applyTransaction(tx: SvGridTransaction<TData>): SvGridTransactionResult\n\n // ----- Columns -----\n /** Add one column. `position` defaults to `'right'`. */\n addColumn(\n column: ColumnDef<TFeatures, TData>,\n position?: 'left' | 'right' | number,\n ): void\n addColumns(\n columns: ReadonlyArray<ColumnDef<TFeatures, TData>>,\n position?: 'left' | 'right' | number,\n ): void\n /** Remove a column by id (or field when no id was provided). */\n removeColumn(columnId: string): void\n\n // ----- Visibility -----\n setColumnVisible(columnId: string, visible: boolean): void\n isColumnVisible(columnId: string): boolean\n\n // ----- Sort / group / filter -----\n /** Sort by one column (replaces any existing sort). Pass `null` to clear. */\n setSort(columnId: string, direction: 'asc' | 'desc' | null): void\n clearSort(): void\n setGroupBy(columnIds: ReadonlyArray<string>): void\n\n // ----- Options (runtime prop overrides) -----\n /**\n * Change a grid prop at runtime, e.g. `api.setOption('sortable', true)`. The\n * override is merged over the incoming prop and the grid re-renders reactively -\n * identical to the parent passing a new prop value. Pass `undefined` to clear the\n * override and fall back to the prop.\n *\n * Note: seed-once props are NOT retroactive - `initialSorting`,\n * `initialColumnPinning`, `initialHiddenColumns`, `columnOrder`, the initial\n * `pageSize`, and the one-shot `externalSort` / `externalFilter` are read at mount,\n * so overriding them later has no effect. Prefer the dedicated data path for\n * `data` / `columns` (this works, but the sync effects are the idiomatic route).\n */\n setOption<K extends keyof Props<TFeatures, TData>>(key: K, value: Props<TFeatures, TData>[K] | undefined): void\n /** Read a prop's effective value: the runtime override if set, else the incoming prop. */\n getOption<K extends keyof Props<TFeatures, TData>>(key: K): Props<TFeatures, TData>[K]\n /** Clear every runtime override set via `setOption`, reverting to the incoming props. */\n resetOptions(): void\n\n /** Set the operator filter for a column. Pass `null` to clear. */\n setFilter(\n columnId: string,\n filter:\n | {\n operator: SvGridFilterOperator\n value?: string\n /** Upper bound for the `between` operator. Required when `operator === 'between'`. */\n valueTo?: string\n /**\n * Optional SECOND condition on the same column, joined by `join`\n * (multi-condition filtering, e.g. \"> 100 AND < 500\").\n */\n operator2?: SvGridFilterOperator\n value2?: string\n valueTo2?: string\n /** How to combine the two conditions. Defaults to `'AND'`. */\n join?: 'AND' | 'OR'\n }\n | null,\n ): void\n /**\n * Set the facet (set-list, Excel-style multi-select) filter for a column.\n * Pass an empty array or `null` to clear it. The values restore the\n * checked state of the column-menu's value list - the engine then filters\n * the data to rows whose cell value is in the set. Used to restore\n * snapshots captured via `onFiltersChange`'s `selectedValues`.\n */\n setFacetFilter(columnId: string, values: ReadonlyArray<string> | null): void\n /**\n * Set the model of a column's `customFilter` (whatever its `predicate`\n * takes: `[min, max]`, a tag list, ...). `null` clears it. ANDed with the\n * column's operator filter and Values checklist. Ignored for a column with\n * `filterable: false`.\n */\n setCustomFilter(columnId: string, model: unknown): void\n /** A column's custom-filter model, or `undefined` when none is set. */\n getCustomFilter(columnId: string): unknown\n /** Clear every filter on the column: condition, Values checklist and custom model. */\n clearFilter(columnId: string): void\n /**\n * Drop cached async `editorOptions` so the next render refetches them.\n * Omit `columnId` to clear every column. Only affects columns whose\n * `editorOptions` returns a Promise - static lists are never refetched.\n */\n refreshEditorOptions(columnId?: string): void\n /**\n * Open the `contextMenu` at the pointer, for the cell at (rowIndex,\n * colIndex), from an element of your own: a spreadsheet's column letters\n * and row numbers offer the cell menu for the column or row they select.\n * Does nothing without a `contextMenu` prop.\n */\n openContextMenu(event: MouseEvent, rowIndex: number, colIndex: number): void\n /**\n * Clear every active column filter (menu, filter-row, set-list, global, and\n * the advanced filter). Resets the grid to \"no filtering\" in a single call.\n */\n clearAllFilters(): void\n /**\n * Set the advanced-filter expression (Pro). `null` clears it. Composed with\n * AND after the global, column and facet filters.\n *\n * Rows are only removed once `@svgrid/enterprise`'s `enableAdvancedFilter()`\n * has registered a compiler. Without it the expression is stored but nothing\n * is filtered - use `isAdvancedFilterActive()` to tell the two apart.\n */\n setAdvancedFilter(expr: GridPredicateExpr | null): void\n /** The current advanced-filter expression, or `null`. */\n getAdvancedFilter(): GridPredicateExpr | null\n /** Clear the advanced filter, leaving other filter surfaces untouched. */\n clearAdvancedFilter(): void\n /** Whether an expression is set AND an engine is registered to run it. */\n isAdvancedFilterActive(): boolean\n /**\n * Read the active column-menu filters as a snapshot. Keyed by column id.\n * Returns an empty object when nothing is filtered. `valueTo` is only\n * present when `operator === 'between'`.\n */\n getFilters(): Record<\n string,\n { operator: SvGridFilterOperator; value: string; valueTo?: string }\n >\n\n /**\n * Snapshot of the DATA rows the grid is displaying right now - after\n * filtering, sorting, grouping and pagination. Use this when you need the\n * visible result set (e.g. to export it as CSV).\n *\n * Group banner rows are not included: the return type is `TData`, and a\n * banner is not one of your rows. That matters while grouping is on, because\n * with every group collapsed this returns an EMPTY array even though the\n * grid visibly shows a banner per group. Count banners from `getState()`\n * rather than from the length of this.\n */\n getDisplayedRows(): ReadonlyArray<TData>\n\n /** Snapshot of the current data array (pre-pipeline). */\n getData(): ReadonlyArray<TData>\n\n /**\n * Where a row sits in the filtered, sorted rows across every page, or null\n * when a filter hides it or it is inside a collapsed group. Without\n * grouping, `Math.floor(position / pageSize)` is its page under client\n * paging. With grouping, pages are counted in groups and that formula does\n * not hold.\n */\n getRowPosition(rowId: string): number | null\n\n /**\n * The stable id the grid keys a row by: what the `getRowId` prop\n * computed, or the row's position when no `getRowId` is set. Pass a\n * display index (the space `getActiveCell`, `scrollToRow` and the cell\n * methods use) or a row object; returns null for an unknown index or a\n * row that is not in the data. Pair with `selectRows`, `toggleRowSelected`\n * or an `applyTransaction` remove, all of which take these ids.\n */\n getRowId(row: number | TData): string | null\n\n /**\n * Snapshot of every column the grid currently knows about, in visual\n * order, with the human-readable header label. Use this when exporting\n * or building a column-picker UI - the data is read once, no\n * subscription. Hidden columns are included; check `visible` to filter.\n */\n getColumns(): ReadonlyArray<{\n id: string\n field?: string\n header: string\n visible: boolean\n /** The column's `format` config, when set. Lets an exporter reproduce\n * the on-screen display value (currency, date pattern, etc.). */\n format?: CellFormatConfig\n /** Effective horizontal alignment ('left' | 'center' | 'right'). */\n align?: 'left' | 'center' | 'right'\n /** The column's data type: `cellDataType`, or the one a built-in\n * `editorType` implies. Lets a filter or expression UI offer\n * type-appropriate operators whatever edits the cell. */\n cellDataType?: 'text' | 'number' | 'boolean' | 'date' | 'dateString'\n /** The column's `editorType`, when set: what edits it. */\n editorType?: string\n }>\n\n // ----- Free data export (CSV / TSV / JSON + clipboard) -----\n /**\n * Export the grid to a **CSV** file. Free in the community grid; the\n * richer Excel / PDF / styled formats live in @svgrid/enterprise. Values\n * are formatted as shown on screen (pass `rawValues: true` for raw). Rows\n * default to the current view (`rows: 'selected' | 'all'` to change).\n * Resolves with the serialized text; pass `download: false` to skip the\n * browser download and just get the string.\n */\n exportCsv(options?: GridExportOptions): Promise<string>\n /** Export the grid to a **TSV** file (tab-separated). See `exportCsv`. */\n exportTsv(options?: GridExportOptions): Promise<string>\n /** Export the grid to a **JSON** file (array of `{ field: value }`). */\n exportJson(options?: GridExportOptions): Promise<string>\n /**\n * Copy the grid to the system clipboard. `format: 'tsv'` (default) pastes\n * straight into Excel / Sheets; `'csv'` / `'markdown'` also supported.\n * Resolves with the copied text.\n */\n copyToClipboard(options?: GridClipboardOptions): Promise<string>\n\n /** Clear every checked row. Emits `onRowSelectionChange({}, [])`. */\n clearRowSelection(): void\n\n // ----- Column layout (width + pinning) -----\n /**\n * Set the width of one column in pixels. Identical to dragging the\n * column's resize handle. Width is clamped to `MIN_COLUMN_WIDTH`.\n */\n setColumnWidth(columnId: string, width: number): void\n /**\n * Snapshot of every column's current width (in pixels), keyed by\n * column id. Columns the user has never resized AND that have no\n * explicit `width` on their ColumnDef are reported at the grid-wide\n * default. Useful for \"save view\" + URL persistence.\n */\n getColumnWidths(): Record<string, number>\n /**\n * Snap one column's width to its widest visible cell (header text +\n * any rendered body cell). Equivalent to double-clicking the column's\n * resize handle. The grid also exposes this through the column menu's\n * \"Autosize\" item.\n */\n autosizeColumn(columnId: string): void\n /**\n * The height of a row in px: the one it was dragged or set to, else the\n * declared `rowHeight` (30 when none). `rowIndex` is a display index.\n */\n getRowHeight(rowIndex: number): number\n /**\n * Give a row its own height, the way dragging its grip does with\n * `rowResize`; `null` takes it back to the declared height. The height\n * belongs to the row (its id), so it follows the row through a sort and\n * survives the data being replaced. Ignored under `autoRowHeight`, where\n * the content decides.\n */\n setRowHeight(rowIndex: number, height: number | null): void\n /**\n * Fold a column to nothing, the way a spreadsheet hides one: it keeps\n * its index, its cells and its width, and takes no room until it is\n * unfolded. Unlike `setColumnVisible(id, false)`, which takes the\n * column out of the model and shifts every index after it, references\n * by index stay valid, so a sheet's formulas and formats are untouched.\n * Arrow keys, Tab and Enter step over a collapsed column.\n */\n setColumnCollapsed(columnId: string, collapsed: boolean): void\n isColumnCollapsed(columnId: string): boolean\n /**\n * Fold a row to nothing, the row-side twin of `setColumnCollapsed`.\n * `rowIndex` is a display index; the fold belongs to the row (its id)\n * and follows it through a sort.\n */\n setRowCollapsed(rowIndex: number, collapsed: boolean): void\n isRowCollapsed(rowIndex: number): boolean\n /** The `mergedCells` in force, copied: origins with their spans. */\n getMergedCells(): Array<{ rowIndex: number; colIndex: number; rowSpan: number; colSpan: number }>\n /** Run `autosizeColumn` on every column. */\n autosizeAllColumns(): void\n /**\n * Replace the column-pinning state in one call. Each entry is a\n * column id; the order in the array becomes the visible order along\n * the pinned edge.\n */\n setColumnPinning(pinning: {\n left?: ReadonlyArray<string>\n right?: ReadonlyArray<string>\n }): void\n /** Snapshot of the current column-pinning state. */\n getColumnPinning(): { left: string[]; right: string[] }\n\n // ----- Column reorder -----\n /**\n * Replace the column order. Pass an array of column ids in the\n * desired visual order. Unknown ids are skipped; columns not in the\n * array keep their existing relative position after the listed ones.\n * Fires `onColumnOrderChange` once the new order is applied. Pin\n * groups (`columnPinning.left` / `right`) are still applied on top.\n */\n setColumnOrder(order: ReadonlyArray<string>): void\n /**\n * Snapshot of the current visual column order - the same shape the\n * `onColumnOrderChange` callback receives. Useful for saving and\n * restoring a view layout.\n */\n getColumnOrder(): string[]\n\n // ----- Row expansion -----\n /**\n * Set whether a row (group node or expandable leaf) is expanded.\n * The `id` is the engine's row id - for grouped rows that's the\n * synthetic group key, `group_<field>_<value>` (e.g.\n * `\"group_department_Engineering\"`; a second level appends\n * `_<field>_<value>`). An id that matches no row is ignored silently.\n */\n setRowExpanded(id: string, expanded: boolean): void\n /** Expand every group node in the current grouped row model. */\n expandAllGroups(): void\n /** Collapse every expansion - resets expanded state to {}. */\n collapseAllGroups(): void\n\n // ----- Undo / redo -----\n /** Undo the most recent inline-edit. Returns false when the history is empty. */\n undo(): boolean\n /** Redo the most recently undone edit. Returns false when the redo stack is empty. */\n redo(): boolean\n /** True when there's at least one step on the undo stack. */\n canUndo(): boolean\n /** True when there's at least one step on the redo stack. */\n canRedo(): boolean\n /** Wipe both stacks (e.g. after a server save commits the buffer). */\n clearHistory(): void\n /**\n * Mark every step recorded from now on with `tag`, until the next call;\n * `undefined` stops the marking. The grid never reads the tag. It is for a\n * consumer that shows one of several data sets through the grid (a\n * workbook's sheets, say) and has to know which one the next Ctrl+Z would\n * change before it lets the grid apply it: it tags the steps with the data\n * set they were made on and asks `peekUndo` first.\n */\n setHistoryTag(tag: unknown): void\n /** The step the next `undo()` would apply, or null when there is none. A\n * multi-cell action carries one tag, so it reports as one. */\n peekUndo(): { tag: unknown } | null\n /** The step the next `redo()` would apply, or null when there is none. */\n peekRedo(): { tag: unknown } | null\n\n // ----- Keyboard commands -----\n /**\n * The same `GridCommandContext` a registered shortcut handler receives.\n *\n * Keyboard commands are handed one on every keystroke, but a button in a\n * ribbon or a toolbar has no keystroke to ride in on, and re-implementing\n * \"bold the selection\" against the api would give the button and the key\n * two code paths that drift. Both go through this instead.\n *\n * Live, not a snapshot: the object reads through to the grid, so one built\n * once at mount still reports the current selection.\n */\n getCommandContext(): GridCommandContext\n\n // ----- Find in grid -----\n /** Open the built-in find overlay (Ctrl+F also opens it). */\n openFind(): void\n /** Close the find overlay and clear the query. */\n closeFind(): void\n /** Update the find query programmatically (useful for app-wide command palettes). */\n setFindQuery(q: string): void\n /** Snapshot of the current find hits (rowIndex / colIndex / columnId). */\n getFindHits(): Array<{ rowIndex: number; colIndex: number; columnId: string }>\n\n // ----- Row selection (read + write) -----\n /**\n * The currently selected data rows (group-header rows excluded), in row-model\n * order. Read once - no subscription. The push-based equivalent is\n * `onRowSelectionChange`.\n */\n getSelectedRows(): TData[]\n /** The engine row ids of the selected rows. Keys into the selection record. */\n getSelectedRowIds(): string[]\n /**\n * Select rows by engine row id. By default this REPLACES the selection;\n * pass `additive: true` to add to the existing selection instead.\n */\n selectRows(ids: ReadonlyArray<string>, additive?: boolean): void\n /** Select every selectable (non-group) row in the current row model. */\n selectAllRows(): void\n /** Flip one row's selected state by id. */\n toggleRowSelected(id: string): void\n\n // ----- Pagination -----\n /**\n * Current pagination snapshot. `total` is the post-filter row count;\n * `pageCount` is derived from it and `pageSize` (always >= 1).\n */\n getPageInfo(): {\n pageIndex: number\n pageSize: number\n pageCount: number\n total: number\n }\n /** Jump to a 0-based page. Clamped to [0, pageCount - 1]. */\n setPage(pageIndex: number): void\n /** Advance one page (no-op past the last page). */\n nextPage(): void\n /** Go back one page (no-op before the first page). */\n prevPage(): void\n /** Jump to the first page. */\n firstPage(): void\n /** Jump to the last page. */\n lastPage(): void\n /** Change the page size, keeping the first visible row in view. */\n setPageSize(pageSize: number): void\n\n // ----- Navigation / scrolling -----\n /**\n * Scroll the body so the given row index is at the top of the viewport.\n * Works with virtualization on. Index is clamped to the row count.\n */\n scrollToRow(rowIndex: number): void\n /** The active (focused) cell, or null when nothing is focused. */\n getActiveCell(): { rowIndex: number; colIndex: number; columnId: string } | null\n /** Move the active cell. Both coordinates are clamped to the grid bounds. */\n setActiveCell(rowIndex: number, colIndex: number): void\n\n // ----- View state (save / restore) -----\n /**\n * Serializable snapshot of the whole view - sort, grouping, pagination,\n * column layout, and every filter surface. Pair with `setState` for\n * \"save view\" / URL persistence / named views.\n */\n getState(): SvGridViewState\n /**\n * Restore a view from a (partial) snapshot produced by `getState`. Only the\n * keys present are applied, so you can restore just the columns, just the\n * filters, etc.\n */\n setState(state: Partial<SvGridViewState>): void\n /** Force a recompute of the row pipeline + a re-render. */\n refresh(): void\n}\n```\n\n### `type SvGridWrapperProps`\n\nThe props `<SvGrid>` accepts. See the SvGrid reference for the full list with defaults.\n\n```ts\nexport type SvGridWrapperProps<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = {\n data: ReadonlyArray<TData>\n columns: Array<ColumnDef<TFeatures, TData>>\n /**\n * Feature set from `tableFeatures({ ... })`. Optional - the `sortable` /\n * `filterable` / `groupable` shortcuts inject the matching feature, so a\n * grid can be configured from the boolean shortcuts alone.\n */\n features?: TFeatures\n /**\n * Capability shortcuts. Every capability is OFF by default (a bare grid is\n * a plain read-only table); set a shortcut `true` to opt in.\n *\n * `sortable` - column sorting (injects `rowSortingFeature`)\n * `filterable` - column filtering (injects `columnFilteringFeature`)\n * `editable` - inline editing (alias of `enableInlineEditing`)\n * `groupable` - grouping controls (alias of `showGroupingControls`)\n * `pageable` - pagination footer (alias of `showPagination`)\n */\n sortable?: boolean\n filterable?: boolean\n editable?: boolean\n groupable?: boolean\n pageable?: boolean\n options?: Partial<SvGridOptions<TFeatures, TData>>\n loading?: boolean\n error?: string | null\n emptyMessage?: string\n showGlobalFilter?: boolean\n showColumnFilters?: boolean\n showGroupingControls?: boolean\n showRowSelection?: boolean\n showPagination?: boolean\n virtualization?: boolean\n /** Row height in pixels. Pass a function `(rowIndex) => px` for per-row\n * variable heights (e.g. when wiring up an interactive row-resize). */\n rowHeight?: number | ((rowIndex: number) => number)\n overscan?: number\n containerHeight?: number\n columnVirtualization?: boolean\n columnOverscan?: number\n columnWidth?: number\n showFilterMenu?: boolean\n showFilterRow?: boolean\n enableCellSelection?: boolean\n enableInlineEditing?: boolean\n enableRowSummaries?: boolean\n /** Shortcut alias for `enableRowSummaries`; wins when both are set. */\n summary?: boolean\n /** Receives the imperative grid API when the component is ready. */\n onApiReady?: (api: SvGridApi<TFeatures, TData>) => void\n}\n```\n"
8108
8179
  },
8109
8180
  {
8110
8181
  "slug": "reference/auto/svgrid-grid-timezone",
8111
8182
  "path": "docs/reference/auto/svgrid-grid-timezone.md",
8112
8183
  "title": "@svgrid/grid · datetime/timezone.ts",
8113
8184
  "section": "API reference",
8114
- "markdown": "# `@svgrid/grid` · `datetime/timezone.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\timezone.ts`.\n\n### `type ZoneParts`\n\nA wall-clock time broken into fields, as it reads in a specific time zone.\n\n```ts\nexport type ZoneParts = {\n year: number\n month: number // 1-12\n day: number\n hour: number // 0-23\n minute: number\n second: number\n}\n```\n\n### `function zoneParts`\n\nThe wall-clock parts of `instant` in `timeZone` (browser-local if undefined).\n\n```ts\nexport function zoneParts(instant: Date, timeZone?: string): ZoneParts {\n if (!timeZone) {\n return {\n year: instant.getFullYear(),\n month: instant.getMonth() + 1,\n day: instant.getDate(),\n hour: instant.getHours(),\n minute: instant.getMinutes(),\n second: instant.getSeconds(),\n }\n }\n const map: Record<string, number> = {}\n for (const p of partsFormat(timeZone).formatToParts(instant)) {\n if (p.type !== 'literal') map[p.type] = Number(p.value)\n }\n let hour = map.hour ?? 0\n if (hour === 24) hour = 0 // some engines emit '24' for midnight under h23\n return { year: map.year!, month: map.month!, day: map.day!, hour, minute: map.minute ?? 0, second: map.second ?? 0 }\n}\n```\n\n### `function zoneOffsetMs`\n\nMilliseconds `timeZone` is ahead of UTC at `instant` (DST-aware; negative west of UTC).\n\n```ts\nexport function zoneOffsetMs(instant: Date, timeZone?: string): number {\n if (!timeZone) return -instant.getTimezoneOffset() * 60_000\n const p = zoneParts(instant, timeZone)\n const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second)\n // `asUtc` reads the wall-clock as if it were UTC; its distance from the real\n // instant (truncated to whole seconds, matching the parts' resolution) is the offset.\n return asUtc - Math.floor(instant.getTime() / 1000) * 1000\n}\n```\n\n### `function toZonedLocal`\n\nAn instant -> a Date whose LOCAL fields equal its wall-clock in `timeZone`.\n\n```ts\nexport function toZonedLocal(instant: Date, timeZone?: string): Date {\n if (!timeZone) return instant\n const p = zoneParts(instant, timeZone)\n return new Date(p.year, p.month - 1, p.day, p.hour, p.minute, p.second, instant.getMilliseconds())\n}\n```\n\n### `function instantFromWallClock`\n\nThe instant whose wall-clock in `timeZone` is the given Y-M-D H:M:S.\n\n```ts\nexport function instantFromWallClock(\n year: number,\n month: number, // 1-12\n day: number,\n hour: number,\n minute: number,\n second = 0,\n timeZone?: string,\n ms = 0,\n): Date {\n if (!timeZone) return new Date(year, month - 1, day, hour, minute, second, ms)\n const wallUtc = Date.UTC(year, month - 1, day, hour, minute, second, ms)\n // Assume the wall-clock is UTC, subtract the offset there, then correct once\n // in case the candidate instant lands on the other side of a DST transition.\n const off1 = zoneOffsetMs(new Date(wallUtc), timeZone)\n let inst = new Date(wallUtc - off1)\n const off2 = zoneOffsetMs(inst, timeZone)\n if (off2 !== off1) inst = new Date(wallUtc - off2)\n return inst\n}\n```\n\n### `function fromZonedLocal`\n\nInverse of {@link toZonedLocal}: a pseudo-local Date -> the real instant.\n\n```ts\nexport function fromZonedLocal(pseudo: Date, timeZone?: string): Date {\n if (!timeZone) return pseudo\n return instantFromWallClock(\n pseudo.getFullYear(),\n pseudo.getMonth() + 1,\n pseudo.getDate(),\n pseudo.getHours(),\n pseudo.getMinutes(),\n pseudo.getSeconds(),\n timeZone,\n pseudo.getMilliseconds(),\n )\n}\n```\n\n### `function zoneAbbr`\n\nShort zone name at `instant`, e.g. \"EDT\" / \"GMT+5:30\" - for a ruler header.\n\n```ts\nexport function zoneAbbr(instant: Date, timeZone?: string): string {\n if (!timeZone) return ''\n const parts = new Intl.DateTimeFormat('en-US', { timeZone, hour: '2-digit', timeZoneName: 'short' }).formatToParts(instant)\n return parts.find((p) => p.type === 'timeZoneName')?.value ?? ''\n}\n```\n\n### `function normalizeTimeZone`\n\nValidate an IANA zone id; returns it if usable, else undefined (falls back to local).\n\n```ts\nexport function normalizeTimeZone(timeZone?: string): string | undefined {\n if (!timeZone) return undefined\n try {\n new Intl.DateTimeFormat('en-US', { timeZone })\n return timeZone\n } catch {\n return undefined\n }\n}\n```\n"
8185
+ "markdown": "# `@svgrid/grid` · `datetime/timezone.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\datetime\\timezone.ts`.\n\n### `type ZoneParts`\n\nA wall-clock time broken into fields, as it reads in a specific time zone.\n\n```ts\nexport type ZoneParts = {\n year: number\n month: number // 1-12\n day: number\n hour: number // 0-23\n minute: number\n second: number\n}\n```\n\n### `function zoneParts`\n\nThe wall-clock parts of `instant` in `timeZone` (browser-local if undefined).\n\n```ts\nexport function zoneParts(instant: Date, timeZone?: string): ZoneParts\n```\n\n### `function zoneOffsetMs`\n\nMilliseconds `timeZone` is ahead of UTC at `instant` (DST-aware; negative west of UTC).\n\n```ts\nexport function zoneOffsetMs(instant: Date, timeZone?: string): number\n```\n\n### `function toZonedLocal`\n\nAn instant -> a Date whose LOCAL fields equal its wall-clock in `timeZone`.\n\n```ts\nexport function toZonedLocal(instant: Date, timeZone?: string): Date\n```\n\n### `function instantFromWallClock`\n\nThe instant whose wall-clock in `timeZone` is the given Y-M-D H:M:S.\n\n```ts\nexport function instantFromWallClock(\n year: number,\n month: number, // 1-12\n day: number,\n hour: number,\n minute: number,\n second = 0,\n timeZone?: string,\n ms = 0,\n): Date\n```\n\n### `function fromZonedLocal`\n\nInverse of {@link toZonedLocal}: a pseudo-local Date -> the real instant.\n\n```ts\nexport function fromZonedLocal(pseudo: Date, timeZone?: string): Date\n```\n\n### `function zoneAbbr`\n\nShort zone name at `instant`, e.g. \"EDT\" / \"GMT+5:30\" - for a ruler header.\n\n```ts\nexport function zoneAbbr(instant: Date, timeZone?: string): string\n```\n\n### `function normalizeTimeZone`\n\nValidate an IANA zone id; returns it if usable, else undefined (falls back to local).\n\n```ts\nexport function normalizeTimeZone(timeZone?: string): string | undefined\n```\n"
8115
8186
  },
8116
8187
  {
8117
8188
  "slug": "reference/auto/svgrid-grid-toast-store.svelte",
8118
8189
  "path": "docs/reference/auto/svgrid-grid-toast-store.svelte.md",
8119
8190
  "title": "@svgrid/grid · toast-store.svelte.ts",
8120
8191
  "section": "API reference",
8121
- "markdown": "# `@svgrid/grid` · `toast-store.svelte.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\toast-store.svelte.ts`.\n\n### `type ToastVariant`\n\nA toast's severity, which selects its colour and icon.\n\n```ts\nexport type ToastVariant = 'info' | 'success' | 'warning' | 'error'\n```\n\n### `type ToastAction`\n\nA button rendered inside a toast (a primary `action` or a secondary `cancel`).\n\n```ts\nexport type ToastAction = {\n label: string\n /** Invoked with the toast id when pressed. */\n onClick?: (id: number) => void\n /** Keep the toast open after the click (default: dismiss it). */\n keepOpen?: boolean\n}\n```\n\n### `type ToastOptions`\n\nOptions for one toast: its variant, how long it stays, and any action button.\n\n```ts\nexport type ToastOptions = {\n variant?: ToastVariant\n /** Auto-dismiss after N ms. `0` = sticky (dismiss manually). Default 4000. */\n duration?: number\n /** Show the dismiss (x) button. Default true. */\n dismissible?: boolean\n /** Optional bold title above the message. */\n title?: string\n /** Primary action button. */\n action?: ToastAction\n /** Secondary (cancel) action button. */\n cancel?: ToastAction\n /** Render a fully custom toast body instead of the icon + title + message. */\n render?: Snippet<[Toast]>\n}\n```\n\n### `type Toast`\n\nA live toast: its options plus the id needed to dismiss it.\n\n```ts\nexport type Toast = {\n id: number\n message: string\n variant: ToastVariant\n duration: number\n dismissible: boolean\n title?: string\n action?: ToastAction\n cancel?: ToastAction\n render?: Snippet<[Toast]>\n}\n```\n\n### `type UpdateToast`\n\nPatch applied by `toast.update(id, patch)`; every field is optional.\n\n```ts\nexport type UpdateToast = Partial<Omit<Toast, 'id'>>\n```\n\n### `type PromiseMessages`\n\nMessages for `toast.promise`; success/error may derive from the value/error.\n\n```ts\nexport type PromiseMessages<T> = {\n loading: string\n success: string | ((value: T) => string)\n error: string | ((error: unknown) => string)\n}\n```\n\n### `type ToastFn`\n\nThe callable toast API - `toast(msg)` plus `.success` / `.error` / friends.\n\n```ts\nexport type ToastFn = {\n (message: string, options?: ToastOptions): number\n info: (message: string, options?: VariantOptions) => number\n success: (message: string, options?: VariantOptions) => number\n warning: (message: string, options?: VariantOptions) => number\n error: (message: string, options?: VariantOptions) => number\n /**\n * Show a sticky loading toast, then update it IN PLACE to success/error when\n * the promise settles. Returns the original promise so callers can await it.\n */\n promise: <T>(promise: Promise<T>, messages: PromiseMessages<T>, options?: ToastOptions) => Promise<T>\n /** Patch an existing toast (message/variant/title/action/duration/render). */\n update: (id: number, patch: UpdateToast) => void\n /** Push a toast with a fully custom body snippet. Returns its id. */\n custom: (render: Snippet<[Toast]>, options?: ToastOptions) => number\n /** Dismiss a toast by id. */\n dismiss: (id: number) => void\n}\n```\n\n### `const toastStore`\n\nLive reactive list of active toasts (read inside a component/effect).\n\n```ts\nexport const toastStore = { get toasts() { return store.toasts } }\n```\n\n### `const toast`\n\nShow a toast. Returns its id. Has `.info/.success/.warning/.error` helpers.\n\n```ts\nexport const toast: ToastFn = store.toast\n```\n\n### `const dismissToast`\n\nDismiss a toast by id.\n\n```ts\nexport const dismissToast = (id: number): void => store.dismiss(id)\n```\n\n### `const updateToast`\n\nPatch an existing toast in place (message/variant/title/action/duration/render).\n\n```ts\nexport const updateToast = (id: number, patch: UpdateToast): void => store.update(id, patch)\n```\n\n### `const clearToasts`\n\nRemove every toast (and cancel their timers).\n\n```ts\nexport const clearToasts = (): void => store.clear()\n```\n\n### `const pauseToast`\n\nPause a toast's auto-dismiss countdown (e.g. while hovered).\n\n```ts\nexport const pauseToast = (id: number): void => store.pause(id)\n```\n\n### `const resumeToast`\n\nResume a paused toast's countdown with the time it had left.\n\n```ts\nexport const resumeToast = (id: number): void => store.resume(id)\n```\n"
8192
+ "markdown": "# `@svgrid/grid` · `toast-store.svelte.ts`\n\nAuto-generated. Source: `packages\\grid\\src\\toast-store.svelte.ts`.\n\n### `type ToastVariant`\n\nA toast's severity, which selects its colour and icon.\n\n```ts\nexport type ToastVariant = 'info' | 'success' | 'warning' | 'error'\n```\n\n### `type ToastAction`\n\nA button rendered inside a toast (a primary `action` or a secondary `cancel`).\n\n```ts\nexport type ToastAction = {\n label: string\n /** Invoked with the toast id when pressed. */\n onClick?: (id: number) => void\n /** Keep the toast open after the click (default: dismiss it). */\n keepOpen?: boolean\n}\n```\n\n### `type ToastOptions`\n\nOptions for one toast: its variant, how long it stays, and any action button.\n\n```ts\nexport type ToastOptions = {\n variant?: ToastVariant\n /** Auto-dismiss after N ms. `0` = sticky (dismiss manually). Default 4000. */\n duration?: number\n /** Show the dismiss (x) button. Default true. */\n dismissible?: boolean\n /** Optional bold title above the message. */\n title?: string\n /** Primary action button. */\n action?: ToastAction\n /** Secondary (cancel) action button. */\n cancel?: ToastAction\n /** Render a fully custom toast body instead of the icon + title + message. */\n render?: Snippet<[Toast]>\n}\n```\n\n### `type Toast`\n\nA live toast: its options plus the id needed to dismiss it.\n\n```ts\nexport type Toast = {\n id: number\n message: string\n variant: ToastVariant\n duration: number\n dismissible: boolean\n title?: string\n action?: ToastAction\n cancel?: ToastAction\n render?: Snippet<[Toast]>\n}\n```\n\n### `type UpdateToast`\n\nPatch applied by `toast.update(id, patch)`; every field is optional.\n\n```ts\nexport type UpdateToast = Partial<Omit<Toast, 'id'>>\n```\n\n### `type PromiseMessages`\n\nMessages for `toast.promise`; success/error may derive from the value/error.\n\n```ts\nexport type PromiseMessages<T> = {\n loading: string\n success: string | ((value: T) => string)\n error: string | ((error: unknown) => string)\n}\n```\n\n### `type ToastFn`\n\nThe callable toast API - `toast(msg)` plus `.success` / `.error` / friends.\n\n```ts\nexport type ToastFn = {\n (message: string, options?: ToastOptions): number\n info: (message: string, options?: VariantOptions) => number\n success: (message: string, options?: VariantOptions) => number\n warning: (message: string, options?: VariantOptions) => number\n error: (message: string, options?: VariantOptions) => number\n /**\n * Show a sticky loading toast, then update it IN PLACE to success/error when\n * the promise settles. Returns the original promise so callers can await it.\n */\n promise: <T>(promise: Promise<T>, messages: PromiseMessages<T>, options?: ToastOptions) => Promise<T>\n /** Patch an existing toast (message/variant/title/action/duration/render). */\n update: (id: number, patch: UpdateToast) => void\n /** Push a toast with a fully custom body snippet. Returns its id. */\n custom: (render: Snippet<[Toast]>, options?: ToastOptions) => number\n /** Dismiss a toast by id. */\n dismiss: (id: number) => void\n}\n```\n\n### `const toastStore`\n\nLive reactive list of active toasts (read inside a component/effect).\n\n```ts\nexport const toastStore = { get toasts() { return store.toasts } }\n```\n\n### `const toast`\n\nShow a toast. Returns its id. Has `.info/.success/.warning/.error` helpers.\n\n```ts\nexport const toast: ToastFn = store.toast\n```\n\n### `const dismissToast`\n\nDismiss a toast by id.\n\n```ts\nexport const dismissToast = (id: number): void => ...\n```\n\n### `const updateToast`\n\nPatch an existing toast in place (message/variant/title/action/duration/render).\n\n```ts\nexport const updateToast = (id: number, patch: UpdateToast): void => ...\n```\n\n### `const clearToasts`\n\nRemove every toast (and cancel their timers).\n\n```ts\nexport const clearToasts = (): void => ...\n```\n\n### `const pauseToast`\n\nPause a toast's auto-dismiss countdown (e.g. while hovered).\n\n```ts\nexport const pauseToast = (id: number): void => ...\n```\n\n### `const resumeToast`\n\nResume a paused toast's countdown with the time it had left.\n\n```ts\nexport const resumeToast = (id: number): void => ...\n```\n"
8122
8193
  },
8123
8194
  {
8124
8195
  "slug": "reference/enterprise",
@@ -8378,7 +8449,7 @@ export const apiReference = {
8378
8449
  };
8379
8450
  export const apiSurface = {
8380
8451
  "gridVersion": "3.0.22",
8381
- "enterpriseVersion": "3.1.23",
8452
+ "enterpriseVersion": "3.1.25",
8382
8453
  "grid": {
8383
8454
  "values": [
8384
8455
  "ALL_FILTER_OPERATORS",