@svgrid/mcp 3.0.28 → 3.0.30
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 +40 -7
- package/dist/preview.d.ts +1 -1
- package/dist/preview.js +1 -1
- package/dist/validate.d.ts +10 -0
- package/dist/validate.js +115 -3
- package/package.json +3 -3
- package/server.json +2 -2
package/dist/data.js
CHANGED
|
@@ -4055,6 +4055,30 @@ export const examples = [
|
|
|
4055
4055
|
"blurb": "701. Review queue: overdue, labels and a row count Four @svgrid/enterprise additions to the grid's filtering and sorting, each switched on once and then used through ordinary column options:",
|
|
4056
4056
|
"source": "<script lang=\"ts\">\n /**\n * 701. Review queue: overdue, labels and a row count\n * ---------------------------------------------------\n * Four @svgrid/enterprise additions to the grid's filtering and sorting,\n * each switched on once and then used through ordinary column options:\n *\n * enableRelativeDateFilters() Due's filter menu gains Today, Before\n * today, After today, Next 7 days and Last\n * 7 days. No value to type: pick one and it\n * filters. A server data source receives\n * the dates they mean, not the operator.\n * enableFilterLabels() Status is stored as APPROVED /\n * MARKED_AS_FAILED; its filter checklist\n * lists \"Approved\" and \"Failed\", as the\n * cells show them.\n * enableRowCount() statusBar={{ rows: true }} shows \"24\n * rows\", or \"6 of 24 rows\" under a filter.\n * sortComparator: blanksLast() Reviews with no due date stay at the\n * bottom whichever way Due sorts.\n *\n * The accessor of every column stays the raw value, so Reviews sorts\n * 0, 1, 2, 10 and Due sorts by date, while the cells and the checklist read\n * as words.\n */\n import { SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n import {\n blanksLast,\n enableFilterLabels,\n enableRelativeDateFilters,\n enableRowCount,\n } from '@svgrid/enterprise'\n\n enableRelativeDateFilters()\n enableFilterLabels()\n enableRowCount()\n\n type Status = 'APPROVED' | 'MARKED_AS_FAILED' | 'UNDECIDED'\n type Review = {\n id: number\n name: string\n version: string\n status: Status\n reviews: number\n reviewer: string\n due: string | null\n }\n\n const STATUS_TEXT: Record<Status, string> = {\n APPROVED: 'Approved',\n MARKED_AS_FAILED: 'Failed',\n UNDECIDED: 'Undecided',\n }\n const STATUSES: Status[] = ['UNDECIDED', 'APPROVED', 'UNDECIDED', 'MARKED_AS_FAILED']\n const NAMES = [\n 'kernel-image', 'web-gateway', 'postgres-operator', 'metrics-agent', 'auth-service',\n 'snap-store-proxy', 'log-shipper', 'dns-resolver', 'object-store', 'build-runner',\n 'queue-broker', 'edge-cache',\n ]\n const REVIEWERS = ['A. Osei', 'R. Vance', 'M. Iqbal', 'J. Lindqvist', '']\n\n // Due dates are relative to today so Overdue and Next 7 days always have\n // something to show. Every fifth review has no due date.\n const OFFSETS = [-9, -2, 0, 3, 6, 12, -1, 5, 21, 1, -15, 8]\n const isoFromToday = (days: number) => {\n const d = new Date()\n d.setDate(d.getDate() + days)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n\n const reviews: Review[] = Array.from({ length: 24 }, (_, i) => ({\n id: i + 1,\n name: NAMES[i % NAMES.length],\n version: `${1 + (i % 3)}.${(i * 7) % 12}.${i % 5}`,\n status: STATUSES[(i * 5) % STATUSES.length],\n // 0 through 12, so a text sort would put 10 before 2.\n reviews: (i * 7) % 13,\n reviewer: REVIEWERS[i % REVIEWERS.length],\n due: i % 5 === 4 ? null : isoFromToday(OFFSETS[i % OFFSETS.length]),\n }))\n\n const columns: GridColumns<Review> = [\n { field: 'name', header: 'Artifact', width: 190 },\n { field: 'version', header: 'Version', width: 100 },\n {\n field: 'status',\n header: 'Status',\n width: 130,\n cell: ({ getValue }) => STATUS_TEXT[getValue() as Status] ?? '',\n },\n { field: 'reviews', header: 'Reviews', width: 100, cellDataType: 'number' },\n { field: 'reviewer', header: 'Reviewer', width: 140 },\n {\n field: 'due',\n header: 'Due',\n width: 150,\n cellDataType: 'dateString',\n format: { type: 'date', options: { dateStyle: 'medium' } },\n sortComparator: blanksLast('date'),\n },\n ]\n\n let api = $state<SvGridApi<{}, Review> | null>(null)\n let preset = $state<'all' | 'beforeToday' | 'today' | 'next7Days'>('all')\n\n const PRESETS = [\n { id: 'all', label: 'All' },\n { id: 'beforeToday', label: 'Overdue' },\n { id: 'today', label: 'Due today' },\n { id: 'next7Days', label: 'Next 7 days' },\n ] as const\n\n // The same operators the Due column's filter menu offers.\n function pick(id: (typeof PRESETS)[number]['id']) {\n preset = id\n api?.setFilter('due', id === 'all' ? null : { operator: id })\n }\n</script>\n\n<section class=\"wrap\">\n <header class=\"chrome\">\n <p class=\"hint\">\n Open the filter on <strong>Due</strong> for the days-from-today operators, or on\n <strong>Status</strong> for a checklist that reads as the cells do. Sort Due either way:\n reviews with no date stay last.\n </p>\n <div class=\"seg\" role=\"group\" aria-label=\"Due date\">\n {#each PRESETS as p (p.id)}\n <button class:on={preset === p.id} aria-pressed={preset === p.id} onclick={() => pick(p.id)}>\n {p.label}\n </button>\n {/each}\n </div>\n </header>\n\n <div class=\"grid-host\">\n <SvGrid\n responsive={true}\n data={reviews}\n {columns}\n getRowId={(r) => String(r.id)}\n sortable\n filterable\n filterMode=\"menu\"\n initialSorting={[{ id: 'due', desc: false }]}\n statusBar={{ rows: true, aggregates: [] }}\n rowHeight={36}\n containerHeight=\"100%\"\n fitColumns\n onApiReady={(next) => (api = next)}\n onFiltersChange={(f) => {\n // Due set from its menu to something the buttons do not name: no button is on.\n const op = f.columns.find((c) => c.id === 'due')?.operator\n if (!PRESETS.some((p) => p.id === op)) preset = 'all'\n }}\n />\n </div>\n</section>\n\n<style>\n .wrap {\n display: flex;\n flex-direction: column;\n flex: 1;\n min-height: 0;\n gap: 12px;\n }\n\n .chrome {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n flex-wrap: wrap;\n flex: none;\n }\n .hint {\n margin: 0;\n font-size: 13px;\n line-height: 1.5;\n color: var(--sg-muted, #64748b);\n max-width: 62ch;\n }\n .hint strong { color: var(--sg-fg, #0f172a); font-weight: 600; }\n\n .seg {\n display: inline-flex;\n border: 1px solid var(--sg-border, #cbd5e1);\n border-radius: 8px;\n overflow: hidden;\n }\n .seg button {\n border: 0;\n padding: 6px 12px;\n font: inherit;\n font-size: 13px;\n background: var(--sg-bg, #fff);\n color: var(--sg-muted, #64748b);\n cursor: pointer;\n }\n .seg button + button { border-left: 1px solid var(--sg-border, #cbd5e1); }\n .seg button.on { background: var(--sg-accent, #6366f1); color: var(--sg-on-accent, #fff); }\n .seg button:focus-visible { outline: 2px solid var(--sg-focus-ring, #6366f1); outline-offset: -2px; }\n\n .grid-host {\n flex: 1;\n min-height: 0;\n display: flex;\n flex-direction: column;\n }\n</style>\n"
|
|
4057
4057
|
},
|
|
4058
|
+
{
|
|
4059
|
+
"id": "702-change-review",
|
|
4060
|
+
"path": "examples/src/demos/702-change-review.svelte",
|
|
4061
|
+
"title": "Change Review",
|
|
4062
|
+
"category": "Misc",
|
|
4063
|
+
"blurb": "702. Change review: an agent's edits, accepted by group A customer table with the dirt a CRM export carries. Run the cleanup agent and its edits arrive as proposals, not writes: each changed cell",
|
|
4064
|
+
"source": "<script lang=\"ts\">\n /**\n * 702. Change review: an agent's edits, accepted by group\n * --------------------------------------------------------\n * A customer table with the dirt a CRM export carries. Run the cleanup\n * agent and its edits arrive as proposals, not writes: each changed cell\n * shows the proposed value with the old one struck through beside it, and\n * the panel groups them by what they do.\n *\n * Trim spaces, Change to Title Case, Reformat Phone,\n * Divide Revenue by 100 rule groups: every member follows the rule\n * Country: 5 values -> ... a mapping table, one decision\n * Fill empty Region split by value; the low-confidence fills\n * (two of them wrong) lead the sample\n *\n * Accept a group and one setRows call writes it; Ctrl+Z in the grid puts it\n * back. Edit a cell that has a proposal, then accept: the proposal is\n * marked stale and your value stays. Import the CRM update and one cell gets\n * a second, different proposal: a conflict, decided in the panel.\n *\n * The agent here is a few fixed rules standing in for a model, so the demo\n * runs without a key. With one, reviewSmartFill / reviewClassify feed the\n * same review from the AI helpers.\n */\n import { SvButton, SvGrid, type GridColumns, type SvGridApi } from '@svgrid/grid'\n import { createReview, fromRows, SvReviewPanel, type ProposalInput } from '@svgrid/enterprise/review'\n\n type Customer = {\n id: string\n company: string\n contact: string\n phone: string\n country: string\n region: string\n revenue: number\n }\n\n const COMPANIES = ['Acme Corp', 'Globex', 'Initech', 'Umbrella Labs', 'Hooli', 'Vandelay Imports', 'Stark Industries',\n 'Wayne Holdings', 'Tyrell Systems', 'Cyberdyne', 'Aperture Science', 'Soylent Foods', 'Oscorp', 'Wonka Partners',\n 'Gringotts', 'Monarch Group', 'Pied Piper', 'Dunder Paper', 'Prestige Worldwide', 'Massive Dynamic']\n const PEOPLE = ['maria silva', 'wei chen', 'aisha khan', 'carlos ruiz', 'emma berg', 'liam novak', 'sofia rossi',\n 'noah okafor', 'yuki tanaka', 'omar haddad']\n const COUNTRIES = ['United States', 'usa', 'Germany', 'U.S.', 'Japan', 'US', 'United Kingdom', 'United States of America', 'Brazil', 'U.S.A.']\n const REGION_OF: Record<string, string> = { 'United States': 'AMER', Brazil: 'AMER', Germany: 'EMEA', 'United Kingdom': 'EMEA', Japan: 'APAC' }\n const US = new Set(['usa', 'U.S.', 'US', 'United States of America', 'U.S.A.'])\n\n const seed = (): Customer[] =>\n COMPANIES.map((name, i) => {\n const country = COUNTRIES[i % COUNTRIES.length]\n const a = 200 + ((i * 37) % 700)\n const b = 100 + ((i * 53) % 800)\n const c = 1000 + ((i * 271) % 9000)\n return {\n id: `c${i + 1}`,\n company: i % 3 === 0 ? `${name} ` : i % 7 === 1 ? ` ${name}` : name,\n contact: i % 2 === 0 ? PEOPLE[i % PEOPLE.length].toUpperCase() : titleCase(PEOPLE[i % PEOPLE.length]),\n phone: i % 4 === 3 ? `${a}-${b}-${c}` : `(${a}) ${b}-${c}`,\n country,\n region: i % 3 === 1 ? '' : REGION_OF[US.has(country) ? 'United States' : country] ?? '',\n // Six rows came in from the old billing system, in cents.\n revenue: i % 3 === 2 ? (40 + i * 13) * 1000 * 100 : (40 + i * 13) * 1000,\n }\n })\n\n function titleCase(s: string) {\n return s.replace(/\\b\\p{Ll}/gu, (ch) => ch.toUpperCase())\n }\n\n let rows = $state(seed())\n let api = $state<SvGridApi<any, Customer> | null>(null)\n const review = createReview<Customer>({ api: () => api, setRows: (next) => (rows = next) })\n\n const columns: GridColumns<Customer> = [\n { field: 'company', header: 'Company', width: 190, editable: true },\n { field: 'contact', header: 'Contact', width: 150, editable: true },\n { field: 'phone', header: 'Phone', width: 140, editable: true },\n { field: 'country', header: 'Country', width: 170, editable: true },\n { field: 'region', header: 'Region', width: 100, editable: true },\n { field: 'revenue', header: 'Revenue', width: 130, editable: true, editorType: 'number', format: { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } } },\n ]\n\n /** A few fixed rules standing in for a cleanup model. */\n function runAgent() {\n const proposals: ProposalInput[] = []\n for (const r of rows) {\n const add = (field: keyof Customer, after: unknown, extra: Partial<ProposalInput> = {}) => {\n if (r[field] !== after) proposals.push({ rowId: r.id, field, before: r[field], after, ...extra })\n }\n add('company', r.company.trim())\n add('contact', titleCase(r.contact.toLowerCase()))\n const digits = r.phone.replace(/\\D/g, '')\n add('phone', `${digits.slice(0, 3)}-${digits.slice(3, 6)}-${digits.slice(6)}`)\n const country = US.has(r.country) ? 'United States' : r.country\n add('country', country)\n if (!r.region) {\n // Two guesses are wrong, and the agent says it is unsure of them.\n // c5 is in Japan and c11 in the United States.\n const guess = r.id === 'c5' ? 'EMEA' : r.id === 'c11' ? 'APAC' : null\n const unsure = guess !== null\n add('region', guess ?? REGION_OF[country], {\n confidence: unsure ? 0.42 : 0.93,\n reason: unsure ? 'guessed from the company name' : `from Country (${country})`,\n })\n }\n if (r.revenue >= 1_000_000) add('revenue', r.revenue / 100, { reason: 'billing export was in cents' })\n }\n review.add({ source: { kind: 'agent', id: 'cleanup', label: 'Cleanup agent' }, proposals })\n }\n\n /** The CRM sends its own region for one customer, different from the agent's. */\n function runImport() {\n if (!api) return\n const set = fromRows<Customer>([{ id: 'c2', region: 'EMEA' }, { id: 'c8', region: 'EMEA' }], {\n api,\n key: 'id',\n source: { kind: 'import', id: 'crm-update.csv', label: 'crm-update.csv' },\n })\n review.add(set)\n }\n\n function reset() {\n review.clear()\n rows = seed()\n }\n\n const pending = $derived(review.pending().length)\n\n // A phone has no room for both side by side, and the demo stage has a fixed\n // height: show one at a time. The grid stays mounted, so its api does too.\n let narrow = $state(false)\n let view = $state<'grid' | 'review'>('grid')\n $effect(() => {\n const mq = window.matchMedia('(max-width: 860px)')\n const sync = () => (narrow = mq.matches)\n sync()\n mq.addEventListener('change', sync)\n return () => mq.removeEventListener('change', sync)\n })\n</script>\n\n<div class=\"cr-demo\">\n <div class=\"cr-bar\">\n <SvButton size=\"sm\" onclick={runAgent}>Run cleanup agent</SvButton>\n <SvButton size=\"sm\" variant=\"outline\" onclick={runImport}>Import crm-update.csv</SvButton>\n <SvButton size=\"sm\" variant=\"ghost\" onclick={reset}>Reset</SvButton>\n <span class=\"cr-note\">{pending ? `${pending} proposed, nothing written yet` : 'The data is as loaded'}</span>\n </div>\n {#if narrow}\n <div class=\"cr-bar\" role=\"group\" aria-label=\"Show\">\n <SvButton size=\"sm\" variant={view === 'grid' ? 'secondary' : 'ghost'} onclick={() => (view = 'grid')}>Grid</SvButton>\n <SvButton size=\"sm\" variant={view === 'review' ? 'secondary' : 'ghost'} onclick={() => (view = 'review')}>Review ({pending})</SvButton>\n </div>\n {/if}\n <div class=\"cr-split\">\n <div class=\"cr-grid\" class:cr-hidden={narrow && view === 'review'}>\n <SvGrid\n data={rows}\n columns={review.columns(columns)}\n getRowId={(r) => r.id}\n conditionalFormats={review.formats}\n editable\n containerHeight={460}\n onApiReady={(a) => (api = a)}\n />\n </div>\n <div class=\"cr-panel\" class:cr-hidden={narrow && view === 'grid'}>\n <SvReviewPanel {review} title=\"Review the agent's changes\" />\n </div>\n </div>\n</div>\n\n<style>\n .cr-demo {\n display: flex;\n flex-direction: column;\n gap: 10px;\n font-family: var(--sg-font, inherit);\n color: var(--sg-fg);\n }\n .cr-bar {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 8px;\n }\n .cr-note {\n color: var(--sg-muted);\n font-size: 13px;\n }\n .cr-split {\n display: grid;\n grid-template-columns: minmax(0, 1fr) 340px;\n gap: 12px;\n align-items: start;\n }\n .cr-grid,\n .cr-panel {\n min-width: 0;\n }\n /* The stage has a fixed height: the panel scrolls within the grid's. */\n .cr-panel {\n max-height: 460px;\n overflow: auto;\n }\n .cr-hidden {\n display: none;\n }\n @media (max-width: 860px) {\n .cr-split {\n grid-template-columns: minmax(0, 1fr);\n }\n }\n</style>\n"
|
|
4065
|
+
},
|
|
4066
|
+
{
|
|
4067
|
+
"id": "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
|
+
},
|
|
4074
|
+
{
|
|
4075
|
+
"id": "704-agent-review-desk",
|
|
4076
|
+
"path": "examples/src/demos/704-agent-review-desk.svelte",
|
|
4077
|
+
"title": "Agent Review Desk",
|
|
4078
|
+
"category": "App Templates",
|
|
4079
|
+
"blurb": "704. Agent review desk (app template) A CRM agent cleans a customer table, and nothing it does lands until a person says so. The agent works through the same tools a real model would",
|
|
4080
|
+
"source": "<script lang=\"ts\">\n /**\n * 704. Agent review desk (app template)\n * -------------------------------------\n * A CRM agent cleans a customer table, and nothing it does lands until a\n * person says so. The agent works through the same tools a real model would\n * get from createGridTools:\n *\n * grid_describe what the table holds and what it may edit\n * grid_query_rows the rows, with their row ids\n * grid_propose_edits edits, each with a reason and a confidence\n *\n * Every step it takes shows in the strip under the header with the tool\n * call it made. Its edits arrive as proposals: the cell shows the proposed\n * value with the old one struck through, and the review panel groups them\n * by what they do, the risky groups first. Two of its region guesses are\n * wrong, and it says it is unsure of them.\n *\n * Accept or reject a group; one Ctrl+Z in the grid undoes it. Edit a cell\n * before accepting its proposal and your value stays. The Log tab lists\n * every decision (onDecision, where an app writes its audit trail). Revert\n * run proposes undoing what was accepted (revertSet); Copy for approver\n * puts the review on the clipboard as JSON for someone else to merge.\n *\n * The agent is a script standing in for a model, so the demo runs offline.\n *\n * Grid, buttons: @svgrid/grid. Change review, agent tools: @svgrid/enterprise.\n */\n import { onMount } from 'svelte'\n import { SvGrid, SvButton, renderSnippet, type GridColumns, type SvGridApi } from '@svgrid/grid'\n import {\n createReview,\n createGridTools,\n SvReviewPanel,\n type GridTool,\n type ReviewDecision,\n } from '@svgrid/enterprise/review'\n\n type Customer = {\n id: string\n company: string\n contact: string\n email: string\n phone: string\n country: string\n region: string\n segment: string\n arr: number\n }\n\n // ---- data -------------------------------------------------------------\n\n const NAMES = ['Acme Robotics', 'Bluefin Labs', 'Cobalt Freight', 'Driftwood Media', 'Ember Analytics', 'Fjord Outdoor',\n 'Granite Health', 'Harbor Logistics', 'Ion Energy', 'Juniper Foods', 'Kestrel Air', 'Lumen Optics', 'Mosaic Retail',\n 'Nimbus Cloud', 'Orchid Beauty', 'Pinecone Games', 'Quarry Steel', 'Radiant Solar', 'Saffron Spices', 'Tundra Gear',\n 'Umbra Security', 'Vertex Bio', 'Willow Insurance', 'Xenon Motors', 'Yarrow Pharma', 'Zephyr Travel', 'Atlas Mapping',\n 'Beacon Schools', 'Cypress Legal', 'Delta Dental', 'Echo Audio', 'Falcon Drones', 'Garnet Jewels', 'Helix Genomics',\n 'Indigo Textiles', 'Jade Ceramics']\n const PEOPLE = ['maria lopez', 'wei zhang', 'aisha bello', 'tom fischer', 'emma dubois', 'liam walsh', 'sofia ricci',\n 'noah park', 'yuki sato', 'omar nasser', 'lena berg', 'ravi iyer']\n const COUNTRIES = ['United States', 'usa', 'Germany', 'U.S.', 'Japan', 'US', 'United Kingdom', 'United States of America',\n 'Brazil', 'France', 'U.S.A.', 'India']\n const US = new Set(['usa', 'U.S.', 'US', 'United States of America', 'U.S.A.'])\n const REGION: Record<string, string> = { 'United States': 'AMER', Brazil: 'AMER', Germany: 'EMEA', 'United Kingdom': 'EMEA', France: 'EMEA', Japan: 'APAC', India: 'APAC' }\n const titleCase = (s: string) => s.replace(/\\b\\p{Ll}/gu, (c) => c.toUpperCase())\n\n function seed(): Customer[] {\n return NAMES.map((name, i) => {\n const person = PEOPLE[i % PEOPLE.length]!\n const country = COUNTRIES[i % COUNTRIES.length]!\n const domain = name.split(' ')[0]!.toLowerCase()\n const [a, b, c] = [200 + ((i * 37) % 700), 100 + ((i * 53) % 800), 1000 + ((i * 271) % 9000)]\n const arr = (18 + ((i * 47) % 160)) * 1000\n return {\n id: `cus-${1001 + i}`,\n company: i % 4 === 0 ? `${name} ` : i % 9 === 2 ? ` ${name}` : name,\n contact: i % 3 === 0 ? person.toUpperCase() : titleCase(person),\n email: i % 2 === 0 ? `${titleCase(person).replace(' ', '.')}@${titleCase(domain)}.COM` : `${person.replace(' ', '.')}@${domain}.com`,\n phone: i % 5 === 4 ? `${a}-${b}-${c}` : i % 3 === 1 ? `${a}.${b}.${c}` : `(${a}) ${b}-${c}`,\n country,\n region: i % 4 === 1 ? '' : REGION[US.has(country) ? 'United States' : country] ?? '',\n segment: '',\n // Seven accounts came over from the old billing system in cents.\n arr: i % 5 === 2 ? arr * 100 : arr,\n }\n })\n }\n\n let rows = $state(seed())\n let api = $state<SvGridApi<any, Customer> | null>(null)\n\n // ---- review -------------------------------------------------------------\n\n type LogEntry = { id: number; at: number; text: string; tone: 'accept' | 'reject' | 'undo' }\n let log = $state<LogEntry[]>([])\n let logSeq = 0\n const FIELD_LABEL: Record<string, string> = { company: 'Company', contact: 'Contact', email: 'Email', phone: 'Phone', country: 'Country', region: 'Region', segment: 'Segment', arr: 'ARR' }\n\n function describeDecision(d: ReviewDecision): LogEntry {\n const fields = [...new Set(d.proposals.map((p) => FIELD_LABEL[p.field] ?? p.field))].join(', ')\n const n = d.proposals.length\n const what = `${n} ${n === 1 ? 'change' : 'changes'} to ${fields}`\n const text =\n d.action === 'accept' ? `Accepted ${what}`\n : d.action === 'reject' ? `Rejected ${what}`\n : d.action === 'undo' ? `Undid the ${d.of} of ${what}`\n : `Redid the ${d.of} of ${what}`\n return { id: ++logSeq, at: d.at, text, tone: d.action === 'accept' || (d.action === 'redo' && d.of === 'accept') ? 'accept' : d.action === 'reject' ? 'reject' : 'undo' }\n }\n\n const review = createReview<Customer>({\n api: () => api,\n setRows: (next) => (rows = next),\n user: 'You',\n onDecision: (d) => (log = [describeDecision(d), ...log]),\n })\n\n const AGENT = { kind: 'agent' as const, id: 'crm-agent', label: 'CRM agent' }\n const tools = createGridTools({\n review,\n api: () => api,\n source: AGENT,\n fields: ['company', 'contact', 'email', 'phone', 'country', 'region', 'segment', 'arr'],\n })\n const tool = (name: string) => tools.find((t) => t.name === name) as GridTool\n\n // ---- the agent --------------------------------------------------------\n\n type Step = { id: number; title: string; call: string; result: string; state: 'running' | 'done' }\n let steps = $state<Step[]>([])\n const SHORT: Record<string, string> = {\n 'Read the customer table': 'Read the table',\n 'Trim stray spaces in company names': 'Trim spaces',\n 'Put contact names in title case': 'Title-case names',\n 'Lower-case email addresses': 'Lower-case emails',\n 'Use one phone format': 'One phone format',\n 'Map country spellings to one name': 'Map countries',\n 'Fill missing regions': 'Fill regions',\n 'Convert ARR booked in cents': 'ARR from cents',\n 'Tag each account with a segment': 'Tag segments',\n }\n // The newest step stays in view as the strip grows.\n let stepsEl = $state<HTMLOListElement | null>(null)\n $effect(() => {\n void steps.length\n queueMicrotask(() => stepsEl?.scrollTo({ left: stepsEl.scrollWidth, behavior: 'smooth' }))\n })\n let agentState = $state<'idle' | 'running' | 'done'>('idle')\n let runToken = 0\n\n const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n type Edit = { rowId: string; field: string; value: unknown; reason?: string; confidence?: number }\n\n async function step(title: string, call: string, work: () => Promise<string>, token: number) {\n if (token !== runToken) return false\n const s: Step = { id: steps.length + 1, title, call, result: '', state: 'running' }\n steps = [...steps, s]\n await sleep(650)\n if (token !== runToken) return false\n const result = await work()\n steps = steps.map((x) => (x.id === s.id ? { ...x, result, state: 'done' } : x))\n return true\n }\n\n async function propose(title: string, edits: Edit[]) {\n const out = (await tool('grid_propose_edits').execute({ title, edits })) as { proposed: number }\n return `${out.proposed} proposed`\n }\n\n async function runAgent() {\n const token = ++runToken\n steps = []\n agentState = 'running'\n let table: Customer[] = []\n const ok = await step('Read the customer table', 'grid_describe() · grid_query_rows()', async () => {\n const d = (await tool('grid_describe').execute({})) as { rowCount: number; columns: unknown[] }\n table = ((await tool('grid_query_rows').execute({})) as { rows: Array<Customer & { rowId: string }> }).rows.map((r) => ({ ...r, id: r.rowId }))\n return `${d.rowCount} rows, ${d.columns.length} columns`\n }, token)\n if (!ok) return\n const each = (fn: (r: Customer) => Edit | null) => table.map(fn).filter((e): e is Edit => e !== null)\n\n const plan: Array<[string, string, () => Edit[]]> = [\n ['Trim stray spaces in company names', 'company', () =>\n each((r) => (r.company !== r.company.trim() ? { rowId: r.id, field: 'company', value: r.company.trim() } : null))],\n ['Put contact names in title case', 'contact', () =>\n each((r) => (r.contact === r.contact.toUpperCase() ? { rowId: r.id, field: 'contact', value: titleCase(r.contact.toLowerCase()) } : null))],\n ['Lower-case email addresses', 'email', () =>\n each((r) => (r.email !== r.email.toLowerCase() ? { rowId: r.id, field: 'email', value: r.email.toLowerCase() } : null))],\n ['Use one phone format', 'phone', () =>\n each((r) => {\n const d = r.phone.replace(/\\D/g, '')\n const v = `${d.slice(0, 3)}-${d.slice(3, 6)}-${d.slice(6)}`\n return v !== r.phone ? { rowId: r.id, field: 'phone', value: v } : null\n })],\n ['Map country spellings to one name', 'country', () =>\n each((r) => (US.has(r.country) ? { rowId: r.id, field: 'country', value: 'United States', reason: `\"${r.country}\" is the United States` } : null))],\n ['Fill missing regions', 'region', () =>\n each((r) => {\n if (r.region) return null\n const country = US.has(r.country) ? 'United States' : r.country\n // Two guesses come from the company name, and the agent says so.\n if (r.id === 'cus-1006') return { rowId: r.id, field: 'region', value: 'APAC', confidence: 0.38, reason: 'guessed from the company name' }\n if (r.id === 'cus-1018') return { rowId: r.id, field: 'region', value: 'EMEA', confidence: 0.44, reason: 'guessed from the company name' }\n return { rowId: r.id, field: 'region', value: REGION[country], confidence: 0.94, reason: `from Country (${country})` }\n })],\n ['Convert ARR booked in cents', 'arr', () =>\n each((r) => (r.arr >= 1_000_000 ? { rowId: r.id, field: 'arr', value: r.arr / 100, reason: 'imported from billing in cents' } : null))],\n ['Tag each account with a segment', 'segment', () =>\n each((r) => {\n const arr = r.arr >= 1_000_000 ? r.arr / 100 : r.arr\n return { rowId: r.id, field: 'segment', value: arr >= 120_000 ? 'Enterprise' : arr >= 60_000 ? 'Mid-market' : 'SMB', confidence: 0.86, reason: 'from ARR bands' }\n })],\n ]\n for (const [title, field, build] of plan) {\n const edits = build()\n const done = await step(title, `grid_propose_edits(${edits.length} × ${field})`, () => propose(title, edits), token)\n if (!done) return\n }\n if (token === runToken) agentState = 'done'\n }\n\n function runAgain() {\n review.clear()\n rows = seed()\n log = []\n void runAgent()\n }\n\n // ---- after review -------------------------------------------------------\n\n let note = $state('')\n function revertRun() {\n let n = 0\n for (const s of review.sets()) {\n if (s.source.id !== AGENT.id) continue\n const set = review.revertSet(s.id)\n if (set) n += set.proposals.length\n }\n note = n ? `${n} reverts proposed: review them like any other change` : 'Nothing accepted to revert'\n }\n async function copyForApprover() {\n const json = JSON.stringify(review.toJSON())\n try {\n await navigator.clipboard.writeText(json)\n note = `Copied ${review.sets().length} sets (${Math.round(json.length / 1024)} KB of JSON) for an approver to merge`\n } catch {\n note = 'The browser blocked the clipboard'\n }\n }\n\n // ---- derived chrome -----------------------------------------------------\n\n const tally = $derived.by(() => {\n const t = { proposed: 0, pending: 0, accepted: 0, rejected: 0 }\n for (const p of review.proposals()) {\n t.proposed++\n if (p.status === 'pending' || p.status === 'conflict') t.pending++\n else if (p.status === 'accepted') t.accepted++\n else if (p.status === 'rejected' || p.status === 'stale') t.rejected++\n }\n return t\n })\n const status = $derived(\n agentState === 'running' ? { text: 'Agent working', tone: 'info' }\n : tally.pending ? { text: 'Waiting for review', tone: 'warning' }\n : tally.proposed ? { text: 'All reviewed', tone: 'success' }\n : { text: 'Idle', tone: 'muted' },\n )\n\n let side = $state<'review' | 'log'>('review')\n let narrow = $state(false)\n let view = $state<'grid' | 'side'>('grid')\n\n onMount(() => {\n const mq = window.matchMedia('(max-width: 860px)')\n const sync = () => (narrow = mq.matches)\n sync()\n mq.addEventListener('change', sync)\n const t = setTimeout(() => void runAgent(), 500)\n return () => {\n mq.removeEventListener('change', sync)\n clearTimeout(t)\n runToken++\n }\n })\n\n const time = (at: number) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })\n\n const SEGMENT_TONE: Record<string, string> = { Enterprise: '#7c3aed', 'Mid-market': '#0e7490', SMB: '#64748b' }\n const columns: GridColumns<Customer> = [\n { field: 'company', header: 'Company', width: 180, editable: true },\n { field: 'contact', header: 'Contact', width: 140, editable: true },\n { field: 'email', header: 'Email', width: 220, editable: true },\n { field: 'phone', header: 'Phone', width: 130, editable: true },\n { field: 'country', header: 'Country', width: 150, editable: true },\n { field: 'region', header: 'Region', width: 90, editable: true },\n { field: 'segment', header: 'Segment', width: 120, editable: true, cell: (ctx) => renderSnippet(segmentCell, { value: ctx.getValue() as string }) },\n { field: 'arr', header: 'ARR', width: 120, editable: true, editorType: 'number', format: { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } } },\n ]\n</script>\n\n{#snippet segmentCell({ value }: { value: string })}\n {#if value}<span class=\"ard-seg\" style:--seg={SEGMENT_TONE[value] ?? '#64748b'}>{value}</span>{/if}\n{/snippet}\n\n<div class=\"ard\">\n <header class=\"ard-head\">\n <div class=\"ard-title\">\n <span class=\"ard-logo\" aria-hidden=\"true\">\n <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\"><path d=\"M4 6h16M4 12h10M4 18h7\" /><path d=\"M16 16l2 2 4-4\" /></svg>\n </span>\n <div>\n <h2>Customer master data</h2>\n <p>Northbeam CRM · cleanup by <strong>CRM agent</strong> · {rows.length} accounts</p>\n </div>\n <span class=\"ard-status is-{status.tone}\"><span class=\"ard-dot\" aria-hidden=\"true\"></span>{status.text}</span>\n </div>\n <dl class=\"ard-stats\">\n <div><dt>Proposed</dt><dd>{tally.proposed}</dd></div>\n <div><dt>Pending</dt><dd>{tally.pending}</dd></div>\n <div><dt>Accepted</dt><dd class=\"is-good\">{tally.accepted}</dd></div>\n <div><dt>Rejected</dt><dd>{tally.rejected}</dd></div>\n </dl>\n </header>\n\n <div class=\"ard-agent\" aria-live=\"polite\">\n <ol class=\"ard-steps\" bind:this={stepsEl}>\n {#each steps as s (s.id)}\n <li class=\"ard-step is-{s.state}\" title=\"{s.title}: {s.call}\">\n <span class=\"ard-step-icon\" aria-hidden=\"true\">\n {#if s.state === 'running'}<span class=\"ard-spin\"></span>{:else}<svg viewBox=\"0 0 24 24\" width=\"12\" height=\"12\"><path d=\"M5 12.5l4.5 4.5L19 7.5\" /></svg>{/if}\n </span>\n <span class=\"ard-step-text\">\n <span class=\"ard-step-title\">{SHORT[s.title] ?? s.title}</span>\n <code>{s.call}</code>\n </span>\n {#if s.result}<span class=\"ard-step-result\">{s.result}</span>{/if}\n </li>\n {:else}\n <li class=\"ard-step is-idle\">The agent starts in a moment…</li>\n {/each}\n </ol>\n <div class=\"ard-actions\">\n <SvButton size=\"sm\" variant=\"outline\" disabled={agentState === 'running'} onclick={runAgain}>Run again</SvButton>\n <SvButton size=\"sm\" variant=\"ghost\" disabled={!tally.accepted} onclick={revertRun}>Revert run</SvButton>\n <SvButton size=\"sm\" variant=\"ghost\" disabled={!tally.proposed} onclick={copyForApprover}>Copy for approver</SvButton>\n </div>\n </div>\n {#if note}<p class=\"ard-note\" role=\"status\">{note}</p>{/if}\n\n {#if narrow}\n <div class=\"ard-tabs\" role=\"tablist\" aria-label=\"Show\">\n <button type=\"button\" role=\"tab\" aria-selected={view === 'grid'} onclick={() => (view = 'grid')}>Table</button>\n <button type=\"button\" role=\"tab\" aria-selected={view === 'side'} onclick={() => (view = 'side')}>Review ({tally.pending})</button>\n </div>\n {/if}\n\n <div class=\"ard-body\">\n <div class=\"ard-grid\" class:ard-hidden={narrow && view !== 'grid'}>\n <SvGrid\n data={rows}\n columns={review.columns(columns)}\n getRowId={(r) => r.id}\n conditionalFormats={review.formats}\n editable\n rowHeight={34}\n initialColumnPinning={{ left: ['company'] }}\n containerHeight={narrow ? 300 : 430}\n onApiReady={(a) => (api = a)}\n />\n </div>\n <aside class=\"ard-side\" class:ard-hidden={narrow && view !== 'side'}>\n <div class=\"ard-tabs\" role=\"tablist\" aria-label=\"Side panel\">\n <button type=\"button\" role=\"tab\" aria-selected={side === 'review'} onclick={() => (side = 'review')}>Review</button>\n <button type=\"button\" role=\"tab\" aria-selected={side === 'log'} onclick={() => (side = 'log')}>{log.length ? `Log (${log.length})` : 'Log'}</button>\n </div>\n <div class=\"ard-side-body\">\n {#if side === 'review'}\n <SvReviewPanel {review} title=\"The agent's changes\" />\n {:else}\n <ol class=\"ard-log\">\n {#each log as e (e.id)}\n <li class=\"is-{e.tone}\">\n <span class=\"ard-log-dot\" aria-hidden=\"true\"></span>\n <span class=\"ard-log-text\">{e.text}</span>\n <time>{time(e.at)}</time>\n </li>\n {:else}\n <li class=\"is-empty\">Decisions show up here, newest first, with who made them: what an app writes to its audit trail from onDecision.</li>\n {/each}\n </ol>\n {/if}\n </div>\n </aside>\n </div>\n</div>\n\n<style>\n .ard {\n display: flex;\n flex-direction: column;\n border: 1px solid var(--sg-border, #e5e7eb);\n border-radius: 12px;\n overflow: hidden;\n background: var(--sg-bg, #fff);\n color: var(--sg-fg, #0f172a);\n font-family: var(--sg-font, inherit);\n font-size: 13px;\n }\n .ard-head {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n flex-wrap: wrap;\n padding: 14px 18px;\n border-bottom: 1px solid var(--sg-border, #e5e7eb);\n }\n .ard-title { display: flex; align-items: center; gap: 12px; min-width: 0; flex-wrap: wrap; }\n .ard-logo {\n display: grid;\n place-items: center;\n width: 34px;\n height: 34px;\n flex: none;\n border-radius: 9px;\n background: var(--sg-fg, #0f172a);\n color: var(--sg-bg, #fff);\n }\n .ard-logo svg { fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }\n .ard-title h2 { margin: 0; font-size: 16px; font-weight: 650; letter-spacing: -0.01em; }\n .ard-title p { margin: 2px 0 0; font-size: 12px; color: var(--sg-muted, #64748b); }\n .ard-title strong { color: var(--sg-fg, #0f172a); font-weight: 600; }\n .ard-status {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 3px 10px;\n border-radius: 999px;\n font-size: 11.5px;\n font-weight: 650;\n --tone: var(--sg-muted, #64748b);\n color: color-mix(in srgb, var(--tone) 80%, var(--sg-fg, #0f172a));\n background: color-mix(in srgb, var(--tone) 13%, transparent);\n }\n .ard-status.is-info { --tone: var(--sg-info, #0284c7); }\n .ard-status.is-warning { --tone: var(--sg-warning, #d97706); }\n .ard-status.is-success { --tone: var(--sg-success, #16a34a); }\n .ard-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--tone); }\n .ard-status.is-info .ard-dot { animation: ard-pulse 1.1s ease-in-out infinite; }\n @keyframes ard-pulse { 50% { opacity: 0.3; } }\n\n .ard-stats { display: flex; gap: 22px; margin: 0; }\n .ard-stats div { display: flex; flex-direction: column; align-items: flex-end; }\n .ard-stats dt { font-size: 11px; color: var(--sg-muted, #64748b); }\n .ard-stats dd { margin: 0; font-size: 18px; font-weight: 650; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; }\n .ard-stats dd.is-good { color: var(--sg-success, #16a34a); }\n\n .ard-agent {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 18px;\n border-bottom: 1px solid var(--sg-border, #e5e7eb);\n background: var(--sg-bg-subtle, var(--sg-header-bg, #f8fafc));\n }\n .ard-steps {\n flex: 1;\n min-width: 0;\n display: flex;\n gap: 6px;\n margin: 0;\n padding: 2px 0;\n list-style: none;\n overflow-x: auto;\n scrollbar-width: thin;\n }\n .ard-step {\n display: flex;\n align-items: center;\n gap: 7px;\n flex: none;\n max-width: 260px;\n padding: 5px 10px 5px 7px;\n border: 1px solid var(--sg-border, #e5e7eb);\n border-radius: 8px;\n background: var(--sg-bg, #fff);\n animation: ard-in 0.25s ease-out;\n }\n @keyframes ard-in { from { opacity: 0; transform: translateY(3px); } }\n .ard-step.is-idle { color: var(--sg-muted, #64748b); border-style: dashed; animation: none; }\n .ard-step-icon {\n display: grid;\n place-items: center;\n width: 18px;\n height: 18px;\n flex: none;\n border-radius: 50%;\n color: var(--sg-bg, #fff);\n background: var(--sg-success, #16a34a);\n }\n .ard-step-icon svg { fill: none; stroke: currentColor; stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }\n .ard-step.is-running .ard-step-icon { background: none; }\n .ard-spin {\n width: 14px;\n height: 14px;\n border-radius: 50%;\n border: 2px solid color-mix(in srgb, var(--sg-info, #0284c7) 25%, transparent);\n border-top-color: var(--sg-info, #0284c7);\n animation: ard-rot 0.7s linear infinite;\n }\n @keyframes ard-rot { to { transform: rotate(360deg); } }\n .ard-step-text { display: flex; flex-direction: column; min-width: 0; }\n .ard-step-title { font-size: 12px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .ard-step code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: 10.5px;\n color: var(--sg-muted, #64748b);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .ard-step-result { font-size: 11.5px; font-weight: 650; font-variant-numeric: tabular-nums; white-space: nowrap; }\n .ard-actions { display: flex; gap: 6px; flex: none; }\n .ard-note { margin: 0; padding: 7px 18px; font-size: 12px; color: var(--sg-muted, #64748b); border-bottom: 1px solid var(--sg-border, #e5e7eb); }\n\n .ard-body { display: grid; grid-template-columns: minmax(0, 1fr) 360px; min-height: 0; }\n .ard-grid { min-width: 0; padding: 12px 0 12px 12px; }\n .ard-side { min-width: 0; display: flex; flex-direction: column; border-left: 1px solid var(--sg-border, #e5e7eb); margin-left: 12px; }\n .ard-side-body { max-height: 430px; overflow: auto; padding: 0 12px 12px; }\n .ard-side-body :global(.sv-review) { border: 0; padding: 0; }\n .ard-tabs { display: flex; gap: 2px; padding: 8px 12px 0; border-bottom: 1px solid var(--sg-border, #e5e7eb); }\n .ard-tabs button {\n padding: 6px 10px;\n margin-bottom: -1px;\n font: inherit;\n font-size: 12.5px;\n font-weight: 550;\n color: var(--sg-muted, #64748b);\n background: none;\n border: 0;\n border-bottom: 2px solid transparent;\n cursor: pointer;\n }\n .ard-tabs button[aria-selected='true'] { color: var(--sg-fg, #0f172a); border-bottom-color: var(--sg-fg, #0f172a); }\n .ard-tabs button:focus-visible { outline: 2px solid var(--sg-focus-ring, var(--sg-accent, #2563eb)); outline-offset: -2px; }\n\n .ard-log { list-style: none; margin: 0; padding: 10px 0 0; display: flex; flex-direction: column; }\n .ard-log li { display: grid; grid-template-columns: 10px minmax(0, 1fr) auto; align-items: baseline; gap: 8px; padding: 7px 0; border-bottom: 1px solid var(--sg-border, #e5e7eb); }\n .ard-log li.is-empty { display: block; color: var(--sg-muted, #64748b); border: 0; line-height: 1.5; }\n .ard-log-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--sg-muted, #94a3b8); transform: translateY(-1px); }\n .ard-log .is-accept .ard-log-dot { background: var(--sg-success, #16a34a); }\n .ard-log .is-reject .ard-log-dot { background: var(--sg-danger, #dc2626); }\n .ard-log time { font-size: 11px; color: var(--sg-muted, #64748b); font-variant-numeric: tabular-nums; }\n\n /* Data palette: segment pills carry their own colours. */\n .ard-seg {\n display: inline-block;\n padding: 1px 8px;\n border-radius: 999px;\n font-size: 11.5px;\n font-weight: 600;\n color: var(--seg);\n background: color-mix(in srgb, var(--seg) 12%, transparent);\n }\n .ard-hidden { display: none; }\n\n @media (max-width: 860px) {\n .ard-head { padding: 12px 14px; gap: 10px; }\n .ard-logo { display: none; }\n .ard-stats { gap: 14px; }\n .ard-stats dd { font-size: 15px; }\n .ard-side-body { max-height: 340px; }\n .ard-agent { flex-direction: column; align-items: stretch; padding: 10px 14px; }\n .ard-body { grid-template-columns: minmax(0, 1fr); }\n .ard-grid { padding: 10px; }\n .ard-side { margin-left: 0; border-left: 0; }\n }\n @media (prefers-reduced-motion: reduce) {\n .ard-step, .ard-spin, .ard-status.is-info .ard-dot { animation: none; }\n }\n</style>\n"
|
|
4081
|
+
},
|
|
4058
4082
|
{
|
|
4059
4083
|
"id": "71-submit-validation",
|
|
4060
4084
|
"path": "examples/src/demos/71-submit-validation.svelte",
|
|
@@ -4357,7 +4381,7 @@ export const docs = [
|
|
|
4357
4381
|
"path": "docs/brand/social/README.md",
|
|
4358
4382
|
"title": "GitHub social preview images",
|
|
4359
4383
|
"section": "Brand",
|
|
4360
|
-
"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.
|
|
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"
|
|
4361
4385
|
},
|
|
4362
4386
|
{
|
|
4363
4387
|
"slug": "changelog",
|
|
@@ -5008,7 +5032,7 @@ export const docs = [
|
|
|
5008
5032
|
"path": "docs/help/base/templates.md",
|
|
5009
5033
|
"title": "Ready-to-use bases",
|
|
5010
5034
|
"section": "SvGrid Base",
|
|
5011
|
-
"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\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\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\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\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\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\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\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\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\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\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"
|
|
5012
5036
|
},
|
|
5013
5037
|
{
|
|
5014
5038
|
"slug": "help/base/views",
|
|
@@ -5316,7 +5340,7 @@ export const docs = [
|
|
|
5316
5340
|
"path": "docs/help/columns/column-spanning.md",
|
|
5317
5341
|
"title": "Column & row spanning (merged cells)",
|
|
5318
5342
|
"section": "Columns",
|
|
5319
|
-
"markdown": "# Column & row spanning (merged cells)\n\nSpanning lets a single body cell cover **multiple columns** and/or **rows** -\nmerged report headers, grouped labels, financial statements. SvGrid does this\nwith a real `colspan` / `rowspan` merge engine; there are three ways to drive\nit, and the first is the one to reach for on a new grid.\n\n<div data-docs-demo=\"170-cell-merging\" data-height=\"480\"></div>\n\n## 0. The `mergedCells` prop (the renderer's own)\n\nThe grid draws merges itself from a list of origins with their spans, in\ndisplay indices:\n\n```svelte\n<SvGrid\n {data} {columns}\n mergedCells={[\n { rowIndex: 0, colIndex: 0, rowSpan: 1, colSpan: 4 }, // a title across A1:D1\n { rowIndex: 3, colIndex: 1, rowSpan: 3, colSpan: 1 }, // B4:B6 as one cell\n ]}\n/>\n```\n\nThe origin's td takes the `rowspan` / `colspan` and shows the origin's\nvalue; the covered cells are not drawn at all, so there is nothing to\nhide after the fact. A selection grows to whole merges (a merged cell is\none cell), the active cell inside a merge is its origin, the arrow keys\nstep over a merge as one cell, and `api.getMergedCells()` reads the list\nback. Under row virtualization a merge whose origin has scrolled out of\nthe rendered window is drawn from its first rendered row with the rows\nthat remain, and one that crosses the frozen boundary is drawn in two\nparts; nothing needs the covered rows mounted. The grid does not write\ninto covered cells on its own; a consumer that merges keeps them empty or\nmarks them read-only through the column's `editable`, which is what the\nspreadsheet shell's Merge & Center does.\n\n## 1. Explicit merges (spreadsheet-style, DOM action)\n\nDeclare exact merges as `MergeSpec[]` and apply them with the\n`spreadsheetLayout` action, which works on a grid you do not own the\nrender of (it edits the table after each paint). Prefer `mergedCells`\nwhere you can. The origin cell `(rowIndex, columnId)` spans\n`colspan` columns right and `rowspan` rows down; covered cells are hidden.\n\n```svelte\n<script lang=\"ts\">\n import { spreadsheetLayout, type MergeSpec } from '@svgrid/grid'\n\n const merges: MergeSpec[] = [\n { rowIndex: 0, columnId: 'A', colspan: 6 }, // title bar\n { rowIndex: 14, columnId: 'A', colspan: 3 }, // \"Total\" label\n ]\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\nSee [demos/170-cell-merging.svelte](../../../examples/src/demos/170-cell-merging.svelte).\n\n## 2. Declarative `colSpan` / `rowSpan` (value-driven)\n\nFor data-driven spanning - \"merge each run of equal values\", \"this cell spans 2\ncolumns when X\" - put `colSpan` / `rowSpan` callbacks on the column and turn\nthem into merges with `spansToMerges`. This runs on the **same** merge engine\nas option 1 (no separate code path).\n\n```svelte\n<script lang=\"ts\">\n // `SpanColumn` rather than `ColumnDef`: `spansToMerges` needs `id` to be\n // present, and on a ColumnDef it is optional.\n import { spreadsheetLayout, spansToMerges, type SpanColumn } from '@svgrid/grid'\n\n const columns: SpanColumn<Row>[] = [\n { id: 'region', field: 'region',\n // merge each vertical run of equal regions\n rowSpan: ({ data, rowIndex }) => {\n if (rowIndex > 0 && rows[rowIndex - 1].region === data.region) return 1 // covered\n let n = 1\n while (rows[rowIndex + n]?.region === data.region) n += 1\n return n\n } },\n { id: 'country', field: 'country' },\n { id: 'amount', field: 'amount' },\n ]\n\n // Recompute after sort / filter - indexes are display-row indexes.\n const merges = $derived(spansToMerges(rows, columns))\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\n`colSpan` / `rowSpan` receive `CellSpanParams` (`{ data, rowIndex, columnId,\nvalue }`) and return the span count (1 = no span). `spansToMerges` handles\ncovered-cell bookkeeping so overlapping spans never double-emit.\n\n## Virtualization note\n\nThe declarative `rowSpan` and the `spreadsheetLayout` action use real\n`rowspan` and need the covered rows mounted in the render window. For very\nlarge spanning grids on those two, keep spans modest or disable row\nvirtualization (`virtualization={false}`) so the origin cell stays mounted\nwhile its covered rows are on screen. The `mergedCells` prop has no such\nlimit: it clamps every span to the rendered window and continues a merge\nfrom its first rendered row.\n\n## More examples\n\n### Budget report: merged headers\n\nA half-year budget report laid out with merged cells the way Excel lays one out: a title merged across the page, Q1 / Q2 / H1 group headers merged over their months, a Line corner merged down two rows, a notes paragraph merged into one wrapped block. A merge is one cell to the grid: click inside Q1 and the Name Box says B2, Merge & Center lights, the arrows step over it and its column letters are shaded. Unmerge and merge again from the ribbon; Ctrl+Z each step.\n\n<div data-docs-demo=\"463-merged-report-headers\" data-height=\"560\"></div>\n\n## See also\n\n- [Cell merging demo](../../../examples/src/demos/170-cell-merging.svelte)\n- [Row spanning](../rows/row-spanning.md)\n"
|
|
5343
|
+
"markdown": "# Column & row spanning (merged cells)\n\nSpanning lets a single body cell cover **multiple columns** and/or **rows** -\nmerged report headers, grouped labels, financial statements. SvGrid does this\nwith a real `colspan` / `rowspan` merge engine; there are three ways to drive\nit, and the first is the one to reach for on a new grid.\n\n<div data-docs-demo=\"170-cell-merging\" data-height=\"480\"></div>\n\n## 0. The `mergedCells` prop (the renderer's own)\n\nThe grid draws merges itself from a list of origins with their spans, in\ndisplay indices:\n\n```svelte\n<SvGrid\n {data} {columns}\n mergedCells={[\n { rowIndex: 0, colIndex: 0, rowSpan: 1, colSpan: 4 }, // a title across A1:D1\n { rowIndex: 3, colIndex: 1, rowSpan: 3, colSpan: 1 }, // B4:B6 as one cell\n ]}\n/>\n```\n\nThe origin's td takes the `rowspan` / `colspan` and shows the origin's\nvalue; the covered cells are not drawn at all, so there is nothing to\nhide after the fact. A selection grows to whole merges (a merged cell is\none cell), the active cell inside a merge is its origin, the arrow keys\nstep over a merge as one cell, and `api.getMergedCells()` reads the list\nback. Under row virtualization a merge whose origin has scrolled out of\nthe rendered window is drawn from its first rendered row with the rows\nthat remain, and one that crosses the frozen boundary is drawn in two\nparts; nothing needs the covered rows mounted. The grid does not write\ninto covered cells on its own; a consumer that merges keeps them empty or\nmarks them read-only through the column's `editable`, which is what the\nspreadsheet shell's Merge & Center does.\n\nThe merge code loads with the first `mergedCells`, not with every grid, so\ngrids that never merge do not carry it. Until it lands the cells draw\nunmerged: one frame in the browser, and server-rendered HTML shows them\nunmerged until the page hydrates.\n\n## 1. Explicit merges (spreadsheet-style, DOM action)\n\nDeclare exact merges as `MergeSpec[]` and apply them with the\n`spreadsheetLayout` action, which works on a grid you do not own the\nrender of (it edits the table after each paint). Prefer `mergedCells`\nwhere you can. The origin cell `(rowIndex, columnId)` spans\n`colspan` columns right and `rowspan` rows down; covered cells are hidden.\n\n```svelte\n<script lang=\"ts\">\n import { spreadsheetLayout, type MergeSpec } from '@svgrid/grid'\n\n const merges: MergeSpec[] = [\n { rowIndex: 0, columnId: 'A', colspan: 6 }, // title bar\n { rowIndex: 14, columnId: 'A', colspan: 3 }, // \"Total\" label\n ]\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\nSee [demos/170-cell-merging.svelte](../../../examples/src/demos/170-cell-merging.svelte).\n\n## 2. Declarative `colSpan` / `rowSpan` (value-driven)\n\nFor data-driven spanning - \"merge each run of equal values\", \"this cell spans 2\ncolumns when X\" - put `colSpan` / `rowSpan` callbacks on the column and turn\nthem into merges with `spansToMerges`. This runs on the **same** merge engine\nas option 1 (no separate code path).\n\n```svelte\n<script lang=\"ts\">\n // `SpanColumn` rather than `ColumnDef`: `spansToMerges` needs `id` to be\n // present, and on a ColumnDef it is optional.\n import { spreadsheetLayout, spansToMerges, type SpanColumn } from '@svgrid/grid'\n\n const columns: SpanColumn<Row>[] = [\n { id: 'region', field: 'region',\n // merge each vertical run of equal regions\n rowSpan: ({ data, rowIndex }) => {\n if (rowIndex > 0 && rows[rowIndex - 1].region === data.region) return 1 // covered\n let n = 1\n while (rows[rowIndex + n]?.region === data.region) n += 1\n return n\n } },\n { id: 'country', field: 'country' },\n { id: 'amount', field: 'amount' },\n ]\n\n // Recompute after sort / filter - indexes are display-row indexes.\n const merges = $derived(spansToMerges(rows, columns))\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\n`colSpan` / `rowSpan` receive `CellSpanParams` (`{ data, rowIndex, columnId,\nvalue }`) and return the span count (1 = no span). `spansToMerges` handles\ncovered-cell bookkeeping so overlapping spans never double-emit.\n\n## Virtualization note\n\nThe declarative `rowSpan` and the `spreadsheetLayout` action use real\n`rowspan` and need the covered rows mounted in the render window. For very\nlarge spanning grids on those two, keep spans modest or disable row\nvirtualization (`virtualization={false}`) so the origin cell stays mounted\nwhile its covered rows are on screen. The `mergedCells` prop has no such\nlimit: it clamps every span to the rendered window and continues a merge\nfrom its first rendered row.\n\n## More examples\n\n### Budget report: merged headers\n\nA half-year budget report laid out with merged cells the way Excel lays one out: a title merged across the page, Q1 / Q2 / H1 group headers merged over their months, a Line corner merged down two rows, a notes paragraph merged into one wrapped block. A merge is one cell to the grid: click inside Q1 and the Name Box says B2, Merge & Center lights, the arrows step over it and its column letters are shaded. Unmerge and merge again from the ribbon; Ctrl+Z each step.\n\n<div data-docs-demo=\"463-merged-report-headers\" data-height=\"560\"></div>\n\n## See also\n\n- [Cell merging demo](../../../examples/src/demos/170-cell-merging.svelte)\n- [Row spanning](../rows/row-spanning.md)\n"
|
|
5320
5344
|
},
|
|
5321
5345
|
{
|
|
5322
5346
|
"slug": "help/columns/column-state",
|
|
@@ -5885,6 +5909,13 @@ export const docs = [
|
|
|
5885
5909
|
"section": "Help",
|
|
5886
5910
|
"markdown": "# Recipes / Cookbook\n\nQuick patterns for the questions that come up over and over. Each\nrecipe is paired with a live demo or a minimal snippet that runs\nagainst the shipping library.\n\n## Sort, filter, paginate at the same time\n\nThree of the most-asked features wired together against a 5k-row\ndataset. Click any header to sort, open the filter icon to filter,\nuse the pager at the bottom to walk pages:\n\n<div data-docs-demo=\"02-sort-filter-paginate\" data-height=\"440\"></div>\n\nThe implementation: register all three features in one\n`tableFeatures(...)` call and enable the matching props on `<SvGrid>`.\nSee [Filtering overview](./filtering/overview.md) and\n[Row sorting](./rows/row-sorting.md).\n\n## Select rows + copy / paste a range\n\nClick + drag selects a rectangular cell range; Ctrl/Cmd+C copies as\nTSV; pasting back from Excel writes through the same cell-write\npipeline as inline edit:\n\n<div data-docs-demo=\"04-selection-copy-paste\" data-height=\"440\"></div>\n\nThe pattern: enable `enableCellSelection={true}` and let the grid\nhandle the keyboard + paste plumbing. Cell writes go through\n`onCellValueChange` so your validator runs on every pasted value.\n\n## Bulk actions toolbar\n\nThe Gmail / Linear pattern: tick row checkboxes, a sticky toolbar\nreveals \"Mark / Delete / Copy as TSV\":\n\n<div data-docs-demo=\"23-bulk-actions\" data-height=\"440\"></div>\n\nThe trick: subscribe to `onRowSelectionChange` and render your\ntoolbar whenever the count is > 0. The grid doesn't ship a bulk-action\ncomponent on purpose - your design system's button + toast UI is\nbetter than anything we could embed.\n\n## Cascade editing (formula-like dependencies)\n\nEditing qty / price cascades into line totals + a summary card:\n\n<div data-docs-demo=\"18-cascade-editing\" data-height=\"440\"></div>\n\nIn `onCellValueChange`, after writing the cell, recompute the dependent\ncells in the same row (or in the summary state) and let Svelte 5's\nreactivity carry the update through. The pattern is essentially\n\"editable cells + a `$derived` summary\".\n\n## Validation while editing\n\nPer-column rules: invalid commits get rolled back via `setCellValue`,\nand a sidebar logs the rejection so users can audit what was tried:\n\n<div data-docs-demo=\"24-validation\" data-height=\"440\"></div>\n\nUse `onCellValueChange`: validate, and if invalid, call\n`api.setCellValue(rowIndex, columnId, oldValue)` to undo. The grid\nemits a fresh `onCellValueChange` for the undo write that your\nvalidator can recognise and skip.\n\n## Column pinning + freezing\n\nWide 13-column grid: pin Company on the left and Price on the right;\nthe middle scrolls under sticky edges:\n\n<div data-docs-demo=\"25-column-pinning\" data-height=\"440\"></div>\n\nThe user pins via the column menu - no extra wiring needed if\n`columnFilteringFeature` is registered (the menu lives on the same\nheader button). Or set the whole pinning state programmatically with\n`api.setColumnPinning({ left: ['name'], right: ['total'] })` - pass an\nempty array for a side to unpin it. `api.getColumnPinning()` reads it\nback for persistence.\n\n## List + chips editors\n\nThe two built-in multi-select editors:\n\n<div data-docs-demo=\"26-list-chips-editors\" data-height=\"440\"></div>\n\nAdd `editorType: 'list'` for a single `<select>` or `editorType: 'chips'`\nwith `editorMultiple={true}` for removable tokens. Pass static\n`editorOptions` or a `(row) => options` callback for cascading lists\n(e.g. City options depend on Country).\n\n## Spreadsheet ribbon\n\nAn Excel-style Ribbon UI driving the grid via `SvGridApi`: bold + colour\n+ number format + insert/delete row + sort, plus a live SUM/AVG/COUNT\nstatus bar:\n\n<div data-docs-demo=\"27-spreadsheet-ribbon\" data-height=\"500\"></div>\n\nThe ribbon is a regular Svelte component; every button calls\n`api.setCellValue`, `api.addRow`, `api.setSort`, etc. Status bar\nreads `getDisplayedRows()` for the live aggregate.\n\n## Master / detail\n\nA hierarchical row that expands to reveal a child grid:\n\n<div data-docs-demo=\"08-tree-and-master-detail\" data-height=\"440\"></div>\n\nSame flatten pattern as [tree rows](./rows/tree-rows.md): a flat\n`visibleRows` derivation, plus a custom cell snippet that renders the\ndetail grid inline when the row is expanded.\n\n## Forms-in-grid (master grid + side form)\n\nClick a row to load it into a tabbed detail form on the right; edits\nflow back to the grid live:\n\n<div data-docs-demo=\"40-forms-master-detail\" data-height=\"500\"></div>\n\nPattern: `onActiveCellChange` -> set `activeRowId` -> `draft = $state.snapshot(activeRow)` -> form\nbinds against `draft`. On save, write `draft` back into the rows array.\n**Use `$state.snapshot()`, not `structuredClone()`**, on Svelte 5 state\nproxies - the latter throws `DataCloneError`.\n\n## Saved views / persistence\n\nPivot-lite with chips + saved views stored in localStorage:\n\n<div data-docs-demo=\"36-reporting-workspace\" data-height=\"500\"></div>\n\nThe pattern: a `view: { groupBy, sortBy, filters, columns }` object\nthat you serialise into localStorage under a versioned key\n(`'my-app:view:v1'`). On load, hydrate the state from the saved view\nand call the matching `api.set*` methods.\n\n## Theming studio\n\nLive token playground: brand color, density, radius, font, dark/light,\nzebra. The CSS snippet at the bottom is copy-ready:\n\n<div data-docs-demo=\"37-theming-studio\" data-height=\"540\"></div>\n\nTheming is `--sg-*` custom properties - see [Tailwind integration](./tailwind.md)\nfor the full token list.\n\n## Localisation + RTL switching\n\nSix locales (en, de, fr-CA, ja, ar, he); headers, currencies, dates,\nand the grid's own scrollbar flip:\n\n<div data-docs-demo=\"38-rtl-i18n\" data-height=\"500\"></div>\n\nSet `<html dir=\"...\">` and `<html lang=\"...\">` based on the locale.\nPer-column `format: { type: 'currency', locales }` overrides the\ndocument locale for specific columns.\n\n## Print + boardroom export\n\nQuarterly P&L print pack: cover page, repeat-on-page headers, page-\nsize + orientation, CSV / HTML download, browser-native PDF:\n\n<div data-docs-demo=\"39-print-board-export\" data-height=\"500\"></div>\n\n`api.print({ title, columns, rows, orientation, pageSize })` opens a\nsandbox window with an isolated HTML document and calls `.print()` on\nit. The popup pattern is what isolates your print stylesheet from your\napp's CSS.\n\n## Healthcare EMR (role-based editing)\n\nInpatient board with vitals sparklines, risk score, code status, allergy\nchips, role-based editing (viewer / nurse / physician / admin):\n\n<div data-docs-demo=\"41-healthcare-emr\" data-height=\"500\"></div>\n\nThe role gate uses `editable: (ctx) => roleCanEdit(currentRole, ctx.column.id)`.\nThat lambda runs per-cell, so you get column + role granularity\nwithout a separate config table.\n\n## Live shipment / fleet board\n\nStreaming-style live update at 2-3 Hz with cell-level flash on change,\nETA delta colors, alert chips:\n\n<div data-docs-demo=\"42-logistics-fleet\" data-height=\"500\"></div>\n\nThe pattern: a `$state` rows array that you mutate from a\nWebSocket/SSE handler. The render component diffs at the data-array\nlevel, so reassigning the array (`rows = updated`) is what triggers\nthe visible repaint.\n\n## Compliance / approval queue\n\nL1 / L2 / L3 approval chain with live SLA timer, role-gated approve /\nreturn / reject buttons, immutable case-history audit panel:\n\n<div data-docs-demo=\"43-compliance-queue\" data-height=\"500\"></div>\n\nThis is the pattern for any \"this row needs a decision; some users can\nmake it, some can't\" workflow. Status changes go through a state\nmachine you own; the grid only renders the current state.\n\n## Field service dispatch\n\nDispatcher board: priority + status + tech editable inline, SLA tone\ngauge, today-timeline cell, tech capacity panel, live status stream:\n\n<div data-docs-demo=\"44-field-service\" data-height=\"500\"></div>\n\nSame `editable: (ctx) => ...` per-cell pattern for tech/status. The\ntoday-timeline cell is a positioned-bar in a single wide cell - see\nthe [pivot doc](./pivot.md) for that pattern.\n\n## Gantt chart in a grid\n\nProject plan with a wide custom Schedule cell: bars positioned by\nstart/end %, phase coloring, progress fill, today line, overdue glow:\n\n<div data-docs-demo=\"45-gantt-chart\" data-height=\"540\"></div>\n\nNo special Gantt mode - it's a single wide cell per row whose snippet\npositions absolute bars by `(start - projectStart) / projectSpan * 100`.\nAxis above the grid uses the same math.\n\nFor a real plan - a work-breakdown tree with rolled-up phases, dependency\narrows and a zoomable axis - use [Gantt chart mode](/help/rows/gantt), the\n`gantt` prop's Enterprise renderer, rather than building on this recipe.\n\n## Scheduler (single-day appointments)\n\nProviders as rows, an hour axis, click any appointment to edit it in\nthe side panel. Now-line ticks live:\n\n<div data-docs-demo=\"46-scheduler\" data-height=\"540\"></div>\n\nSame single-wide-cell pattern as the Gantt. The axis-wrap inside the\ngrid wrapper uses `ResizeObserver` so the axis width matches the\nschedule column - that's what keeps the now-line aligned between the\nheader and the cells.\n\n## Trash truck timeline (animated)\n\nPublic-works dispatcher: each truck glides along its day-long route\nwith spinning wheels, stops, and live fill levels:\n\n<div data-docs-demo=\"47-trash-truck-timeline\" data-height=\"540\"></div>\n\nThe mover uses `transition: left 220ms linear` so the new position\nanimates in. The bounce + wheel spin are CSS keyframes; no JS animation\nloop required.\n\n## CRM - sales pipeline\n\nDeal board with stage chips, weighted forecast bar, inline stage +\nprobability editing, deal detail aside with activity feed:\n\n<div data-docs-demo=\"48-crm-sales-pipeline\" data-height=\"540\"></div>\n\nThis is the canonical example of mixing inline edit + a side panel\nthat mirrors the active row.\n\n## Enterprise admin dashboard\n\nCRUD-heavy users board: inline role / status / MFA edit, bulk\nactivate / deactivate / delete, invite dialog, permissions matrix,\nlive audit log:\n\n<div data-docs-demo=\"49-admin-dashboard\" data-height=\"540\"></div>\n\nThe audit log is the recurring pattern: every mutation appends an\nentry to a `$state` array; the right-side panel renders the array.\nDelete + Invite use simple `<dialog>`-style modals.\n\n## E-commerce seller panel\n\nTabbed Amazon-seller view: catalog with SVG thumbnails, inventory bars\nvs reorder threshold, live orders pipeline, pricing rules:\n\n<div data-docs-demo=\"50-seller-panel\" data-height=\"540\"></div>\n\nThe tab strip is just chip buttons that swap which dataset / columns\nthe grid receives. One grid component, four tabs - share styling and\nbehavior without four separate mounts.\n\n## Long-form recipes\n\nThe recipes above pair a paragraph + a demo. These deeper write-ups\nhave their own pages:\n\n- [Persist column layout to URL](../recipes/persist-column-layout-to-url.md) - sort + filter + page in the URL, with debounced replaceState and restore-on-mount.\n- [Two-grid master / detail](../recipes/two-grid-master-detail.md) - one master grid drives a second detail grid; remount semantics and multi-select union.\n- [Bulk-edit selected rows](../recipes/bulk-edit-selected-rows.md) - the standard back-office workflow: pick a field, pick a value, apply to N selected rows. Includes optimistic + rollback patterns.\n- [Server-side filter with TanStack Query](../recipes/server-side-filter-with-tanstack-query.md) - caching, deduplication, cancellation, retries, optimistic edits via mutations.\n\n## See also\n\n- [Architecture overview](./architecture.md) - the layered model that\n makes these recipes composable.\n- [API reference](../reference/index.md) - every method called in the\n recipes above.\n"
|
|
5887
5911
|
},
|
|
5912
|
+
{
|
|
5913
|
+
"slug": "help/review/change-review",
|
|
5914
|
+
"path": "docs/help/review/change-review.md",
|
|
5915
|
+
"title": "Change review - Enterprise",
|
|
5916
|
+
"section": "help/review",
|
|
5917
|
+
"markdown": "# Change review - Enterprise\n\nAn AI helper fills 900 empty cells, an agent cleans up a CRM export, an import\nupdates 2,000 rows. None of those writes was typed by the person who owns the\ndata, and none of them should land before someone has looked. Change review\nholds such writes as **proposals**, apart from the data, groups them by what\nthey do, and lets a person accept or reject a group at a time. Only accepted\nvalues are written, and each decision is one Ctrl+Z.\n\n```ts\nimport { createReview, reviewSmartFill, SvReviewPanel } from '@svgrid/enterprise/review'\n```\n\n<div data-docs-demo=\"702-change-review\" data-height=\"620\"></div>\n\nIn the demo, **Run cleanup agent** proposes fixes to a customer table. Nothing\nis written until you accept a group in the panel. Edit a cell that has a\nproposal before accepting it and the proposal is marked stale. **Import\ncrm-update.csv** proposes a different region for two customers the agent also\nfilled, and the panel asks which one to keep.\n\n## A grid with a review\n\n```svelte\n<script lang=\"ts\">\n import { SvGrid, type SvGridApi } from '@svgrid/grid'\n import { createReview, SvReviewPanel } from '@svgrid/enterprise/review'\n\n let rows = $state(customers)\n let api = $state<SvGridApi<any, Customer> | null>(null)\n\n const review = createReview<Customer>({\n api: () => api,\n setRows: (next) => (rows = next),\n onCommit: async (accepted) => {\n await fetch('/api/customers/bulk', { method: 'PATCH', body: JSON.stringify(accepted) })\n },\n })\n</script>\n\n<div class=\"layout\">\n <SvGrid\n data={rows}\n columns={review.columns(columns)}\n getRowId={(r) => r.id}\n conditionalFormats={review.formats}\n onApiReady={(a) => (api = a)}\n />\n <SvReviewPanel {review} />\n</div>\n```\n\nThree things are required:\n\n- **`getRowId` on the grid.** Proposals are keyed by row id, because row\n positions move on sort, filter and insert. `createReview` reads the function\n from the grid and throws a clear error when it is missing.\n- **The app owns the rows.** `setRows` replaces the array the grid is given,\n and it must apply synchronously. Reads go through `api.getData()`, which\n includes the grid's own writes (a paste, a fill, `addRows`), so building the\n next array from it carries those forward.\n- **The grid api**, passed as a getter, because `onApiReady` fires after mount.\n\n## Adding proposals\n\nAnything can add a set of proposals. Each one names the row, the field, the\nvalue it saw (`before`) and the value it proposes (`after`):\n\n```ts\nreview.add({\n source: { kind: 'agent', id: 'crm-cleanup', label: 'Cleanup agent' },\n proposals: [\n { rowId: 'c-104', field: 'company', before: 'Acme Inc.', after: 'Acme Inc' },\n { rowId: 'c-221', field: 'phone', before: '(555) 123-4567', after: '555-123-4567', reason: 'one phone format' },\n ],\n})\n```\n\n`confidence` (0 to 1) and `reason` are optional and show in the panel.\nProposals whose `after` equals `before` are skipped. A newer proposal from the\nsame source for the same cell replaces the older one. Two sources proposing\ndifferent values for one cell is a **conflict**: neither can be accepted by a\ngroup action until a person keeps one.\n\n### From the AI helpers\n\nThe AI helpers in `@svgrid/grid` return predictions keyed by data index.\n`reviewSmartFill` and `reviewClassify` snapshot the data before the call,\nresolve each index to its row id, drop indices the helper was not asked about,\nand add the result:\n\n```ts\nconst result = await reviewSmartFill(review, api, {\n field: 'region',\n examples: [{ input: { country: 'Germany' }, output: 'EMEA' }],\n})\nresult.dropped // predictions that pointed at rows outside the request\n```\n\n`fromSmartFill(result, snapshot, { api })` and `fromClassify` do the same for a\nresult you already have; pass the snapshot you took before calling the helper.\n\n### From an import or a sync\n\n`fromRows` diffs incoming rows against the grid's data by a key field and\nproposes one change per field that differs:\n\n```ts\nconst set = fromRows(imported.rows, {\n api,\n key: 'id',\n source: { kind: 'import', id: file.name, label: file.name },\n})\nreview.add(set)\nset.unmatched // incoming rows with no match; adding rows is not proposed yet\n```\n\n## How proposals are grouped\n\nThe panel never shows 2,000 cells in a list. `review.groups()` puts every\npending proposal in one group by the change it makes. The first four kinds are\n**rule groups**: every member is proven to follow the rule. The rest are\n**judgment groups**, where a person has to look.\n\n| Kind | Rule | Label in the panel |\n|---|---|---|\n| `whitespace` | `after` is `before` trimmed or with spaces collapsed | Trim spaces in Company |\n| `case` | same letters, different case | Change Email to lower case |\n| `format` | same characters apart from punctuation, the same unambiguous date, or text that parses to the number | Reformat Phone as 999-999-9999 |\n| `scale` | `after / before` is one number, 5 or more members | Divide Revenue by 100 |\n| `same-mapping` | several `before` values each mapped to one `after` at least twice | Country: 6 values → United States |\n| `fill-empty` | blank `before`, one group per proposed value | Fill empty Region with EMEA |\n| `constant-target` | many different `before` values, one `after` | Set Status to Closed |\n| `unpatterned` | everything else, per field | Notes: no shared pattern |\n\nA few cases are kept out of the rule groups on purpose. `\"3.5\"` to `\"35\"` keeps\nevery digit but changes the number, so it is not a format change. `03/05/2024`\ncould be March or May, so a reformat of it is never proven. A rule group proves\nthat every member follows its rule, not that the rule is right: an agent that\ndivides by 10 where it should divide by 100 shows up as its own \"Divide Revenue\nby 10\" group, labelled for what it does.\n\nThe panel lists the risky groups first: unpatterned, then one target from many\nvalues, then groups with low confidence, then the rest by size. Each group\ncarries a sample to check: every member below 60% confidence (up to ten), then\nmembers spread across the group. An unpatterned group lists every member.\n`same-mapping` and `constant-target` groups show which `before` values they\nmap, so \"everything became Canada\" is visible at a glance.\n\n## What the grid shows\n\n`review.formats` tints every cell with a pending proposal and draws a dot before\nits value, so the mark is never colour alone. Pass it as `conditionalFormats`,\nconcatenated with your own formats if you have them. Theme the tint with\n`--sg-review-pending-bg`. A cell two sources disagree on gets a red wash and a\n\"!\" instead (`--sg-review-conflict-bg`), so the grid shows where the panel's\nconflicts are.\n\n`review.columns(columns)` draws the proposal inside the cell: the proposed\nvalue, then the current value struck through. It does this by wrapping the\ncolumn's `cell`, and only for columns where that leaves the rest of the column\nas it was: columns with a `cell` of their own, and plain text columns.\nCheckbox, list, chips and boolean columns, and field types with a cell of their\nown, keep their cell as it is and show the proposed value after it (\"→ Closed\").\n\n## Deciding\n\n```ts\nconst outcome = await review.acceptGroup(group.key, group.ids)\n// { accepted: [...], rejected: [], stale: [...], skipped: [...], error? }\n```\n\nOn accept, for each proposal:\n\n1. An open cell editor is committed first, so a value someone just typed wins.\n Under `fullRowEditing`, the row being edited is left pending instead.\n2. If the cell no longer holds `before`, the proposal becomes **stale** and is\n not written.\n3. `onCommit` receives the remaining proposals. Throw or reject to keep them\n pending; nothing is written.\n4. The cells are checked again, because a person could edit one while\n `onCommit` was saving.\n5. One `setRows` call writes every accepted value.\n6. One undo step is recorded. Ctrl+Z in the grid writes the old values back,\n by row id, so it works with paging and filters on, and returns the proposals\n to pending. A cell edited after the accept is left as it is.\n\n`acceptGroup` and `rejectGroup` take the ids that were shown, so a proposal\nthat arrived after the panel rendered is never decided unseen.\n\n### Server row model\n\nWith the server row model there is no app array to replace. Pass the\ncontroller instead of `setRows`; `onCommit` is then required:\n\n```ts\nconst review = createReview({\n api: () => api,\n server: controller,\n onCommit: (accepted) => saveToServer(accepted),\n})\n```\n\nAccept saves through `onCommit` and refreshes the controller. Undo saves the\ninverse (`before` and `after` swapped) and refreshes again. The backend decides\nstaleness there.\n\n## SvReviewPanel\n\n| Prop | Type | Default | |\n|---|---|---|---|\n| `review` | `Review` | required | What `createReview` returned. |\n| `title` | `string` | `'Review changes'` | The panel heading. |\n| `confirmOver` | `number` | `50` | Ask before deciding more than this many at once. |\n| `onDecide` | `(outcome) => void` | | Called after each decision. |\n\n**Accept rule groups** accepts every rule group at once (trims, case changes,\nreformats, one numeric factor), the changes that are proven by their rule, and\nleaves the groups that need a person. It is the panel's primary button, and\nrule groups are the only ones marked, with a \"Rule\" badge. **Accept all** is\nthe primary button only when every group left is a rule group: deciding\neverything unseen is what a review is there to prevent.\n\nA line in an open group names its row, then the change, then the reason and\nconfidence the source gave. The name is the row's first visible text column\n(the company, say), and a line leaves it out when that column is the one being\nchanged, since the old value already names the row. Set `rowLabel` on\n`createReview` to choose it yourself:\n\n```ts\nconst review = createReview<Customer>({\n api: () => api,\n setRows: (next) => (rows = next),\n rowLabel: (row) => `${row.company} (${row.city})`,\n})\n```\n\nA click on a line shows that row in the grid, and the row lights up for a\nmoment so the eye finds it. A value is quoted only where the quotes say\nsomething: around spaces at its ends (shown as dots), or when text reads as a\nnumber or a boolean.\n\nEach line of an open group has its own accept and reject, for a group that is\nmostly right: reject the two wrong guesses, then accept the group. A judgment\ngroup lists its sample first; **Show all** lists every change in it, up to\n200. A decision can move what is left of a group under another heading (two\n\"EMEA\" fills less one is a single fill, pooled with the others), and the open\ngroup follows its remaining changes rather than closing.\n\nIt is a plain panel, not a drawer, so the grid stays usable beside it. Inside\nthe group list, **J** and **K** move between groups, **Enter** opens one, **A**\naccepts it and **R** rejects it. \"Show in grid\" goes to the group's next row\nwithout moving the active cell: with client paging it turns to the row's page\nfirst (`api.getRowPosition`), then scrolls to it. Rows a filter hides are\ncounted, not shown. With grouping, where pages count groups, it stays on the\ncurrent page.\n\n**Only rows with changes** narrows the grid to the rows with a pending or\nconflicting proposal, on top of whatever the user filtered: it adds one\ncondition to the advanced filter with AND, and switching it off takes that\ncondition back out and leaves the rest. Rows leave the view as their\nproposals are decided, like an inbox. From code:\n`review.showPendingOnly(true)`, and `review.pendingOnly` tells whether it is\non. It needs the advanced filter engine, which it turns on itself.\n\n## Agents\n\n`createGridTools` gives an AI agent four tools over the grid's data. None of\nthem writes the data: the agent's edits arrive in the review like any other\nproposals, and a person decides.\n\n<div data-docs-demo=\"704-agent-review-desk\" data-height=\"700\"></div>\n\nIn the demo a scripted CRM agent calls these tools step by step; each step\nshows the tool call it made. The Log tab lists every decision as\n`onDecision` reports it.\n\n| Tool | What it does |\n|---|---|\n| `grid_describe` | The columns (field, header, type), the row count, and which fields the agent may edit. |\n| `grid_query_rows` | Rows matching `where` conditions (`equals`, `contains`, `blank`, `gt`, ...), with their `rowId`, paged and capped at `maxRows`. |\n| `grid_propose_edits` | Adds edits as proposals, with a reason and a confidence. Unknown rows, fields the agent may not edit, and edits that change nothing are skipped and reported. |\n| `grid_review_status` | How many of the agent's proposals are pending, accepted, rejected or stale, so it can learn from the review. |\n\n```ts\nimport { createGridTools, registerWebMcpTools } from '@svgrid/enterprise/review'\n\nconst tools = createGridTools({\n review,\n api: () => api,\n fields: ['region', 'phone'], // what the agent may propose edits to\n source: { kind: 'agent', id: 'crm-agent', label: 'CRM agent' },\n})\n```\n\nEach tool is `{ name, description, inputSchema, execute }`: hand them to the\ntool loop of your LLM SDK, or to an MCP server of your own.\n`registerWebMcpTools(tools)` registers them with the browser's WebMCP API\n(`document.modelContext`), so an agent driving the page can call them. WebMCP\nis a draft; where a browser does not have it, the call returns\n`{ supported: false }` and does nothing.\n\nA model's input is not trusted. One `grid_propose_edits` call carries at most\n`maxEdits` edits (500 by default) and a larger one is refused. A value that\ndoes not fit its column (text for a number, an object for a text cell, a list\nfor a single value) is skipped and reported back, not proposed.\n\n## Audit log and revert\n\n`onDecision` is called after every accept and reject, and after their undo and\nredo, with copies of the proposals it moved and who decided. Write these to\nyour own audit log:\n\n```ts\ncreateReview({\n api: () => api,\n setRows: (next) => (rows = next),\n user: currentUser.email,\n onDecision: (d) => audit.write({ action: d.action, by: d.by, at: d.at, changes: d.proposals }),\n})\n```\n\n`review.log()` lists the decided proposals in this session, in the order they\nwere decided.\n\nIf an undo or redo has to save through `onCommit` and the save fails, nothing\nis written and the decision stands. `onError(error, 'undo' | 'redo')` is\ncalled, `review.lastError` holds it, and the panel says \"Undo not saved\".\n\nCtrl+Z covers the last decisions. To take back a whole set later,\n`review.revertSet(setId)` adds a new set that proposes each accepted value's\nreverse. It is reviewed and accepted like any other, so a cell edited after the\noriginal accept is not overwritten.\n\n## Routing to an approver\n\n`review.toJSON({ setIds })` exports sets with their proposals as plain JSON.\nOn the approver's page, `review.merge(json)` adds them beside what that review\nalready holds. A cell that also has a pending proposal there from another\nsource becomes a conflict. `review.load(json)` replaces everything instead.\n\nAn export can come from another person, another session or an agent, so both\ncheck it first. Something that is not an export (`{ v: 1, sets: [...] }`)\nthrows and leaves the review as it was; a proposal with no id, row, field or a\nknown status is dropped. Both return `{ dropped }`.\n\nA person's own staged edits can take the same route. `fromStaged` turns a\n`createStagedEditing` buffer into proposals. Staged edits have already been\nwritten into the grid, so revert the stage first:\n\n```ts\nconst changes = stage.changes()\nstage.revert((rowIndex, columnId, value) => api.setCellValue(rowIndex, columnId, value))\nreview.add(fromStaged(changes, { api, source: { kind: 'user', id: me.id, label: `${me.name} (staged)` } }))\nconst forApprover = JSON.stringify(review.toJSON({ setIds: [review.sets().at(-1)!.id] }))\n```\n\n## At scale\n\nA test in the package runs 100,000 rows and 20,000 proposals through every\nstep and fails if one becomes slow. Measured in jsdom on a development\nmachine (2026-10-24):\n\n| Step | Time |\n| --- | --- |\n| Add 20,000 proposals | 88 ms |\n| Group them | 55 ms |\n| Build the tint rules | 8 ms |\n| Mark 1,000 cards | 24 ms |\n| Accept all 20,000 (one `setRows`) | 140 ms |\n| Undo, then redo | 71 ms, 96 ms |\n\nClustering, the stale checks and the writes are each a single pass over the\nproposals and the rows; nothing compares every proposal with every row.\n\n## With SvGrid Base\n\n`SvBase` hands any prop it does not use to its grid, so a review attaches the\nsame way. Add `onApply: baseReviewApplied(...)` so an accept does what an edit\ndoes in a base: \"Last modified time\" and \"Last modified by\" fields are stamped\nin the same write, and the record's activity credits the change to what\nproposed it and to the person who accepted it (\"CRM agent (accepted by Dana)\").\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, baseReviewApplied } from '@svgrid/enterprise/base'\n import { createReview, SvReviewPanel } from '@svgrid/enterprise/review'\n\n enableBase()\n let records = $state(initialRecords)\n let api = $state(null)\n const review = createReview({\n api: () => api,\n setRows: (next) => (records = next),\n onApply: baseReviewApplied(() => api),\n })\n</script>\n\n<SvBase\n data={records}\n columns={review.columns(columns)}\n conditionalFormats={review.formats}\n primaryField=\"name\"\n onApiReady={(a) => (api = a)}\n/>\n<SvReviewPanel {review} />\n```\n\nWhat a base shows:\n\n- **The proposed value in the cell** for field types that draw no cell of\n their own: single line text, long text, date, number, currency, percent,\n duration, formula, autonumber, lookup, rollup, count, created time and last\n modified time.\n- **The proposed value beside the cell** for types with a cell of their own:\n attachment, checkbox, single and multiple select, user, phone, email, URL,\n barcode, button, rating, link, created by and last modified by, and long\n text set to rich text or a percent drawn as a bar. The cell draws as it\n always does and \"→ Closed\" follows it, read through the field's own\n formatter, so a person shows by name.\n- **Cards and events too.** Kanban and gallery cards with pending proposals\n show \"2 proposed\", and calendar events a dot, with the fields and values on\n hover. A form adds new records, so it has nothing to mark.\n- **Sync.** With `createBaseSync`, an accepted value is a change like any\n other and is saved with the rest. Changes made elsewhere are still marked as\n before; a review is the step before that, where an agent proposes and a\n person decides.\n\nWith several tables (`tables`), keep one review per table: proposals are keyed\nby record id, and ids can repeat across tables. Give the active table's review\nto the grid and write into that table's rows:\n\n```ts\nconst review = createReview({\n api: () => api,\n setRows: (next) => (tables = tables.map((t) => (t.id === 'tasks' ? { ...t, data: next } : t))),\n onApply: baseReviewApplied(() => api),\n})\n```\n\n## Wording and languages\n\nEvery string the review shows comes from one message map with English\ndefaults: the panel, the group labels, the card and cell marks, and the notes\non proposals that were not written. Pass any subset to `createReview`, and\nunset keys stay English. `{name}` placeholders are filled in; `REVIEW_MESSAGES`\nlists every key with its English text.\n\n```ts\nconst review = createReview({\n api: () => api,\n setRows: (next) => (rows = next),\n messages: {\n acceptAll: 'Alle annehmen',\n changes: '{count} Änderungen',\n labelWhitespace: 'Leerzeichen in {field} kürzen',\n cardProposed: '{count} vorgeschlagen',\n },\n})\n```\n\n`<SvReviewPanel messages={...}>` overrides the review's wording for one panel.\n\n## Licensing\n\nChange review is part of SvGrid Enterprise. Without a license key it runs with\na watermark and a one-time notice. It adds nothing to `@svgrid/grid`: the tint\nis `conditionalFormats`, the proposed value is a wrapped `cell`, and the undo\nstep goes through the grid's public command context.\n\n## See also\n\n- [AI helpers](../ai.md)\n- [Undo and redo](../editing/undo-redo.md)\n- [Conditional formatting](../cells/conditional-formatting.md)\n- [Server-side row model](../server/server-row-model.md)\n"
|
|
5918
|
+
},
|
|
5888
5919
|
{
|
|
5889
5920
|
"slug": "help/rows/accessing-rows",
|
|
5890
5921
|
"path": "docs/help/rows/accessing-rows.md",
|
|
@@ -6009,7 +6040,7 @@ export const docs = [
|
|
|
6009
6040
|
"path": "docs/help/rows/tree-data.md",
|
|
6010
6041
|
"title": "Tree data",
|
|
6011
6042
|
"section": "Rows",
|
|
6012
|
-
"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"
|
|
6013
6044
|
},
|
|
6014
6045
|
{
|
|
6015
6046
|
"slug": "help/rows/tree-rows",
|
|
@@ -7626,7 +7657,7 @@ export const docs = [
|
|
|
7626
7657
|
"path": "docs/reference/SvGridApi.md",
|
|
7627
7658
|
"title": "SvGridApi reference",
|
|
7628
7659
|
"section": "API reference",
|
|
7629
|
-
"markdown": "# `SvGridApi` reference\n\nThe imperative API exposed via `<SvGrid onApiReady={(api) => ...}>`.\nUse it for data, column, filter, sort, group, selection, and\nvisibility operations from outside the component.\n\n```ts\nimport type { SvGridApi } from '@svgrid/grid'\n\nlet api = $state<SvGridApi<typeof features, Order> | null>(null)\n```\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onApiReady={(next) => (api = next)}\n/>\n\n<button onclick={() => api?.addRow({ /* ... */ })}>Add row</button>\n```\n\n## Cells\n\n### `getCellValue(rowIndex, columnId)`\n\n```ts\ngetCellValue(rowIndex: number, columnId: string): unknown\n```\n\nRead a cell value from the underlying data. Returns `undefined` when\neither argument doesn't resolve.\n\n### `setCellValue(rowIndex, columnId, value)`\n\n```ts\nsetCellValue(rowIndex: number, columnId: string, value: unknown): void\n```\n\nWrite a cell value through the column's `field`. Triggers a re-render.\nDoes NOT fire `onCellValueChange` - that callback is for **user**\nedits.\n\n## Rows\n\n### `addRow(row, position?)`\n\n```ts\naddRow(row: TData, position?: 'top' | 'bottom' | number): void\n```\n\n`position` defaults to `'bottom'`. A numeric index inserts before that\nindex.\n\n### `addRows(rows, position?)`\n\n```ts\naddRows(rows: ReadonlyArray<TData>, position?: 'top' | 'bottom' | number): void\n```\n\nBatched insert. Cheaper than calling `addRow` in a loop for hundreds\nof rows.\n\n### `removeRow(rowIndex)` / `removeRows(rowIndices)`\n\n```ts\nremoveRow(rowIndex: number): void\nremoveRows(rowIndices: ReadonlyArray<number>): void\n```\n\nRemove by data-array index (the same index `onCellValueChange` reports).\n\n## Columns\n\n### `addColumn(column, position?)` / `addColumns(columns, position?)`\n\n```ts\naddColumn(column: ColumnDef<TFeatures, TData>, position?: 'left' | 'right' | number): void\naddColumns(columns: ReadonlyArray<ColumnDef<TFeatures, TData>>, position?: 'left' | 'right' | number): void\n```\n\n`position` defaults to `'right'`.\n\n### `removeColumn(columnId)`\n\n```ts\nremoveColumn(columnId: string): void\n```\n\nBy id (or `field` when no id was provided).\n\n## Visibility\n\n### `setColumnVisible(columnId, visible)` / `isColumnVisible(columnId)`\n\n```ts\nsetColumnVisible(columnId: string, visible: boolean): void\nisColumnVisible(columnId: string): boolean\n```\n\nHidden columns stay in the column array but don't render.\n\n## Sort\n\n### `setSort(columnId, direction)`\n\n```ts\nsetSort(columnId: string, direction: 'asc' | 'desc' | null): void\n```\n\nReplaces any existing sort. Pass `null` to clear sort on that column.\nMulti-sort through the API is on the\n[Missing features](../help/missing-features.md) list - the user can\nbuild it themselves with Shift-click on headers.\n\n### `clearSort()`\n\n```ts\nclearSort(): void\n```\n\nClear all sort clauses.\n\n## Group\n\n### `setGroupBy(columnIds)`\n\n```ts\nsetGroupBy(columnIds: ReadonlyArray<string>): void\n```\n\nGroup by zero or more columns. Replaces any existing group config.\n\n## Filter\n\n### `setFilter(columnId, filter)`\n\n```ts\nsetFilter(\n columnId: string,\n filter: { operator: SvGridFilterOperator; value?: string } | null,\n): void\n```\n\nWhere `SvGridFilterOperator` is:\n\n```ts\ntype SvGridFilterOperator =\n | 'contains' | 'equals' | 'startsWith'\n | 'greaterThan' | 'lessThan' | 'isBlank'\n```\n\nPass `null` to clear.\n\n### `clearFilter(columnId)`\n\n```ts\nclearFilter(columnId: string): void\n```\n\nClear a single column's filter. (A `clearAllFilters()` helper is on\nthe [Missing features](../help/missing-features.md) list.)\n\n## Data snapshot\n\n### `getData()`\n\n```ts\ngetData(): ReadonlyArray<TData>\n```\n\nSnapshot of the current internal data array - the grid's working\ncopy, which reflects every cell edit and `addRow` / `removeRow` since\nmount.\n\n### `getDisplayedRows()`\n\n```ts\ngetDisplayedRows(): ReadonlyArray<TData>\n```\n\nReturns the rows that are currently **visible** in the grid - after\nfilter, sort, and pagination. Use for `pro.exportData(...)` when you\nwant to export the current view.\n\n## Enterprise extensions\n\nAfter `installEnterprise(api)`, the same object also exposes:\n\n```ts\napi.exportData(opts) // see Enterprise export reference\napi.print(opts)\napi.importData(opts)\napi.ai.filter(...)\napi.ai.smartFill(...)\napi.ai.summarize(...)\napi.ai.classify(...)\napi.pivot.build(config)\napi.pivot.buildFrom(data, config)\n```\n\nSee [Enterprise reference](./enterprise.md).\n"
|
|
7660
|
+
"markdown": "# `SvGridApi` reference\n\nThe imperative API exposed via `<SvGrid onApiReady={(api) => ...}>`.\nUse it for data, column, filter, sort, group, selection, and\nvisibility operations from outside the component.\n\n```ts\nimport type { SvGridApi } from '@svgrid/grid'\n\nlet api = $state<SvGridApi<typeof features, Order> | null>(null)\n```\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onApiReady={(next) => (api = next)}\n/>\n\n<button onclick={() => api?.addRow({ /* ... */ })}>Add row</button>\n```\n\n## Cells\n\n### `getCellValue(rowIndex, columnId)`\n\n```ts\ngetCellValue(rowIndex: number, columnId: string): unknown\n```\n\nRead a cell value from the underlying data. Returns `undefined` when\neither argument doesn't resolve.\n\n### `setCellValue(rowIndex, columnId, value)`\n\n```ts\nsetCellValue(rowIndex: number, columnId: string, value: unknown): void\n```\n\nWrite a cell value through the column's `field`. Triggers a re-render.\nDoes NOT fire `onCellValueChange` - that callback is for **user**\nedits.\n\n## Rows\n\n### `addRow(row, position?)`\n\n```ts\naddRow(row: TData, position?: 'top' | 'bottom' | number): void\n```\n\n`position` defaults to `'bottom'`. A numeric index inserts before that\nindex.\n\n### `addRows(rows, position?)`\n\n```ts\naddRows(rows: ReadonlyArray<TData>, position?: 'top' | 'bottom' | number): void\n```\n\nBatched insert. Cheaper than calling `addRow` in a loop for hundreds\nof rows.\n\n### `removeRow(rowIndex)` / `removeRows(rowIndices)`\n\n```ts\nremoveRow(rowIndex: number): void\nremoveRows(rowIndices: ReadonlyArray<number>): void\n```\n\nRemove by data-array index (the same index `onCellValueChange` reports).\n\n## Columns\n\n### `addColumn(column, position?)` / `addColumns(columns, position?)`\n\n```ts\naddColumn(column: ColumnDef<TFeatures, TData>, position?: 'left' | 'right' | number): void\naddColumns(columns: ReadonlyArray<ColumnDef<TFeatures, TData>>, position?: 'left' | 'right' | number): void\n```\n\n`position` defaults to `'right'`.\n\n### `removeColumn(columnId)`\n\n```ts\nremoveColumn(columnId: string): void\n```\n\nBy id (or `field` when no id was provided).\n\n## Visibility\n\n### `setColumnVisible(columnId, visible)` / `isColumnVisible(columnId)`\n\n```ts\nsetColumnVisible(columnId: string, visible: boolean): void\nisColumnVisible(columnId: string): boolean\n```\n\nHidden columns stay in the column array but don't render.\n\n## Sort\n\n### `setSort(columnId, direction)`\n\n```ts\nsetSort(columnId: string, direction: 'asc' | 'desc' | null): void\n```\n\nReplaces any existing sort. Pass `null` to clear sort on that column.\nMulti-sort through the API is on the\n[Missing features](../help/missing-features.md) list - the user can\nbuild it themselves with Shift-click on headers.\n\n### `clearSort()`\n\n```ts\nclearSort(): void\n```\n\nClear all sort clauses.\n\n## Group\n\n### `setGroupBy(columnIds)`\n\n```ts\nsetGroupBy(columnIds: ReadonlyArray<string>): void\n```\n\nGroup by zero or more columns. Replaces any existing group config.\n\n## Filter\n\n### `setFilter(columnId, filter)`\n\n```ts\nsetFilter(\n columnId: string,\n filter: { operator: SvGridFilterOperator; value?: string } | null,\n): void\n```\n\nWhere `SvGridFilterOperator` is:\n\n```ts\ntype SvGridFilterOperator =\n | 'contains' | 'equals' | 'startsWith'\n | 'greaterThan' | 'lessThan' | 'isBlank'\n```\n\nPass `null` to clear.\n\n### `clearFilter(columnId)`\n\n```ts\nclearFilter(columnId: string): void\n```\n\nClear a single column's filter. (A `clearAllFilters()` helper is on\nthe [Missing features](../help/missing-features.md) list.)\n\n## Data snapshot\n\n### `getData()`\n\n```ts\ngetData(): ReadonlyArray<TData>\n```\n\nSnapshot of the current internal data array - the grid's working\ncopy, which reflects every cell edit and `addRow` / `removeRow` since\nmount.\n\n### `getDisplayedRows()`\n\n```ts\ngetDisplayedRows(): ReadonlyArray<TData>\n```\n\nReturns the rows that are currently **visible** in the grid - after\nfilter, sort, and pagination. Use for `pro.exportData(...)` when you\nwant to export the current view.\n\n### `getRowPosition(rowId)`\n\n```ts\ngetRowPosition(rowId: string): number | null\n```\n\nWhere a row sits in the filtered, sorted rows across every page (group\nbanners included, as paging counts them), or `null` when a filter hides\nit. With client paging, `Math.floor(position / pageSize)` is its page:\n\n```ts\nconst position = api.getRowPosition('ord-1042')\nif (position !== null) {\n const { pageSize } = api.getPageInfo()\n api.setPage(Math.floor(position / pageSize))\n api.scrollToRow(position % pageSize)\n}\n```\n\n## Enterprise extensions\n\nAfter `installEnterprise(api)`, the same object also exposes:\n\n```ts\napi.exportData(opts) // see Enterprise export reference\napi.print(opts)\napi.importData(opts)\napi.ai.filter(...)\napi.ai.smartFill(...)\napi.ai.summarize(...)\napi.ai.classify(...)\napi.pivot.build(config)\napi.pivot.buildFrom(data, config)\n```\n\nSee [Enterprise reference](./enterprise.md).\n"
|
|
7630
7661
|
},
|
|
7631
7662
|
{
|
|
7632
7663
|
"slug": "reference/auto/index",
|
|
@@ -8354,8 +8385,8 @@ export const apiReference = {
|
|
|
8354
8385
|
]
|
|
8355
8386
|
};
|
|
8356
8387
|
export const apiSurface = {
|
|
8357
|
-
"gridVersion": "3.0.
|
|
8358
|
-
"enterpriseVersion": "3.1.
|
|
8388
|
+
"gridVersion": "3.0.22",
|
|
8389
|
+
"enterpriseVersion": "3.1.23",
|
|
8359
8390
|
"grid": {
|
|
8360
8391
|
"values": [
|
|
8361
8392
|
"ALL_FILTER_OPERATORS",
|
|
@@ -10704,6 +10735,7 @@ export const apiSurface = {
|
|
|
10704
10735
|
"@svgrid/enterprise/license",
|
|
10705
10736
|
"@svgrid/enterprise/pivot",
|
|
10706
10737
|
"@svgrid/enterprise/print",
|
|
10738
|
+
"@svgrid/enterprise/review",
|
|
10707
10739
|
"@svgrid/enterprise/server",
|
|
10708
10740
|
"@svgrid/enterprise/sheet",
|
|
10709
10741
|
"@svgrid/enterprise/studio",
|
|
@@ -11931,6 +11963,7 @@ export const apiSurface = {
|
|
|
11931
11963
|
"getPageInfo",
|
|
11932
11964
|
"getRowHeight",
|
|
11933
11965
|
"getRowId",
|
|
11966
|
+
"getRowPosition",
|
|
11934
11967
|
"getSavedCharts",
|
|
11935
11968
|
"getSelected",
|
|
11936
11969
|
"getSelectedLast",
|
package/dist/preview.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare const UI_MIME_TYPE = "text/html;profile=mcp-app";
|
|
|
8
8
|
* start failing in a way nobody is watching for. `tools/mcp-tools.test.ts` checks these
|
|
9
9
|
* against the workspace so they cannot quietly rot either.
|
|
10
10
|
*/
|
|
11
|
-
export declare const PREVIEW_GRID_WC_VERSION = "3.0.
|
|
11
|
+
export declare const PREVIEW_GRID_WC_VERSION = "3.0.30";
|
|
12
12
|
export declare function previewResource(): {
|
|
13
13
|
uri: string;
|
|
14
14
|
name: string;
|
package/dist/preview.js
CHANGED
|
@@ -27,7 +27,7 @@ export const UI_MIME_TYPE = 'text/html;profile=mcp-app';
|
|
|
27
27
|
* start failing in a way nobody is watching for. `tools/mcp-tools.test.ts` checks these
|
|
28
28
|
* against the workspace so they cannot quietly rot either.
|
|
29
29
|
*/
|
|
30
|
-
export const PREVIEW_GRID_WC_VERSION = '3.0.
|
|
30
|
+
export const PREVIEW_GRID_WC_VERSION = '3.0.30';
|
|
31
31
|
const EXT_APPS_VERSION = '1.7.5';
|
|
32
32
|
const CDN = 'https://cdn.jsdelivr.net/npm';
|
|
33
33
|
/**
|
package/dist/validate.d.ts
CHANGED
|
@@ -111,6 +111,16 @@ export declare function blankOut(src: string): string;
|
|
|
111
111
|
* small relative to the word so "foo" does not "resolve" to "bar".
|
|
112
112
|
*/
|
|
113
113
|
export declare function nearest(word: string, candidates: readonly string[]): string | null;
|
|
114
|
+
/**
|
|
115
|
+
* Known names about the same thing as `word`, best first, for when `nearest`
|
|
116
|
+
* found no spelling to offer. `detailRenderer` is no typo of anything, but it
|
|
117
|
+
* shares "detail" with `renderDetailRow` and `isDetailRow`, and that short list
|
|
118
|
+
* is what lets a model pick instead of guessing again.
|
|
119
|
+
*
|
|
120
|
+
* Advice only - never a rename. A shared word must be one that few candidates
|
|
121
|
+
* carry, so `rowFoo` does not come back with every prop that starts with `row`.
|
|
122
|
+
*/
|
|
123
|
+
export declare function related(word: string, candidates: readonly string[], limit?: number): string[];
|
|
114
124
|
/** Run every static rule. Exported for tests and for hosts that skip compiling. */
|
|
115
125
|
/**
|
|
116
126
|
* Apply the mechanically-safe renames to the source, returning the corrected
|
package/dist/validate.js
CHANGED
|
@@ -118,6 +118,12 @@ export function nearest(word, candidates) {
|
|
|
118
118
|
// same idea, so the comparison also runs with the verb prefix removed.
|
|
119
119
|
const core = (s) => s.replace(/^(?:get|set|create|make|build|use|enable|with)/i, '');
|
|
120
120
|
const lowerCore = core(lower);
|
|
121
|
+
// `rowHeightAuto` for `autoRowHeight`: the same words in another order is as
|
|
122
|
+
// certain as a typo, and edit distance cannot see it.
|
|
123
|
+
const order = (s) => words(s).sort().join(' ');
|
|
124
|
+
const sameWords = candidates.filter((c) => c !== word && order(c) === order(word));
|
|
125
|
+
if (sameWords.length === 1)
|
|
126
|
+
return sameWords[0];
|
|
121
127
|
const budget = word.length <= 4 ? 1 : word.length <= 8 ? 2 : 3;
|
|
122
128
|
let best = null;
|
|
123
129
|
let bestScore = Infinity;
|
|
@@ -129,8 +135,103 @@ export function nearest(word, candidates) {
|
|
|
129
135
|
best = c;
|
|
130
136
|
}
|
|
131
137
|
}
|
|
138
|
+
// Three edits turn `onRowSelected` into `onRowsDelete`, the opposite. When
|
|
139
|
+
// another name shares more of the words, the spelling match is a
|
|
140
|
+
// coincidence, and since a guess here is applied as a rename, offer none.
|
|
141
|
+
if (best) {
|
|
142
|
+
const top = related(word, candidates, 1)[0];
|
|
143
|
+
if (top && top !== best && sharedStems(word, top) > sharedStems(word, best))
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
132
146
|
return best;
|
|
133
147
|
}
|
|
148
|
+
/** `onRowSelectionChange` -> `on row selection change`. */
|
|
149
|
+
function words(name) {
|
|
150
|
+
return name
|
|
151
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
152
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
|
|
153
|
+
.toLowerCase()
|
|
154
|
+
.split(/[^a-z0-9]+/)
|
|
155
|
+
.filter(Boolean);
|
|
156
|
+
}
|
|
157
|
+
// Words that say how a prop is switched on, not what it is about.
|
|
158
|
+
const FILLER_WORDS = new Set(['enable', 'show', 'allow', 'use', 'is', 'has', 'get', 'set', 'with']);
|
|
159
|
+
const STEM_SUFFIXES = ['ations', 'ation', 'ings', 'ing', 'able', 'ion', 'ed', 'es', 's'];
|
|
160
|
+
const STEM_ALIASES = { pagin: 'pag', paginat: 'pag', renderer: 'render' };
|
|
161
|
+
/** Crude stem, so `sorting`, `sortable` and `sorted` all read as `sort`. */
|
|
162
|
+
function stem(word) {
|
|
163
|
+
let w = STEM_ALIASES[word] ?? word;
|
|
164
|
+
for (const s of STEM_SUFFIXES) {
|
|
165
|
+
if (w.length - s.length >= 3 && w.endsWith(s)) {
|
|
166
|
+
w = w.slice(0, -s.length);
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (w.length > 3 && w.endsWith('e'))
|
|
171
|
+
w = w.slice(0, -1);
|
|
172
|
+
return STEM_ALIASES[w] ?? w;
|
|
173
|
+
}
|
|
174
|
+
const stems = (name) => new Set(words(name).filter((w) => !FILLER_WORDS.has(w)).map(stem));
|
|
175
|
+
function sharedStems(a, b) {
|
|
176
|
+
const other = stems(b);
|
|
177
|
+
let n = 0;
|
|
178
|
+
for (const w of stems(a))
|
|
179
|
+
if (other.has(w))
|
|
180
|
+
n++;
|
|
181
|
+
return n;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Known names about the same thing as `word`, best first, for when `nearest`
|
|
185
|
+
* found no spelling to offer. `detailRenderer` is no typo of anything, but it
|
|
186
|
+
* shares "detail" with `renderDetailRow` and `isDetailRow`, and that short list
|
|
187
|
+
* is what lets a model pick instead of guessing again.
|
|
188
|
+
*
|
|
189
|
+
* Advice only - never a rename. A shared word must be one that few candidates
|
|
190
|
+
* carry, so `rowFoo` does not come back with every prop that starts with `row`.
|
|
191
|
+
*/
|
|
192
|
+
export function related(word, candidates, limit = 5) {
|
|
193
|
+
const mine = stems(word);
|
|
194
|
+
if (!mine.size)
|
|
195
|
+
return [];
|
|
196
|
+
const sets = candidates.map((c) => ({ name: c, stems: stems(c) }));
|
|
197
|
+
const df = new Map();
|
|
198
|
+
for (const { stems: s } of sets)
|
|
199
|
+
for (const w of s)
|
|
200
|
+
df.set(w, (df.get(w) ?? 0) + 1);
|
|
201
|
+
const distinctive = Math.max(2, Math.floor(candidates.length / 10));
|
|
202
|
+
const scored = [];
|
|
203
|
+
for (const { name, stems: s } of sets) {
|
|
204
|
+
if (name === word)
|
|
205
|
+
continue;
|
|
206
|
+
let score = 0;
|
|
207
|
+
let sharp = false;
|
|
208
|
+
for (const w of mine) {
|
|
209
|
+
if (!s.has(w))
|
|
210
|
+
continue;
|
|
211
|
+
const n = df.get(w);
|
|
212
|
+
score += Math.log(1 + candidates.length / n);
|
|
213
|
+
if (n <= distinctive)
|
|
214
|
+
sharp = true;
|
|
215
|
+
}
|
|
216
|
+
if (!sharp)
|
|
217
|
+
continue;
|
|
218
|
+
// Of two names sharing the same words, the one with fewer others is closer.
|
|
219
|
+
scored.push({ name, score: score - 0.1 * (s.size - 1) });
|
|
220
|
+
}
|
|
221
|
+
return scored
|
|
222
|
+
.sort((a, b) => b.score - a.score || a.name.length - b.name.length)
|
|
223
|
+
.slice(0, limit)
|
|
224
|
+
.map((s) => s.name);
|
|
225
|
+
}
|
|
226
|
+
/** "`a`, `b` (boolean)" - a member's type rides along when it is short enough to help. */
|
|
227
|
+
function listMembers(names, members) {
|
|
228
|
+
return names
|
|
229
|
+
.map((n) => {
|
|
230
|
+
const type = members?.find((m) => m.name === n)?.type.replace(/\s+/g, ' ');
|
|
231
|
+
return type && type.length <= 40 ? `\`${n}\` (${type})` : `\`${n}\``;
|
|
232
|
+
})
|
|
233
|
+
.join(', ');
|
|
234
|
+
}
|
|
134
235
|
/** Index of the bracket matching the one at `open`, or -1. */
|
|
135
236
|
function matchBracket(src, open) {
|
|
136
237
|
const pairs = { '{': '}', '[': ']', '(': ')' };
|
|
@@ -549,6 +650,7 @@ function checkGridProps(ctx) {
|
|
|
549
650
|
continue;
|
|
550
651
|
}
|
|
551
652
|
const guess = nearest(name, known);
|
|
653
|
+
const near = guess ? [] : related(name, known);
|
|
552
654
|
push(ctx, {
|
|
553
655
|
rule: 'svgrid/unknown-prop',
|
|
554
656
|
severity: 'error',
|
|
@@ -556,7 +658,9 @@ function checkGridProps(ctx) {
|
|
|
556
658
|
message: `\`${name}\` is not a prop of <SvGrid> in @svgrid/grid@${surface.gridVersion}.`,
|
|
557
659
|
fix: guess
|
|
558
660
|
? `Did you mean \`${guess}\`?`
|
|
559
|
-
:
|
|
661
|
+
: near.length
|
|
662
|
+
? `Related props: ${listMembers(near, surface.props)}. If none fits, call svgrid_search with what the prop should do.`
|
|
663
|
+
: 'Call svgrid_search with the prop name, or read the reference/SvGrid doc for the prop list.',
|
|
560
664
|
rename: guess ? { from: name, to: guess } : undefined,
|
|
561
665
|
see: 'reference/SvGrid',
|
|
562
666
|
});
|
|
@@ -697,12 +801,15 @@ function checkColumns(ctx) {
|
|
|
697
801
|
continue;
|
|
698
802
|
}
|
|
699
803
|
const guess = nearest(key, known);
|
|
804
|
+
const near = guess ? [] : related(key, known, 3);
|
|
700
805
|
push(ctx, {
|
|
701
806
|
rule: 'svgrid/unknown-column-key',
|
|
702
807
|
severity: 'error',
|
|
703
808
|
line,
|
|
704
809
|
message: `\`${key}\` is not a key of ColumnDef in @svgrid/grid@${surface.gridVersion}.`,
|
|
705
|
-
fix: guess
|
|
810
|
+
fix: guess
|
|
811
|
+
? `Did you mean \`${guess}\`?`
|
|
812
|
+
: `${near.length ? `Related: ${listMembers(near, surface.columnDef)}. ` : ''}Valid keys: ${known.join(', ')}.`,
|
|
706
813
|
see: 'help/columns/column-definitions',
|
|
707
814
|
});
|
|
708
815
|
}
|
|
@@ -920,12 +1027,17 @@ function checkEnterpriseUsage(ctx) {
|
|
|
920
1027
|
const hint = API_METHOD_HINTS[method];
|
|
921
1028
|
const spelling = nearest(method, all);
|
|
922
1029
|
const guess = hint ?? spelling;
|
|
1030
|
+
const near = guess ? [] : related(method, all);
|
|
923
1031
|
push(ctx, {
|
|
924
1032
|
rule: 'svgrid/unknown-api-method',
|
|
925
1033
|
severity: 'error',
|
|
926
1034
|
line,
|
|
927
1035
|
message: `The grid API has no \`${method}()\` in @svgrid/grid@${ctx.surface.gridVersion}.`,
|
|
928
|
-
fix: guess
|
|
1036
|
+
fix: guess
|
|
1037
|
+
? `Use \`${guess}\`.`
|
|
1038
|
+
: near.length
|
|
1039
|
+
? `Related methods: ${listMembers(near)}. If none fits, call svgrid_get with ref:"api" for the api surface.`
|
|
1040
|
+
: 'Call svgrid_get with ref:"api" for the api surface.',
|
|
929
1041
|
// Only the spelling guess is a bare identifier. An API_METHOD_HINTS
|
|
930
1042
|
// value is a call expression - `exportData({ format: "xlsx" })` - and
|
|
931
1043
|
// substituting that for an identifier would emit `api.exportData({...})(...)`.
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"type": "commercial",
|
|
6
6
|
"url": "https://svgrid.com/pricing"
|
|
7
7
|
},
|
|
8
|
-
"version": "3.0.
|
|
8
|
+
"version": "3.0.30",
|
|
9
9
|
"description": "Model Context Protocol server for SvGrid, the Svelte 5 data grid: checks the code your AI writes against the real API surface, plus version-pinned docs, API reference and 373 demo sources.",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"author": "jQWidgets <sales@jqwidgets.com>",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"zod": "^3.23.8"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
|
-
"@svgrid/enterprise": "^3.1.
|
|
38
|
+
"@svgrid/enterprise": "^3.1.23"
|
|
39
39
|
},
|
|
40
40
|
"peerDependenciesMeta": {
|
|
41
41
|
"@svgrid/enterprise": {
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"@types/node": "^22.10.7",
|
|
47
47
|
"typescript": "6.0.3",
|
|
48
|
-
"@svgrid/enterprise": "^3.1.
|
|
48
|
+
"@svgrid/enterprise": "^3.1.23"
|
|
49
49
|
},
|
|
50
50
|
"engines": {
|
|
51
51
|
"node": ">=18"
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "com.svgrid/svgrid",
|
|
4
4
|
"title": "SvGrid",
|
|
5
5
|
"description": "Checks AI-written SvGrid code against the real API, plus version-pinned Svelte 5 grid docs.",
|
|
6
|
-
"version": "3.0.
|
|
6
|
+
"version": "3.0.30",
|
|
7
7
|
"websiteUrl": "https://svgrid.com/docs/help/mcp-server/",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/sv-grid/sv-grid",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"registryType": "npm",
|
|
16
16
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
17
17
|
"identifier": "@svgrid/mcp",
|
|
18
|
-
"version": "3.0.
|
|
18
|
+
"version": "3.0.30",
|
|
19
19
|
"runtimeHint": "npx",
|
|
20
20
|
"transport": {
|
|
21
21
|
"type": "stdio"
|