@svgrid/mcp 3.0.28 → 3.0.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/data.js +29 -4
- package/dist/preview.d.ts +1 -1
- package/dist/preview.js +1 -1
- package/package.json +3 -3
- package/server.json +2 -2
package/dist/data.js
CHANGED
|
@@ -4055,6 +4055,22 @@ 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": "704-agent-review-desk",
|
|
4068
|
+
"path": "examples/src/demos/704-agent-review-desk.svelte",
|
|
4069
|
+
"title": "Agent Review Desk",
|
|
4070
|
+
"category": "App Templates",
|
|
4071
|
+
"blurb": "704. Agent review desk (app template) A CRM agent cleans a customer table, and nothing it does lands until a person says so. The agent works through the same tools a real model would",
|
|
4072
|
+
"source": "<script lang=\"ts\">\n /**\n * 704. Agent review desk (app template)\n * -------------------------------------\n * A CRM agent cleans a customer table, and nothing it does lands until a\n * person says so. The agent works through the same tools a real model would\n * get from createGridTools:\n *\n * grid_describe what the table holds and what it may edit\n * grid_query_rows the rows, with their row ids\n * grid_propose_edits edits, each with a reason and a confidence\n *\n * Every step it takes shows in the strip under the header with the tool\n * call it made. Its edits arrive as proposals: the cell shows the proposed\n * value with the old one struck through, and the review panel groups them\n * by what they do, the risky groups first. Two of its region guesses are\n * wrong, and it says it is unsure of them.\n *\n * Accept or reject a group; one Ctrl+Z in the grid undoes it. Edit a cell\n * before accepting its proposal and your value stays. The Log tab lists\n * every decision (onDecision, where an app writes its audit trail). Revert\n * run proposes undoing what was accepted (revertSet); Copy for approver\n * puts the review on the clipboard as JSON for someone else to merge.\n *\n * The agent is a script standing in for a model, so the demo runs offline.\n *\n * Grid, buttons: @svgrid/grid. Change review, agent tools: @svgrid/enterprise.\n */\n import { onMount } from 'svelte'\n import { SvGrid, SvButton, renderSnippet, type GridColumns, type SvGridApi } from '@svgrid/grid'\n import {\n createReview,\n createGridTools,\n SvReviewPanel,\n type GridTool,\n type ReviewDecision,\n } from '@svgrid/enterprise/review'\n\n type Customer = {\n id: string\n company: string\n contact: string\n email: string\n phone: string\n country: string\n region: string\n segment: string\n arr: number\n }\n\n // ---- data -------------------------------------------------------------\n\n const NAMES = ['Acme Robotics', 'Bluefin Labs', 'Cobalt Freight', 'Driftwood Media', 'Ember Analytics', 'Fjord Outdoor',\n 'Granite Health', 'Harbor Logistics', 'Ion Energy', 'Juniper Foods', 'Kestrel Air', 'Lumen Optics', 'Mosaic Retail',\n 'Nimbus Cloud', 'Orchid Beauty', 'Pinecone Games', 'Quarry Steel', 'Radiant Solar', 'Saffron Spices', 'Tundra Gear',\n 'Umbra Security', 'Vertex Bio', 'Willow Insurance', 'Xenon Motors', 'Yarrow Pharma', 'Zephyr Travel', 'Atlas Mapping',\n 'Beacon Schools', 'Cypress Legal', 'Delta Dental', 'Echo Audio', 'Falcon Drones', 'Garnet Jewels', 'Helix Genomics',\n 'Indigo Textiles', 'Jade Ceramics']\n const PEOPLE = ['maria lopez', 'wei zhang', 'aisha bello', 'tom fischer', 'emma dubois', 'liam walsh', 'sofia ricci',\n 'noah park', 'yuki sato', 'omar nasser', 'lena berg', 'ravi iyer']\n const COUNTRIES = ['United States', 'usa', 'Germany', 'U.S.', 'Japan', 'US', 'United Kingdom', 'United States of America',\n 'Brazil', 'France', 'U.S.A.', 'India']\n const US = new Set(['usa', 'U.S.', 'US', 'United States of America', 'U.S.A.'])\n const REGION: Record<string, string> = { 'United States': 'AMER', Brazil: 'AMER', Germany: 'EMEA', 'United Kingdom': 'EMEA', France: 'EMEA', Japan: 'APAC', India: 'APAC' }\n const titleCase = (s: string) => s.replace(/\\b\\p{Ll}/gu, (c) => c.toUpperCase())\n\n function seed(): Customer[] {\n return NAMES.map((name, i) => {\n const person = PEOPLE[i % PEOPLE.length]!\n const country = COUNTRIES[i % COUNTRIES.length]!\n const domain = name.split(' ')[0]!.toLowerCase()\n const [a, b, c] = [200 + ((i * 37) % 700), 100 + ((i * 53) % 800), 1000 + ((i * 271) % 9000)]\n const arr = (18 + ((i * 47) % 160)) * 1000\n return {\n id: `cus-${1001 + i}`,\n company: i % 4 === 0 ? `${name} ` : i % 9 === 2 ? ` ${name}` : name,\n contact: i % 3 === 0 ? person.toUpperCase() : titleCase(person),\n email: i % 2 === 0 ? `${titleCase(person).replace(' ', '.')}@${titleCase(domain)}.COM` : `${person.replace(' ', '.')}@${domain}.com`,\n phone: i % 5 === 4 ? `${a}-${b}-${c}` : i % 3 === 1 ? `${a}.${b}.${c}` : `(${a}) ${b}-${c}`,\n country,\n region: i % 4 === 1 ? '' : REGION[US.has(country) ? 'United States' : country] ?? '',\n segment: '',\n // Seven accounts came over from the old billing system in cents.\n arr: i % 5 === 2 ? arr * 100 : arr,\n }\n })\n }\n\n let rows = $state(seed())\n let api = $state<SvGridApi<any, Customer> | null>(null)\n\n // ---- review -------------------------------------------------------------\n\n type LogEntry = { id: number; at: number; text: string; tone: 'accept' | 'reject' | 'undo' }\n let log = $state<LogEntry[]>([])\n let logSeq = 0\n const FIELD_LABEL: Record<string, string> = { company: 'Company', contact: 'Contact', email: 'Email', phone: 'Phone', country: 'Country', region: 'Region', segment: 'Segment', arr: 'ARR' }\n\n function describeDecision(d: ReviewDecision): LogEntry {\n const fields = [...new Set(d.proposals.map((p) => FIELD_LABEL[p.field] ?? p.field))].join(', ')\n const n = d.proposals.length\n const what = `${n} ${n === 1 ? 'change' : 'changes'} to ${fields}`\n const text =\n d.action === 'accept' ? `Accepted ${what}`\n : d.action === 'reject' ? `Rejected ${what}`\n : d.action === 'undo' ? `Undid the ${d.of} of ${what}`\n : `Redid the ${d.of} of ${what}`\n return { id: ++logSeq, at: d.at, text, tone: d.action === 'accept' || (d.action === 'redo' && d.of === 'accept') ? 'accept' : d.action === 'reject' ? 'reject' : 'undo' }\n }\n\n const review = createReview<Customer>({\n api: () => api,\n setRows: (next) => (rows = next),\n user: 'You',\n onDecision: (d) => (log = [describeDecision(d), ...log]),\n })\n\n const AGENT = { kind: 'agent' as const, id: 'crm-agent', label: 'CRM agent' }\n const tools = createGridTools({\n review,\n api: () => api,\n source: AGENT,\n fields: ['company', 'contact', 'email', 'phone', 'country', 'region', 'segment', 'arr'],\n })\n const tool = (name: string) => tools.find((t) => t.name === name) as GridTool\n\n // ---- the agent --------------------------------------------------------\n\n type Step = { id: number; title: string; call: string; result: string; state: 'running' | 'done' }\n let steps = $state<Step[]>([])\n const SHORT: Record<string, string> = {\n 'Read the customer table': 'Read the table',\n 'Trim stray spaces in company names': 'Trim spaces',\n 'Put contact names in title case': 'Title-case names',\n 'Lower-case email addresses': 'Lower-case emails',\n 'Use one phone format': 'One phone format',\n 'Map country spellings to one name': 'Map countries',\n 'Fill missing regions': 'Fill regions',\n 'Convert ARR booked in cents': 'ARR from cents',\n 'Tag each account with a segment': 'Tag segments',\n }\n // The newest step stays in view as the strip grows.\n let stepsEl = $state<HTMLOListElement | null>(null)\n $effect(() => {\n void steps.length\n queueMicrotask(() => stepsEl?.scrollTo({ left: stepsEl.scrollWidth, behavior: 'smooth' }))\n })\n let agentState = $state<'idle' | 'running' | 'done'>('idle')\n let runToken = 0\n\n const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n type Edit = { rowId: string; field: string; value: unknown; reason?: string; confidence?: number }\n\n async function step(title: string, call: string, work: () => Promise<string>, token: number) {\n if (token !== runToken) return false\n const s: Step = { id: steps.length + 1, title, call, result: '', state: 'running' }\n steps = [...steps, s]\n await sleep(650)\n if (token !== runToken) return false\n const result = await work()\n steps = steps.map((x) => (x.id === s.id ? { ...x, result, state: 'done' } : x))\n return true\n }\n\n async function propose(title: string, edits: Edit[]) {\n const out = (await tool('grid_propose_edits').execute({ title, edits })) as { proposed: number }\n return `${out.proposed} proposed`\n }\n\n async function runAgent() {\n const token = ++runToken\n steps = []\n agentState = 'running'\n let table: Customer[] = []\n const ok = await step('Read the customer table', 'grid_describe() · grid_query_rows()', async () => {\n const d = (await tool('grid_describe').execute({})) as { rowCount: number; columns: unknown[] }\n table = ((await tool('grid_query_rows').execute({})) as { rows: Array<Customer & { rowId: string }> }).rows.map((r) => ({ ...r, id: r.rowId }))\n return `${d.rowCount} rows, ${d.columns.length} columns`\n }, token)\n if (!ok) return\n const each = (fn: (r: Customer) => Edit | null) => table.map(fn).filter((e): e is Edit => e !== null)\n\n const plan: Array<[string, string, () => Edit[]]> = [\n ['Trim stray spaces in company names', 'company', () =>\n each((r) => (r.company !== r.company.trim() ? { rowId: r.id, field: 'company', value: r.company.trim() } : null))],\n ['Put contact names in title case', 'contact', () =>\n each((r) => (r.contact === r.contact.toUpperCase() ? { rowId: r.id, field: 'contact', value: titleCase(r.contact.toLowerCase()) } : null))],\n ['Lower-case email addresses', 'email', () =>\n each((r) => (r.email !== r.email.toLowerCase() ? { rowId: r.id, field: 'email', value: r.email.toLowerCase() } : null))],\n ['Use one phone format', 'phone', () =>\n each((r) => {\n const d = r.phone.replace(/\\D/g, '')\n const v = `${d.slice(0, 3)}-${d.slice(3, 6)}-${d.slice(6)}`\n return v !== r.phone ? { rowId: r.id, field: 'phone', value: v } : null\n })],\n ['Map country spellings to one name', 'country', () =>\n each((r) => (US.has(r.country) ? { rowId: r.id, field: 'country', value: 'United States', reason: `\"${r.country}\" is the United States` } : null))],\n ['Fill missing regions', 'region', () =>\n each((r) => {\n if (r.region) return null\n const country = US.has(r.country) ? 'United States' : r.country\n // Two guesses come from the company name, and the agent says so.\n if (r.id === 'cus-1006') return { rowId: r.id, field: 'region', value: 'APAC', confidence: 0.38, reason: 'guessed from the company name' }\n if (r.id === 'cus-1018') return { rowId: r.id, field: 'region', value: 'EMEA', confidence: 0.44, reason: 'guessed from the company name' }\n return { rowId: r.id, field: 'region', value: REGION[country], confidence: 0.94, reason: `from Country (${country})` }\n })],\n ['Convert ARR booked in cents', 'arr', () =>\n each((r) => (r.arr >= 1_000_000 ? { rowId: r.id, field: 'arr', value: r.arr / 100, reason: 'imported from billing in cents' } : null))],\n ['Tag each account with a segment', 'segment', () =>\n each((r) => {\n const arr = r.arr >= 1_000_000 ? r.arr / 100 : r.arr\n return { rowId: r.id, field: 'segment', value: arr >= 120_000 ? 'Enterprise' : arr >= 60_000 ? 'Mid-market' : 'SMB', confidence: 0.86, reason: 'from ARR bands' }\n })],\n ]\n for (const [title, field, build] of plan) {\n const edits = build()\n const done = await step(title, `grid_propose_edits(${edits.length} × ${field})`, () => propose(title, edits), token)\n if (!done) return\n }\n if (token === runToken) agentState = 'done'\n }\n\n function runAgain() {\n review.clear()\n rows = seed()\n log = []\n void runAgent()\n }\n\n // ---- after review -------------------------------------------------------\n\n let note = $state('')\n function revertRun() {\n let n = 0\n for (const s of review.sets()) {\n if (s.source.id !== AGENT.id) continue\n const set = review.revertSet(s.id)\n if (set) n += set.proposals.length\n }\n note = n ? `${n} reverts proposed: review them like any other change` : 'Nothing accepted to revert'\n }\n async function copyForApprover() {\n const json = JSON.stringify(review.toJSON())\n try {\n await navigator.clipboard.writeText(json)\n note = `Copied ${review.sets().length} sets (${Math.round(json.length / 1024)} KB of JSON) for an approver to merge`\n } catch {\n note = 'The browser blocked the clipboard'\n }\n }\n\n // ---- derived chrome -----------------------------------------------------\n\n const tally = $derived.by(() => {\n const t = { proposed: 0, pending: 0, accepted: 0, rejected: 0 }\n for (const p of review.proposals()) {\n t.proposed++\n if (p.status === 'pending' || p.status === 'conflict') t.pending++\n else if (p.status === 'accepted') t.accepted++\n else if (p.status === 'rejected' || p.status === 'stale') t.rejected++\n }\n return t\n })\n const status = $derived(\n agentState === 'running' ? { text: 'Agent working', tone: 'info' }\n : tally.pending ? { text: 'Waiting for review', tone: 'warning' }\n : tally.proposed ? { text: 'All reviewed', tone: 'success' }\n : { text: 'Idle', tone: 'muted' },\n )\n\n let side = $state<'review' | 'log'>('review')\n let narrow = $state(false)\n let view = $state<'grid' | 'side'>('grid')\n\n onMount(() => {\n const mq = window.matchMedia('(max-width: 860px)')\n const sync = () => (narrow = mq.matches)\n sync()\n mq.addEventListener('change', sync)\n const t = setTimeout(() => void runAgent(), 500)\n return () => {\n mq.removeEventListener('change', sync)\n clearTimeout(t)\n runToken++\n }\n })\n\n const time = (at: number) => new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })\n\n const SEGMENT_TONE: Record<string, string> = { Enterprise: '#7c3aed', 'Mid-market': '#0e7490', SMB: '#64748b' }\n const columns: GridColumns<Customer> = [\n { field: 'company', header: 'Company', width: 180, editable: true },\n { field: 'contact', header: 'Contact', width: 140, editable: true },\n { field: 'email', header: 'Email', width: 220, editable: true },\n { field: 'phone', header: 'Phone', width: 130, editable: true },\n { field: 'country', header: 'Country', width: 150, editable: true },\n { field: 'region', header: 'Region', width: 90, editable: true },\n { field: 'segment', header: 'Segment', width: 120, editable: true, cell: (ctx) => renderSnippet(segmentCell, { value: ctx.getValue() as string }) },\n { field: 'arr', header: 'ARR', width: 120, editable: true, editorType: 'number', format: { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } } },\n ]\n</script>\n\n{#snippet segmentCell({ value }: { value: string })}\n {#if value}<span class=\"ard-seg\" style:--seg={SEGMENT_TONE[value] ?? '#64748b'}>{value}</span>{/if}\n{/snippet}\n\n<div class=\"ard\">\n <header class=\"ard-head\">\n <div class=\"ard-title\">\n <span class=\"ard-logo\" aria-hidden=\"true\">\n <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\"><path d=\"M4 6h16M4 12h10M4 18h7\" /><path d=\"M16 16l2 2 4-4\" /></svg>\n </span>\n <div>\n <h2>Customer master data</h2>\n <p>Northbeam CRM · cleanup by <strong>CRM agent</strong> · {rows.length} accounts</p>\n </div>\n <span class=\"ard-status is-{status.tone}\"><span class=\"ard-dot\" aria-hidden=\"true\"></span>{status.text}</span>\n </div>\n <dl class=\"ard-stats\">\n <div><dt>Proposed</dt><dd>{tally.proposed}</dd></div>\n <div><dt>Pending</dt><dd>{tally.pending}</dd></div>\n <div><dt>Accepted</dt><dd class=\"is-good\">{tally.accepted}</dd></div>\n <div><dt>Rejected</dt><dd>{tally.rejected}</dd></div>\n </dl>\n </header>\n\n <div class=\"ard-agent\" aria-live=\"polite\">\n <ol class=\"ard-steps\" bind:this={stepsEl}>\n {#each steps as s (s.id)}\n <li class=\"ard-step is-{s.state}\" title=\"{s.title}: {s.call}\">\n <span class=\"ard-step-icon\" aria-hidden=\"true\">\n {#if s.state === 'running'}<span class=\"ard-spin\"></span>{:else}<svg viewBox=\"0 0 24 24\" width=\"12\" height=\"12\"><path d=\"M5 12.5l4.5 4.5L19 7.5\" /></svg>{/if}\n </span>\n <span class=\"ard-step-text\">\n <span class=\"ard-step-title\">{SHORT[s.title] ?? s.title}</span>\n <code>{s.call}</code>\n </span>\n {#if s.result}<span class=\"ard-step-result\">{s.result}</span>{/if}\n </li>\n {:else}\n <li class=\"ard-step is-idle\">The agent starts in a moment…</li>\n {/each}\n </ol>\n <div class=\"ard-actions\">\n <SvButton size=\"sm\" variant=\"outline\" disabled={agentState === 'running'} onclick={runAgain}>Run again</SvButton>\n <SvButton size=\"sm\" variant=\"ghost\" disabled={!tally.accepted} onclick={revertRun}>Revert run</SvButton>\n <SvButton size=\"sm\" variant=\"ghost\" disabled={!tally.proposed} onclick={copyForApprover}>Copy for approver</SvButton>\n </div>\n </div>\n {#if note}<p class=\"ard-note\" role=\"status\">{note}</p>{/if}\n\n {#if narrow}\n <div class=\"ard-tabs\" role=\"tablist\" aria-label=\"Show\">\n <button type=\"button\" role=\"tab\" aria-selected={view === 'grid'} onclick={() => (view = 'grid')}>Table</button>\n <button type=\"button\" role=\"tab\" aria-selected={view === 'side'} onclick={() => (view = 'side')}>Review ({tally.pending})</button>\n </div>\n {/if}\n\n <div class=\"ard-body\">\n <div class=\"ard-grid\" class:ard-hidden={narrow && view !== 'grid'}>\n <SvGrid\n data={rows}\n columns={review.columns(columns)}\n getRowId={(r) => r.id}\n conditionalFormats={review.formats}\n editable\n rowHeight={34}\n initialColumnPinning={{ left: ['company'] }}\n containerHeight={narrow ? 300 : 430}\n onApiReady={(a) => (api = a)}\n />\n </div>\n <aside class=\"ard-side\" class:ard-hidden={narrow && view !== 'side'}>\n <div class=\"ard-tabs\" role=\"tablist\" aria-label=\"Side panel\">\n <button type=\"button\" role=\"tab\" aria-selected={side === 'review'} onclick={() => (side = 'review')}>Review</button>\n <button type=\"button\" role=\"tab\" aria-selected={side === 'log'} onclick={() => (side = 'log')}>{log.length ? `Log (${log.length})` : 'Log'}</button>\n </div>\n <div class=\"ard-side-body\">\n {#if side === 'review'}\n <SvReviewPanel {review} title=\"The agent's changes\" />\n {:else}\n <ol class=\"ard-log\">\n {#each log as e (e.id)}\n <li class=\"is-{e.tone}\">\n <span class=\"ard-log-dot\" aria-hidden=\"true\"></span>\n <span class=\"ard-log-text\">{e.text}</span>\n <time>{time(e.at)}</time>\n </li>\n {:else}\n <li class=\"is-empty\">Decisions show up here, newest first, with who made them: what an app writes to its audit trail from onDecision.</li>\n {/each}\n </ol>\n {/if}\n </div>\n </aside>\n </div>\n</div>\n\n<style>\n .ard {\n display: flex;\n flex-direction: column;\n border: 1px solid var(--sg-border, #e5e7eb);\n border-radius: 12px;\n overflow: hidden;\n background: var(--sg-bg, #fff);\n color: var(--sg-fg, #0f172a);\n font-family: var(--sg-font, inherit);\n font-size: 13px;\n }\n .ard-head {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n flex-wrap: wrap;\n padding: 14px 18px;\n border-bottom: 1px solid var(--sg-border, #e5e7eb);\n }\n .ard-title { display: flex; align-items: center; gap: 12px; min-width: 0; flex-wrap: wrap; }\n .ard-logo {\n display: grid;\n place-items: center;\n width: 34px;\n height: 34px;\n flex: none;\n border-radius: 9px;\n background: var(--sg-fg, #0f172a);\n color: var(--sg-bg, #fff);\n }\n .ard-logo svg { fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }\n .ard-title h2 { margin: 0; font-size: 16px; font-weight: 650; letter-spacing: -0.01em; }\n .ard-title p { margin: 2px 0 0; font-size: 12px; color: var(--sg-muted, #64748b); }\n .ard-title strong { color: var(--sg-fg, #0f172a); font-weight: 600; }\n .ard-status {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 3px 10px;\n border-radius: 999px;\n font-size: 11.5px;\n font-weight: 650;\n --tone: var(--sg-muted, #64748b);\n color: color-mix(in srgb, var(--tone) 80%, var(--sg-fg, #0f172a));\n background: color-mix(in srgb, var(--tone) 13%, transparent);\n }\n .ard-status.is-info { --tone: var(--sg-info, #0284c7); }\n .ard-status.is-warning { --tone: var(--sg-warning, #d97706); }\n .ard-status.is-success { --tone: var(--sg-success, #16a34a); }\n .ard-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--tone); }\n .ard-status.is-info .ard-dot { animation: ard-pulse 1.1s ease-in-out infinite; }\n @keyframes ard-pulse { 50% { opacity: 0.3; } }\n\n .ard-stats { display: flex; gap: 22px; margin: 0; }\n .ard-stats div { display: flex; flex-direction: column; align-items: flex-end; }\n .ard-stats dt { font-size: 11px; color: var(--sg-muted, #64748b); }\n .ard-stats dd { margin: 0; font-size: 18px; font-weight: 650; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; }\n .ard-stats dd.is-good { color: var(--sg-success, #16a34a); }\n\n .ard-agent {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 18px;\n border-bottom: 1px solid var(--sg-border, #e5e7eb);\n background: var(--sg-bg-subtle, var(--sg-header-bg, #f8fafc));\n }\n .ard-steps {\n flex: 1;\n min-width: 0;\n display: flex;\n gap: 6px;\n margin: 0;\n padding: 2px 0;\n list-style: none;\n overflow-x: auto;\n scrollbar-width: thin;\n }\n .ard-step {\n display: flex;\n align-items: center;\n gap: 7px;\n flex: none;\n max-width: 260px;\n padding: 5px 10px 5px 7px;\n border: 1px solid var(--sg-border, #e5e7eb);\n border-radius: 8px;\n background: var(--sg-bg, #fff);\n animation: ard-in 0.25s ease-out;\n }\n @keyframes ard-in { from { opacity: 0; transform: translateY(3px); } }\n .ard-step.is-idle { color: var(--sg-muted, #64748b); border-style: dashed; animation: none; }\n .ard-step-icon {\n display: grid;\n place-items: center;\n width: 18px;\n height: 18px;\n flex: none;\n border-radius: 50%;\n color: var(--sg-bg, #fff);\n background: var(--sg-success, #16a34a);\n }\n .ard-step-icon svg { fill: none; stroke: currentColor; stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }\n .ard-step.is-running .ard-step-icon { background: none; }\n .ard-spin {\n width: 14px;\n height: 14px;\n border-radius: 50%;\n border: 2px solid color-mix(in srgb, var(--sg-info, #0284c7) 25%, transparent);\n border-top-color: var(--sg-info, #0284c7);\n animation: ard-rot 0.7s linear infinite;\n }\n @keyframes ard-rot { to { transform: rotate(360deg); } }\n .ard-step-text { display: flex; flex-direction: column; min-width: 0; }\n .ard-step-title { font-size: 12px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .ard-step code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n font-size: 10.5px;\n color: var(--sg-muted, #64748b);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .ard-step-result { font-size: 11.5px; font-weight: 650; font-variant-numeric: tabular-nums; white-space: nowrap; }\n .ard-actions { display: flex; gap: 6px; flex: none; }\n .ard-note { margin: 0; padding: 7px 18px; font-size: 12px; color: var(--sg-muted, #64748b); border-bottom: 1px solid var(--sg-border, #e5e7eb); }\n\n .ard-body { display: grid; grid-template-columns: minmax(0, 1fr) 360px; min-height: 0; }\n .ard-grid { min-width: 0; padding: 12px 0 12px 12px; }\n .ard-side { min-width: 0; display: flex; flex-direction: column; border-left: 1px solid var(--sg-border, #e5e7eb); margin-left: 12px; }\n .ard-side-body { max-height: 430px; overflow: auto; padding: 0 12px 12px; }\n .ard-side-body :global(.sv-review) { border: 0; padding: 0; }\n .ard-tabs { display: flex; gap: 2px; padding: 8px 12px 0; border-bottom: 1px solid var(--sg-border, #e5e7eb); }\n .ard-tabs button {\n padding: 6px 10px;\n margin-bottom: -1px;\n font: inherit;\n font-size: 12.5px;\n font-weight: 550;\n color: var(--sg-muted, #64748b);\n background: none;\n border: 0;\n border-bottom: 2px solid transparent;\n cursor: pointer;\n }\n .ard-tabs button[aria-selected='true'] { color: var(--sg-fg, #0f172a); border-bottom-color: var(--sg-fg, #0f172a); }\n .ard-tabs button:focus-visible { outline: 2px solid var(--sg-focus-ring, var(--sg-accent, #2563eb)); outline-offset: -2px; }\n\n .ard-log { list-style: none; margin: 0; padding: 10px 0 0; display: flex; flex-direction: column; }\n .ard-log li { display: grid; grid-template-columns: 10px minmax(0, 1fr) auto; align-items: baseline; gap: 8px; padding: 7px 0; border-bottom: 1px solid var(--sg-border, #e5e7eb); }\n .ard-log li.is-empty { display: block; color: var(--sg-muted, #64748b); border: 0; line-height: 1.5; }\n .ard-log-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--sg-muted, #94a3b8); transform: translateY(-1px); }\n .ard-log .is-accept .ard-log-dot { background: var(--sg-success, #16a34a); }\n .ard-log .is-reject .ard-log-dot { background: var(--sg-danger, #dc2626); }\n .ard-log time { font-size: 11px; color: var(--sg-muted, #64748b); font-variant-numeric: tabular-nums; }\n\n /* Data palette: segment pills carry their own colours. */\n .ard-seg {\n display: inline-block;\n padding: 1px 8px;\n border-radius: 999px;\n font-size: 11.5px;\n font-weight: 600;\n color: var(--seg);\n background: color-mix(in srgb, var(--seg) 12%, transparent);\n }\n .ard-hidden { display: none; }\n\n @media (max-width: 860px) {\n .ard-head { padding: 12px 14px; gap: 10px; }\n .ard-logo { display: none; }\n .ard-stats { gap: 14px; }\n .ard-stats dd { font-size: 15px; }\n .ard-side-body { max-height: 340px; }\n .ard-agent { flex-direction: column; align-items: stretch; padding: 10px 14px; }\n .ard-body { grid-template-columns: minmax(0, 1fr); }\n .ard-grid { padding: 10px; }\n .ard-side { margin-left: 0; border-left: 0; }\n }\n @media (prefers-reduced-motion: reduce) {\n .ard-step, .ard-spin, .ard-status.is-info .ard-dot { animation: none; }\n }\n</style>\n"
|
|
4073
|
+
},
|
|
4058
4074
|
{
|
|
4059
4075
|
"id": "71-submit-validation",
|
|
4060
4076
|
"path": "examples/src/demos/71-submit-validation.svelte",
|
|
@@ -5316,7 +5332,7 @@ export const docs = [
|
|
|
5316
5332
|
"path": "docs/help/columns/column-spanning.md",
|
|
5317
5333
|
"title": "Column & row spanning (merged cells)",
|
|
5318
5334
|
"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"
|
|
5335
|
+
"markdown": "# Column & row spanning (merged cells)\n\nSpanning lets a single body cell cover **multiple columns** and/or **rows** -\nmerged report headers, grouped labels, financial statements. SvGrid does this\nwith a real `colspan` / `rowspan` merge engine; there are three ways to drive\nit, and the first is the one to reach for on a new grid.\n\n<div data-docs-demo=\"170-cell-merging\" data-height=\"480\"></div>\n\n## 0. The `mergedCells` prop (the renderer's own)\n\nThe grid draws merges itself from a list of origins with their spans, in\ndisplay indices:\n\n```svelte\n<SvGrid\n {data} {columns}\n mergedCells={[\n { rowIndex: 0, colIndex: 0, rowSpan: 1, colSpan: 4 }, // a title across A1:D1\n { rowIndex: 3, colIndex: 1, rowSpan: 3, colSpan: 1 }, // B4:B6 as one cell\n ]}\n/>\n```\n\nThe origin's td takes the `rowspan` / `colspan` and shows the origin's\nvalue; the covered cells are not drawn at all, so there is nothing to\nhide after the fact. A selection grows to whole merges (a merged cell is\none cell), the active cell inside a merge is its origin, the arrow keys\nstep over a merge as one cell, and `api.getMergedCells()` reads the list\nback. Under row virtualization a merge whose origin has scrolled out of\nthe rendered window is drawn from its first rendered row with the rows\nthat remain, and one that crosses the frozen boundary is drawn in two\nparts; nothing needs the covered rows mounted. The grid does not write\ninto covered cells on its own; a consumer that merges keeps them empty or\nmarks them read-only through the column's `editable`, which is what the\nspreadsheet shell's Merge & Center does.\n\nThe merge code loads with the first `mergedCells`, not with every grid, so\ngrids that never merge do not carry it. Until it lands the cells draw\nunmerged: one frame in the browser, and server-rendered HTML shows them\nunmerged until the page hydrates.\n\n## 1. Explicit merges (spreadsheet-style, DOM action)\n\nDeclare exact merges as `MergeSpec[]` and apply them with the\n`spreadsheetLayout` action, which works on a grid you do not own the\nrender of (it edits the table after each paint). Prefer `mergedCells`\nwhere you can. The origin cell `(rowIndex, columnId)` spans\n`colspan` columns right and `rowspan` rows down; covered cells are hidden.\n\n```svelte\n<script lang=\"ts\">\n import { spreadsheetLayout, type MergeSpec } from '@svgrid/grid'\n\n const merges: MergeSpec[] = [\n { rowIndex: 0, columnId: 'A', colspan: 6 }, // title bar\n { rowIndex: 14, columnId: 'A', colspan: 3 }, // \"Total\" label\n ]\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\nSee [demos/170-cell-merging.svelte](../../../examples/src/demos/170-cell-merging.svelte).\n\n## 2. Declarative `colSpan` / `rowSpan` (value-driven)\n\nFor data-driven spanning - \"merge each run of equal values\", \"this cell spans 2\ncolumns when X\" - put `colSpan` / `rowSpan` callbacks on the column and turn\nthem into merges with `spansToMerges`. This runs on the **same** merge engine\nas option 1 (no separate code path).\n\n```svelte\n<script lang=\"ts\">\n // `SpanColumn` rather than `ColumnDef`: `spansToMerges` needs `id` to be\n // present, and on a ColumnDef it is optional.\n import { spreadsheetLayout, spansToMerges, type SpanColumn } from '@svgrid/grid'\n\n const columns: SpanColumn<Row>[] = [\n { id: 'region', field: 'region',\n // merge each vertical run of equal regions\n rowSpan: ({ data, rowIndex }) => {\n if (rowIndex > 0 && rows[rowIndex - 1].region === data.region) return 1 // covered\n let n = 1\n while (rows[rowIndex + n]?.region === data.region) n += 1\n return n\n } },\n { id: 'country', field: 'country' },\n { id: 'amount', field: 'amount' },\n ]\n\n // Recompute after sort / filter - indexes are display-row indexes.\n const merges = $derived(spansToMerges(rows, columns))\n</script>\n\n<div use:spreadsheetLayout={{ merges, columnOrder: columns.map((c) => c.id) }}>\n <SvGrid {data} {columns} />\n</div>\n```\n\n`colSpan` / `rowSpan` receive `CellSpanParams` (`{ data, rowIndex, columnId,\nvalue }`) and return the span count (1 = no span). `spansToMerges` handles\ncovered-cell bookkeeping so overlapping spans never double-emit.\n\n## Virtualization note\n\nThe declarative `rowSpan` and the `spreadsheetLayout` action use real\n`rowspan` and need the covered rows mounted in the render window. For very\nlarge spanning grids on those two, keep spans modest or disable row\nvirtualization (`virtualization={false}`) so the origin cell stays mounted\nwhile its covered rows are on screen. The `mergedCells` prop has no such\nlimit: it clamps every span to the rendered window and continues a merge\nfrom its first rendered row.\n\n## More examples\n\n### Budget report: merged headers\n\nA half-year budget report laid out with merged cells the way Excel lays one out: a title merged across the page, Q1 / Q2 / H1 group headers merged over their months, a Line corner merged down two rows, a notes paragraph merged into one wrapped block. A merge is one cell to the grid: click inside Q1 and the Name Box says B2, Merge & Center lights, the arrows step over it and its column letters are shaded. Unmerge and merge again from the ribbon; Ctrl+Z each step.\n\n<div data-docs-demo=\"463-merged-report-headers\" data-height=\"560\"></div>\n\n## See also\n\n- [Cell merging demo](../../../examples/src/demos/170-cell-merging.svelte)\n- [Row spanning](../rows/row-spanning.md)\n"
|
|
5320
5336
|
},
|
|
5321
5337
|
{
|
|
5322
5338
|
"slug": "help/columns/column-state",
|
|
@@ -5885,6 +5901,13 @@ export const docs = [
|
|
|
5885
5901
|
"section": "Help",
|
|
5886
5902
|
"markdown": "# Recipes / Cookbook\n\nQuick patterns for the questions that come up over and over. Each\nrecipe is paired with a live demo or a minimal snippet that runs\nagainst the shipping library.\n\n## Sort, filter, paginate at the same time\n\nThree of the most-asked features wired together against a 5k-row\ndataset. Click any header to sort, open the filter icon to filter,\nuse the pager at the bottom to walk pages:\n\n<div data-docs-demo=\"02-sort-filter-paginate\" data-height=\"440\"></div>\n\nThe implementation: register all three features in one\n`tableFeatures(...)` call and enable the matching props on `<SvGrid>`.\nSee [Filtering overview](./filtering/overview.md) and\n[Row sorting](./rows/row-sorting.md).\n\n## Select rows + copy / paste a range\n\nClick + drag selects a rectangular cell range; Ctrl/Cmd+C copies as\nTSV; pasting back from Excel writes through the same cell-write\npipeline as inline edit:\n\n<div data-docs-demo=\"04-selection-copy-paste\" data-height=\"440\"></div>\n\nThe pattern: enable `enableCellSelection={true}` and let the grid\nhandle the keyboard + paste plumbing. Cell writes go through\n`onCellValueChange` so your validator runs on every pasted value.\n\n## Bulk actions toolbar\n\nThe Gmail / Linear pattern: tick row checkboxes, a sticky toolbar\nreveals \"Mark / Delete / Copy as TSV\":\n\n<div data-docs-demo=\"23-bulk-actions\" data-height=\"440\"></div>\n\nThe trick: subscribe to `onRowSelectionChange` and render your\ntoolbar whenever the count is > 0. The grid doesn't ship a bulk-action\ncomponent on purpose - your design system's button + toast UI is\nbetter than anything we could embed.\n\n## Cascade editing (formula-like dependencies)\n\nEditing qty / price cascades into line totals + a summary card:\n\n<div data-docs-demo=\"18-cascade-editing\" data-height=\"440\"></div>\n\nIn `onCellValueChange`, after writing the cell, recompute the dependent\ncells in the same row (or in the summary state) and let Svelte 5's\nreactivity carry the update through. The pattern is essentially\n\"editable cells + a `$derived` summary\".\n\n## Validation while editing\n\nPer-column rules: invalid commits get rolled back via `setCellValue`,\nand a sidebar logs the rejection so users can audit what was tried:\n\n<div data-docs-demo=\"24-validation\" data-height=\"440\"></div>\n\nUse `onCellValueChange`: validate, and if invalid, call\n`api.setCellValue(rowIndex, columnId, oldValue)` to undo. The grid\nemits a fresh `onCellValueChange` for the undo write that your\nvalidator can recognise and skip.\n\n## Column pinning + freezing\n\nWide 13-column grid: pin Company on the left and Price on the right;\nthe middle scrolls under sticky edges:\n\n<div data-docs-demo=\"25-column-pinning\" data-height=\"440\"></div>\n\nThe user pins via the column menu - no extra wiring needed if\n`columnFilteringFeature` is registered (the menu lives on the same\nheader button). Or set the whole pinning state programmatically with\n`api.setColumnPinning({ left: ['name'], right: ['total'] })` - pass an\nempty array for a side to unpin it. `api.getColumnPinning()` reads it\nback for persistence.\n\n## List + chips editors\n\nThe two built-in multi-select editors:\n\n<div data-docs-demo=\"26-list-chips-editors\" data-height=\"440\"></div>\n\nAdd `editorType: 'list'` for a single `<select>` or `editorType: 'chips'`\nwith `editorMultiple={true}` for removable tokens. Pass static\n`editorOptions` or a `(row) => options` callback for cascading lists\n(e.g. City options depend on Country).\n\n## Spreadsheet ribbon\n\nAn Excel-style Ribbon UI driving the grid via `SvGridApi`: bold + colour\n+ number format + insert/delete row + sort, plus a live SUM/AVG/COUNT\nstatus bar:\n\n<div data-docs-demo=\"27-spreadsheet-ribbon\" data-height=\"500\"></div>\n\nThe ribbon is a regular Svelte component; every button calls\n`api.setCellValue`, `api.addRow`, `api.setSort`, etc. Status bar\nreads `getDisplayedRows()` for the live aggregate.\n\n## Master / detail\n\nA hierarchical row that expands to reveal a child grid:\n\n<div data-docs-demo=\"08-tree-and-master-detail\" data-height=\"440\"></div>\n\nSame flatten pattern as [tree rows](./rows/tree-rows.md): a flat\n`visibleRows` derivation, plus a custom cell snippet that renders the\ndetail grid inline when the row is expanded.\n\n## Forms-in-grid (master grid + side form)\n\nClick a row to load it into a tabbed detail form on the right; edits\nflow back to the grid live:\n\n<div data-docs-demo=\"40-forms-master-detail\" data-height=\"500\"></div>\n\nPattern: `onActiveCellChange` -> set `activeRowId` -> `draft = $state.snapshot(activeRow)` -> form\nbinds against `draft`. On save, write `draft` back into the rows array.\n**Use `$state.snapshot()`, not `structuredClone()`**, on Svelte 5 state\nproxies - the latter throws `DataCloneError`.\n\n## Saved views / persistence\n\nPivot-lite with chips + saved views stored in localStorage:\n\n<div data-docs-demo=\"36-reporting-workspace\" data-height=\"500\"></div>\n\nThe pattern: a `view: { groupBy, sortBy, filters, columns }` object\nthat you serialise into localStorage under a versioned key\n(`'my-app:view:v1'`). On load, hydrate the state from the saved view\nand call the matching `api.set*` methods.\n\n## Theming studio\n\nLive token playground: brand color, density, radius, font, dark/light,\nzebra. The CSS snippet at the bottom is copy-ready:\n\n<div data-docs-demo=\"37-theming-studio\" data-height=\"540\"></div>\n\nTheming is `--sg-*` custom properties - see [Tailwind integration](./tailwind.md)\nfor the full token list.\n\n## Localisation + RTL switching\n\nSix locales (en, de, fr-CA, ja, ar, he); headers, currencies, dates,\nand the grid's own scrollbar flip:\n\n<div data-docs-demo=\"38-rtl-i18n\" data-height=\"500\"></div>\n\nSet `<html dir=\"...\">` and `<html lang=\"...\">` based on the locale.\nPer-column `format: { type: 'currency', locales }` overrides the\ndocument locale for specific columns.\n\n## Print + boardroom export\n\nQuarterly P&L print pack: cover page, repeat-on-page headers, page-\nsize + orientation, CSV / HTML download, browser-native PDF:\n\n<div data-docs-demo=\"39-print-board-export\" data-height=\"500\"></div>\n\n`api.print({ title, columns, rows, orientation, pageSize })` opens a\nsandbox window with an isolated HTML document and calls `.print()` on\nit. The popup pattern is what isolates your print stylesheet from your\napp's CSS.\n\n## Healthcare EMR (role-based editing)\n\nInpatient board with vitals sparklines, risk score, code status, allergy\nchips, role-based editing (viewer / nurse / physician / admin):\n\n<div data-docs-demo=\"41-healthcare-emr\" data-height=\"500\"></div>\n\nThe role gate uses `editable: (ctx) => roleCanEdit(currentRole, ctx.column.id)`.\nThat lambda runs per-cell, so you get column + role granularity\nwithout a separate config table.\n\n## Live shipment / fleet board\n\nStreaming-style live update at 2-3 Hz with cell-level flash on change,\nETA delta colors, alert chips:\n\n<div data-docs-demo=\"42-logistics-fleet\" data-height=\"500\"></div>\n\nThe pattern: a `$state` rows array that you mutate from a\nWebSocket/SSE handler. The render component diffs at the data-array\nlevel, so reassigning the array (`rows = updated`) is what triggers\nthe visible repaint.\n\n## Compliance / approval queue\n\nL1 / L2 / L3 approval chain with live SLA timer, role-gated approve /\nreturn / reject buttons, immutable case-history audit panel:\n\n<div data-docs-demo=\"43-compliance-queue\" data-height=\"500\"></div>\n\nThis is the pattern for any \"this row needs a decision; some users can\nmake it, some can't\" workflow. Status changes go through a state\nmachine you own; the grid only renders the current state.\n\n## Field service dispatch\n\nDispatcher board: priority + status + tech editable inline, SLA tone\ngauge, today-timeline cell, tech capacity panel, live status stream:\n\n<div data-docs-demo=\"44-field-service\" data-height=\"500\"></div>\n\nSame `editable: (ctx) => ...` per-cell pattern for tech/status. The\ntoday-timeline cell is a positioned-bar in a single wide cell - see\nthe [pivot doc](./pivot.md) for that pattern.\n\n## Gantt chart in a grid\n\nProject plan with a wide custom Schedule cell: bars positioned by\nstart/end %, phase coloring, progress fill, today line, overdue glow:\n\n<div data-docs-demo=\"45-gantt-chart\" data-height=\"540\"></div>\n\nNo special Gantt mode - it's a single wide cell per row whose snippet\npositions absolute bars by `(start - projectStart) / projectSpan * 100`.\nAxis above the grid uses the same math.\n\nFor a real plan - a work-breakdown tree with rolled-up phases, dependency\narrows and a zoomable axis - use [Gantt chart mode](/help/rows/gantt), the\n`gantt` prop's Enterprise renderer, rather than building on this recipe.\n\n## Scheduler (single-day appointments)\n\nProviders as rows, an hour axis, click any appointment to edit it in\nthe side panel. Now-line ticks live:\n\n<div data-docs-demo=\"46-scheduler\" data-height=\"540\"></div>\n\nSame single-wide-cell pattern as the Gantt. The axis-wrap inside the\ngrid wrapper uses `ResizeObserver` so the axis width matches the\nschedule column - that's what keeps the now-line aligned between the\nheader and the cells.\n\n## Trash truck timeline (animated)\n\nPublic-works dispatcher: each truck glides along its day-long route\nwith spinning wheels, stops, and live fill levels:\n\n<div data-docs-demo=\"47-trash-truck-timeline\" data-height=\"540\"></div>\n\nThe mover uses `transition: left 220ms linear` so the new position\nanimates in. The bounce + wheel spin are CSS keyframes; no JS animation\nloop required.\n\n## CRM - sales pipeline\n\nDeal board with stage chips, weighted forecast bar, inline stage +\nprobability editing, deal detail aside with activity feed:\n\n<div data-docs-demo=\"48-crm-sales-pipeline\" data-height=\"540\"></div>\n\nThis is the canonical example of mixing inline edit + a side panel\nthat mirrors the active row.\n\n## Enterprise admin dashboard\n\nCRUD-heavy users board: inline role / status / MFA edit, bulk\nactivate / deactivate / delete, invite dialog, permissions matrix,\nlive audit log:\n\n<div data-docs-demo=\"49-admin-dashboard\" data-height=\"540\"></div>\n\nThe audit log is the recurring pattern: every mutation appends an\nentry to a `$state` array; the right-side panel renders the array.\nDelete + Invite use simple `<dialog>`-style modals.\n\n## E-commerce seller panel\n\nTabbed Amazon-seller view: catalog with SVG thumbnails, inventory bars\nvs reorder threshold, live orders pipeline, pricing rules:\n\n<div data-docs-demo=\"50-seller-panel\" data-height=\"540\"></div>\n\nThe tab strip is just chip buttons that swap which dataset / columns\nthe grid receives. One grid component, four tabs - share styling and\nbehavior without four separate mounts.\n\n## Long-form recipes\n\nThe recipes above pair a paragraph + a demo. These deeper write-ups\nhave their own pages:\n\n- [Persist column layout to URL](../recipes/persist-column-layout-to-url.md) - sort + filter + page in the URL, with debounced replaceState and restore-on-mount.\n- [Two-grid master / detail](../recipes/two-grid-master-detail.md) - one master grid drives a second detail grid; remount semantics and multi-select union.\n- [Bulk-edit selected rows](../recipes/bulk-edit-selected-rows.md) - the standard back-office workflow: pick a field, pick a value, apply to N selected rows. Includes optimistic + rollback patterns.\n- [Server-side filter with TanStack Query](../recipes/server-side-filter-with-tanstack-query.md) - caching, deduplication, cancellation, retries, optimistic edits via mutations.\n\n## See also\n\n- [Architecture overview](./architecture.md) - the layered model that\n makes these recipes composable.\n- [API reference](../reference/index.md) - every method called in the\n recipes above.\n"
|
|
5887
5903
|
},
|
|
5904
|
+
{
|
|
5905
|
+
"slug": "help/review/change-review",
|
|
5906
|
+
"path": "docs/help/review/change-review.md",
|
|
5907
|
+
"title": "Change review - Enterprise",
|
|
5908
|
+
"section": "help/review",
|
|
5909
|
+
"markdown": "# Change review - Enterprise\n\nAn AI helper fills 900 empty cells, an agent cleans up a CRM export, an import\nupdates 2,000 rows. None of those writes was typed by the person who owns the\ndata, and none of them should land before someone has looked. Change review\nholds such writes as **proposals**, apart from the data, groups them by what\nthey do, and lets a person accept or reject a group at a time. Only accepted\nvalues are written, and each decision is one Ctrl+Z.\n\n```ts\nimport { createReview, reviewSmartFill, SvReviewPanel } from '@svgrid/enterprise/review'\n```\n\n<div data-docs-demo=\"702-change-review\" data-height=\"620\"></div>\n\nIn the demo, **Run cleanup agent** proposes fixes to a customer table. Nothing\nis written until you accept a group in the panel. Edit a cell that has a\nproposal before accepting it and the proposal is marked stale. **Import\ncrm-update.csv** proposes a different region for two customers the agent also\nfilled, and the panel asks which one to keep.\n\n## A grid with a review\n\n```svelte\n<script lang=\"ts\">\n import { SvGrid, type SvGridApi } from '@svgrid/grid'\n import { createReview, SvReviewPanel } from '@svgrid/enterprise/review'\n\n let rows = $state(customers)\n let api = $state<SvGridApi<any, Customer> | null>(null)\n\n const review = createReview<Customer>({\n api: () => api,\n setRows: (next) => (rows = next),\n onCommit: async (accepted) => {\n await fetch('/api/customers/bulk', { method: 'PATCH', body: JSON.stringify(accepted) })\n },\n })\n</script>\n\n<div class=\"layout\">\n <SvGrid\n data={rows}\n columns={review.columns(columns)}\n getRowId={(r) => r.id}\n conditionalFormats={review.formats}\n onApiReady={(a) => (api = a)}\n />\n <SvReviewPanel {review} />\n</div>\n```\n\nThree things are required:\n\n- **`getRowId` on the grid.** Proposals are keyed by row id, because row\n positions move on sort, filter and insert. `createReview` reads the function\n from the grid and throws a clear error when it is missing.\n- **The app owns the rows.** `setRows` replaces the array the grid is given,\n and it must apply synchronously. Reads go through `api.getData()`, which\n includes the grid's own writes (a paste, a fill, `addRows`), so building the\n next array from it carries those forward.\n- **The grid api**, passed as a getter, because `onApiReady` fires after mount.\n\n## Adding proposals\n\nAnything can add a set of proposals. Each one names the row, the field, the\nvalue it saw (`before`) and the value it proposes (`after`):\n\n```ts\nreview.add({\n source: { kind: 'agent', id: 'crm-cleanup', label: 'Cleanup agent' },\n proposals: [\n { rowId: 'c-104', field: 'company', before: 'Acme Inc.', after: 'Acme Inc' },\n { rowId: 'c-221', field: 'phone', before: '(555) 123-4567', after: '555-123-4567', reason: 'one phone format' },\n ],\n})\n```\n\n`confidence` (0 to 1) and `reason` are optional and show in the panel.\nProposals whose `after` equals `before` are skipped. A newer proposal from the\nsame source for the same cell replaces the older one. Two sources proposing\ndifferent values for one cell is a **conflict**: neither can be accepted by a\ngroup action until a person keeps one.\n\n### From the AI helpers\n\nThe AI helpers in `@svgrid/grid` return predictions keyed by data index.\n`reviewSmartFill` and `reviewClassify` snapshot the data before the call,\nresolve each index to its row id, drop indices the helper was not asked about,\nand add the result:\n\n```ts\nconst result = await reviewSmartFill(review, api, {\n field: 'region',\n examples: [{ input: { country: 'Germany' }, output: 'EMEA' }],\n})\nresult.dropped // predictions that pointed at rows outside the request\n```\n\n`fromSmartFill(result, snapshot, { api })` and `fromClassify` do the same for a\nresult you already have; pass the snapshot you took before calling the helper.\n\n### From an import or a sync\n\n`fromRows` diffs incoming rows against the grid's data by a key field and\nproposes one change per field that differs:\n\n```ts\nconst set = fromRows(imported.rows, {\n api,\n key: 'id',\n source: { kind: 'import', id: file.name, label: file.name },\n})\nreview.add(set)\nset.unmatched // incoming rows with no match; adding rows is not proposed yet\n```\n\n## How proposals are grouped\n\nThe panel never shows 2,000 cells in a list. `review.groups()` puts every\npending proposal in one group by the change it makes. The first four kinds are\n**rule groups**: every member is proven to follow the rule. The rest are\n**judgment groups**, where a person has to look.\n\n| Kind | Rule | Label in the panel |\n|---|---|---|\n| `whitespace` | `after` is `before` trimmed or with spaces collapsed | Trim spaces in Company |\n| `case` | same letters, different case | Change Email to lower case |\n| `format` | same characters apart from punctuation, the same unambiguous date, or text that parses to the number | Reformat Phone as 999-999-9999 |\n| `scale` | `after / before` is one number, 5 or more members | Divide Revenue by 100 |\n| `same-mapping` | several `before` values each mapped to one `after` at least twice | Country: 6 values → United States |\n| `fill-empty` | blank `before`, one group per proposed value | Fill empty Region with EMEA |\n| `constant-target` | many different `before` values, one `after` | Set Status to Closed |\n| `unpatterned` | everything else, per field | Notes: no shared pattern |\n\nA few cases are kept out of the rule groups on purpose. `\"3.5\"` to `\"35\"` keeps\nevery digit but changes the number, so it is not a format change. `03/05/2024`\ncould be March or May, so a reformat of it is never proven. A rule group proves\nthat every member follows its rule, not that the rule is right: an agent that\ndivides by 10 where it should divide by 100 shows up as its own \"Divide Revenue\nby 10\" group, labelled for what it does.\n\nThe panel lists the risky groups first: unpatterned, then one target from many\nvalues, then groups with low confidence, then the rest by size. Each group\ncarries a sample to check: every member below 60% confidence (up to ten), then\nmembers spread across the group. An unpatterned group lists every member.\n`same-mapping` and `constant-target` groups show which `before` values they\nmap, so \"everything became Canada\" is visible at a glance.\n\n## What the grid shows\n\n`review.formats` tints every cell with a pending proposal and draws a dot before\nits value, so the mark is never colour alone. Pass it as `conditionalFormats`,\nconcatenated with your own formats if you have them. Theme the tint with\n`--sg-review-pending-bg`. A cell two sources disagree on gets a red wash and a\n\"!\" instead (`--sg-review-conflict-bg`), so the grid shows where the panel's\nconflicts are.\n\n`review.columns(columns)` draws the proposal inside the cell: the proposed\nvalue, then the current value struck through. It does this by wrapping the\ncolumn's `cell`, and only for columns where that leaves the rest of the column\nas it was: columns with a `cell` of their own, and plain text columns.\nCheckbox, list, chips and boolean columns, and field types with a cell of their\nown, keep their cell as it is and show the proposed value after it (\"→ Closed\").\n\n## Deciding\n\n```ts\nconst outcome = await review.acceptGroup(group.key, group.ids)\n// { accepted: [...], rejected: [], stale: [...], skipped: [...], error? }\n```\n\nOn accept, for each proposal:\n\n1. An open cell editor is committed first, so a value someone just typed wins.\n Under `fullRowEditing`, the row being edited is left pending instead.\n2. If the cell no longer holds `before`, the proposal becomes **stale** and is\n not written.\n3. `onCommit` receives the remaining proposals. Throw or reject to keep them\n pending; nothing is written.\n4. The cells are checked again, because a person could edit one while\n `onCommit` was saving.\n5. One `setRows` call writes every accepted value.\n6. One undo step is recorded. Ctrl+Z in the grid writes the old values back,\n by row id, so it works with paging and filters on, and returns the proposals\n to pending. A cell edited after the accept is left as it is.\n\n`acceptGroup` and `rejectGroup` take the ids that were shown, so a proposal\nthat arrived after the panel rendered is never decided unseen.\n\n### Server row model\n\nWith the server row model there is no app array to replace. Pass the\ncontroller instead of `setRows`; `onCommit` is then required:\n\n```ts\nconst review = createReview({\n api: () => api,\n server: controller,\n onCommit: (accepted) => saveToServer(accepted),\n})\n```\n\nAccept saves through `onCommit` and refreshes the controller. Undo saves the\ninverse (`before` and `after` swapped) and refreshes again. The backend decides\nstaleness there.\n\n## SvReviewPanel\n\n| Prop | Type | Default | |\n|---|---|---|---|\n| `review` | `Review` | required | What `createReview` returned. |\n| `title` | `string` | `'Review changes'` | The panel heading. |\n| `confirmOver` | `number` | `50` | Ask before deciding more than this many at once. |\n| `onDecide` | `(outcome) => void` | | Called after each decision. |\n\n**Accept rule groups** accepts every rule group at once (trims, case changes,\nreformats, one numeric factor), the changes that are proven by their rule, and\nleaves the groups that need a person. It is the panel's primary button, and\nrule groups are the only ones marked, with a \"Rule\" badge. **Accept all** is\nthe primary button only when every group left is a rule group: deciding\neverything unseen is what a review is there to prevent.\n\nA line in an open group names its row, then the change, then the reason and\nconfidence the source gave. The name is the row's first visible text column\n(the company, say), and a line leaves it out when that column is the one being\nchanged, since the old value already names the row. Set `rowLabel` on\n`createReview` to choose it yourself:\n\n```ts\nconst review = createReview<Customer>({\n api: () => api,\n setRows: (next) => (rows = next),\n rowLabel: (row) => `${row.company} (${row.city})`,\n})\n```\n\nA click on a line shows that row in the grid, and the row lights up for a\nmoment so the eye finds it. A value is quoted only where the quotes say\nsomething: around spaces at its ends (shown as dots), or when text reads as a\nnumber or a boolean.\n\nEach line of an open group has its own accept and reject, for a group that is\nmostly right: reject the two wrong guesses, then accept the group. A judgment\ngroup lists its sample first; **Show all** lists every change in it, up to\n200. A decision can move what is left of a group under another heading (two\n\"EMEA\" fills less one is a single fill, pooled with the others), and the open\ngroup follows its remaining changes rather than closing.\n\nIt is a plain panel, not a drawer, so the grid stays usable beside it. Inside\nthe group list, **J** and **K** move between groups, **Enter** opens one, **A**\naccepts it and **R** rejects it. \"Show in grid\" goes to the group's next row\nwithout moving the active cell: with client paging it turns to the row's page\nfirst (`api.getRowPosition`), then scrolls to it. Rows a filter hides are\ncounted, not shown. With grouping, where pages count groups, it stays on the\ncurrent page.\n\n**Only rows with changes** narrows the grid to the rows with a pending or\nconflicting proposal, on top of whatever the user filtered: it adds one\ncondition to the advanced filter with AND, and switching it off takes that\ncondition back out and leaves the rest. Rows leave the view as their\nproposals are decided, like an inbox. From code:\n`review.showPendingOnly(true)`, and `review.pendingOnly` tells whether it is\non. It needs the advanced filter engine, which it turns on itself.\n\n## Agents\n\n`createGridTools` gives an AI agent four tools over the grid's data. None of\nthem writes the data: the agent's edits arrive in the review like any other\nproposals, and a person decides.\n\n<div data-docs-demo=\"704-agent-review-desk\" data-height=\"700\"></div>\n\nIn the demo a scripted CRM agent calls these tools step by step; each step\nshows the tool call it made. The Log tab lists every decision as\n`onDecision` reports it.\n\n| Tool | What it does |\n|---|---|\n| `grid_describe` | The columns (field, header, type), the row count, and which fields the agent may edit. |\n| `grid_query_rows` | Rows matching `where` conditions (`equals`, `contains`, `blank`, `gt`, ...), with their `rowId`, paged and capped at `maxRows`. |\n| `grid_propose_edits` | Adds edits as proposals, with a reason and a confidence. Unknown rows, fields the agent may not edit, and edits that change nothing are skipped and reported. |\n| `grid_review_status` | How many of the agent's proposals are pending, accepted, rejected or stale, so it can learn from the review. |\n\n```ts\nimport { createGridTools, registerWebMcpTools } from '@svgrid/enterprise/review'\n\nconst tools = createGridTools({\n review,\n api: () => api,\n fields: ['region', 'phone'], // what the agent may propose edits to\n source: { kind: 'agent', id: 'crm-agent', label: 'CRM agent' },\n})\n```\n\nEach tool is `{ name, description, inputSchema, execute }`: hand them to the\ntool loop of your LLM SDK, or to an MCP server of your own.\n`registerWebMcpTools(tools)` registers them with the browser's WebMCP API\n(`document.modelContext`), so an agent driving the page can call them. WebMCP\nis a draft; where a browser does not have it, the call returns\n`{ supported: false }` and does nothing.\n\nA model's input is not trusted. One `grid_propose_edits` call carries at most\n`maxEdits` edits (500 by default) and a larger one is refused. A value that\ndoes not fit its column (text for a number, an object for a text cell, a list\nfor a single value) is skipped and reported back, not proposed.\n\n## Audit log and revert\n\n`onDecision` is called after every accept and reject, and after their undo and\nredo, with copies of the proposals it moved and who decided. Write these to\nyour own audit log:\n\n```ts\ncreateReview({\n api: () => api,\n setRows: (next) => (rows = next),\n user: currentUser.email,\n onDecision: (d) => audit.write({ action: d.action, by: d.by, at: d.at, changes: d.proposals }),\n})\n```\n\n`review.log()` lists the decided proposals in this session, in the order they\nwere decided.\n\nIf an undo or redo has to save through `onCommit` and the save fails, nothing\nis written and the decision stands. `onError(error, 'undo' | 'redo')` is\ncalled, `review.lastError` holds it, and the panel says \"Undo not saved\".\n\nCtrl+Z covers the last decisions. To take back a whole set later,\n`review.revertSet(setId)` adds a new set that proposes each accepted value's\nreverse. It is reviewed and accepted like any other, so a cell edited after the\noriginal accept is not overwritten.\n\n## Routing to an approver\n\n`review.toJSON({ setIds })` exports sets with their proposals as plain JSON.\nOn the approver's page, `review.merge(json)` adds them beside what that review\nalready holds. A cell that also has a pending proposal there from another\nsource becomes a conflict. `review.load(json)` replaces everything instead.\n\nAn export can come from another person, another session or an agent, so both\ncheck it first. Something that is not an export (`{ v: 1, sets: [...] }`)\nthrows and leaves the review as it was; a proposal with no id, row, field or a\nknown status is dropped. Both return `{ dropped }`.\n\nA person's own staged edits can take the same route. `fromStaged` turns a\n`createStagedEditing` buffer into proposals. Staged edits have already been\nwritten into the grid, so revert the stage first:\n\n```ts\nconst changes = stage.changes()\nstage.revert((rowIndex, columnId, value) => api.setCellValue(rowIndex, columnId, value))\nreview.add(fromStaged(changes, { api, source: { kind: 'user', id: me.id, label: `${me.name} (staged)` } }))\nconst forApprover = JSON.stringify(review.toJSON({ setIds: [review.sets().at(-1)!.id] }))\n```\n\n## At scale\n\nA test in the package runs 100,000 rows and 20,000 proposals through every\nstep and fails if one becomes slow. Measured in jsdom on a development\nmachine (2026-10-24):\n\n| Step | Time |\n| --- | --- |\n| Add 20,000 proposals | 88 ms |\n| Group them | 55 ms |\n| Build the tint rules | 8 ms |\n| Mark 1,000 cards | 24 ms |\n| Accept all 20,000 (one `setRows`) | 140 ms |\n| Undo, then redo | 71 ms, 96 ms |\n\nClustering, the stale checks and the writes are each a single pass over the\nproposals and the rows; nothing compares every proposal with every row.\n\n## With SvGrid Base\n\n`SvBase` hands any prop it does not use to its grid, so a review attaches the\nsame way. Add `onApply: baseReviewApplied(...)` so an accept does what an edit\ndoes in a base: \"Last modified time\" and \"Last modified by\" fields are stamped\nin the same write, and the record's activity credits the change to what\nproposed it and to the person who accepted it (\"CRM agent (accepted by Dana)\").\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, baseReviewApplied } from '@svgrid/enterprise/base'\n import { createReview, SvReviewPanel } from '@svgrid/enterprise/review'\n\n enableBase()\n let records = $state(initialRecords)\n let api = $state(null)\n const review = createReview({\n api: () => api,\n setRows: (next) => (records = next),\n onApply: baseReviewApplied(() => api),\n })\n</script>\n\n<SvBase\n data={records}\n columns={review.columns(columns)}\n conditionalFormats={review.formats}\n primaryField=\"name\"\n onApiReady={(a) => (api = a)}\n/>\n<SvReviewPanel {review} />\n```\n\nWhat a base shows:\n\n- **The proposed value in the cell** for field types that draw no cell of\n their own: single line text, long text, date, number, currency, percent,\n duration, formula, autonumber, lookup, rollup, count, created time and last\n modified time.\n- **The proposed value beside the cell** for types with a cell of their own:\n attachment, checkbox, single and multiple select, user, phone, email, URL,\n barcode, button, rating, link, created by and last modified by, and long\n text set to rich text or a percent drawn as a bar. The cell draws as it\n always does and \"→ Closed\" follows it, read through the field's own\n formatter, so a person shows by name.\n- **Cards and events too.** Kanban and gallery cards with pending proposals\n show \"2 proposed\", and calendar events a dot, with the fields and values on\n hover. A form adds new records, so it has nothing to mark.\n- **Sync.** With `createBaseSync`, an accepted value is a change like any\n other and is saved with the rest. Changes made elsewhere are still marked as\n before; a review is the step before that, where an agent proposes and a\n person decides.\n\nWith several tables (`tables`), keep one review per table: proposals are keyed\nby record id, and ids can repeat across tables. Give the active table's review\nto the grid and write into that table's rows:\n\n```ts\nconst review = createReview({\n api: () => api,\n setRows: (next) => (tables = tables.map((t) => (t.id === 'tasks' ? { ...t, data: next } : t))),\n onApply: baseReviewApplied(() => api),\n})\n```\n\n## Wording and languages\n\nEvery string the review shows comes from one message map with English\ndefaults: the panel, the group labels, the card and cell marks, and the notes\non proposals that were not written. Pass any subset to `createReview`, and\nunset keys stay English. `{name}` placeholders are filled in; `REVIEW_MESSAGES`\nlists every key with its English text.\n\n```ts\nconst review = createReview({\n api: () => api,\n setRows: (next) => (rows = next),\n messages: {\n acceptAll: 'Alle annehmen',\n changes: '{count} Änderungen',\n labelWhitespace: 'Leerzeichen in {field} kürzen',\n cardProposed: '{count} vorgeschlagen',\n },\n})\n```\n\n`<SvReviewPanel messages={...}>` overrides the review's wording for one panel.\n\n## Licensing\n\nChange review is part of SvGrid Enterprise. Without a license key it runs with\na watermark and a one-time notice. It adds nothing to `@svgrid/grid`: the tint\nis `conditionalFormats`, the proposed value is a wrapped `cell`, and the undo\nstep goes through the grid's public command context.\n\n## See also\n\n- [AI helpers](../ai.md)\n- [Undo and redo](../editing/undo-redo.md)\n- [Conditional formatting](../cells/conditional-formatting.md)\n- [Server-side row model](../server/server-row-model.md)\n"
|
|
5910
|
+
},
|
|
5888
5911
|
{
|
|
5889
5912
|
"slug": "help/rows/accessing-rows",
|
|
5890
5913
|
"path": "docs/help/rows/accessing-rows.md",
|
|
@@ -7626,7 +7649,7 @@ export const docs = [
|
|
|
7626
7649
|
"path": "docs/reference/SvGridApi.md",
|
|
7627
7650
|
"title": "SvGridApi reference",
|
|
7628
7651
|
"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"
|
|
7652
|
+
"markdown": "# `SvGridApi` reference\n\nThe imperative API exposed via `<SvGrid onApiReady={(api) => ...}>`.\nUse it for data, column, filter, sort, group, selection, and\nvisibility operations from outside the component.\n\n```ts\nimport type { SvGridApi } from '@svgrid/grid'\n\nlet api = $state<SvGridApi<typeof features, Order> | null>(null)\n```\n\n```svelte\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onApiReady={(next) => (api = next)}\n/>\n\n<button onclick={() => api?.addRow({ /* ... */ })}>Add row</button>\n```\n\n## Cells\n\n### `getCellValue(rowIndex, columnId)`\n\n```ts\ngetCellValue(rowIndex: number, columnId: string): unknown\n```\n\nRead a cell value from the underlying data. Returns `undefined` when\neither argument doesn't resolve.\n\n### `setCellValue(rowIndex, columnId, value)`\n\n```ts\nsetCellValue(rowIndex: number, columnId: string, value: unknown): void\n```\n\nWrite a cell value through the column's `field`. Triggers a re-render.\nDoes NOT fire `onCellValueChange` - that callback is for **user**\nedits.\n\n## Rows\n\n### `addRow(row, position?)`\n\n```ts\naddRow(row: TData, position?: 'top' | 'bottom' | number): void\n```\n\n`position` defaults to `'bottom'`. A numeric index inserts before that\nindex.\n\n### `addRows(rows, position?)`\n\n```ts\naddRows(rows: ReadonlyArray<TData>, position?: 'top' | 'bottom' | number): void\n```\n\nBatched insert. Cheaper than calling `addRow` in a loop for hundreds\nof rows.\n\n### `removeRow(rowIndex)` / `removeRows(rowIndices)`\n\n```ts\nremoveRow(rowIndex: number): void\nremoveRows(rowIndices: ReadonlyArray<number>): void\n```\n\nRemove by data-array index (the same index `onCellValueChange` reports).\n\n## Columns\n\n### `addColumn(column, position?)` / `addColumns(columns, position?)`\n\n```ts\naddColumn(column: ColumnDef<TFeatures, TData>, position?: 'left' | 'right' | number): void\naddColumns(columns: ReadonlyArray<ColumnDef<TFeatures, TData>>, position?: 'left' | 'right' | number): void\n```\n\n`position` defaults to `'right'`.\n\n### `removeColumn(columnId)`\n\n```ts\nremoveColumn(columnId: string): void\n```\n\nBy id (or `field` when no id was provided).\n\n## Visibility\n\n### `setColumnVisible(columnId, visible)` / `isColumnVisible(columnId)`\n\n```ts\nsetColumnVisible(columnId: string, visible: boolean): void\nisColumnVisible(columnId: string): boolean\n```\n\nHidden columns stay in the column array but don't render.\n\n## Sort\n\n### `setSort(columnId, direction)`\n\n```ts\nsetSort(columnId: string, direction: 'asc' | 'desc' | null): void\n```\n\nReplaces any existing sort. Pass `null` to clear sort on that column.\nMulti-sort through the API is on the\n[Missing features](../help/missing-features.md) list - the user can\nbuild it themselves with Shift-click on headers.\n\n### `clearSort()`\n\n```ts\nclearSort(): void\n```\n\nClear all sort clauses.\n\n## Group\n\n### `setGroupBy(columnIds)`\n\n```ts\nsetGroupBy(columnIds: ReadonlyArray<string>): void\n```\n\nGroup by zero or more columns. Replaces any existing group config.\n\n## Filter\n\n### `setFilter(columnId, filter)`\n\n```ts\nsetFilter(\n columnId: string,\n filter: { operator: SvGridFilterOperator; value?: string } | null,\n): void\n```\n\nWhere `SvGridFilterOperator` is:\n\n```ts\ntype SvGridFilterOperator =\n | 'contains' | 'equals' | 'startsWith'\n | 'greaterThan' | 'lessThan' | 'isBlank'\n```\n\nPass `null` to clear.\n\n### `clearFilter(columnId)`\n\n```ts\nclearFilter(columnId: string): void\n```\n\nClear a single column's filter. (A `clearAllFilters()` helper is on\nthe [Missing features](../help/missing-features.md) list.)\n\n## Data snapshot\n\n### `getData()`\n\n```ts\ngetData(): ReadonlyArray<TData>\n```\n\nSnapshot of the current internal data array - the grid's working\ncopy, which reflects every cell edit and `addRow` / `removeRow` since\nmount.\n\n### `getDisplayedRows()`\n\n```ts\ngetDisplayedRows(): ReadonlyArray<TData>\n```\n\nReturns the rows that are currently **visible** in the grid - after\nfilter, sort, and pagination. Use for `pro.exportData(...)` when you\nwant to export the current view.\n\n### `getRowPosition(rowId)`\n\n```ts\ngetRowPosition(rowId: string): number | null\n```\n\nWhere a row sits in the filtered, sorted rows across every page (group\nbanners included, as paging counts them), or `null` when a filter hides\nit. With client paging, `Math.floor(position / pageSize)` is its page:\n\n```ts\nconst position = api.getRowPosition('ord-1042')\nif (position !== null) {\n const { pageSize } = api.getPageInfo()\n api.setPage(Math.floor(position / pageSize))\n api.scrollToRow(position % pageSize)\n}\n```\n\n## Enterprise extensions\n\nAfter `installEnterprise(api)`, the same object also exposes:\n\n```ts\napi.exportData(opts) // see Enterprise export reference\napi.print(opts)\napi.importData(opts)\napi.ai.filter(...)\napi.ai.smartFill(...)\napi.ai.summarize(...)\napi.ai.classify(...)\napi.pivot.build(config)\napi.pivot.buildFrom(data, config)\n```\n\nSee [Enterprise reference](./enterprise.md).\n"
|
|
7630
7653
|
},
|
|
7631
7654
|
{
|
|
7632
7655
|
"slug": "reference/auto/index",
|
|
@@ -8354,8 +8377,8 @@ export const apiReference = {
|
|
|
8354
8377
|
]
|
|
8355
8378
|
};
|
|
8356
8379
|
export const apiSurface = {
|
|
8357
|
-
"gridVersion": "3.0.
|
|
8358
|
-
"enterpriseVersion": "3.1.
|
|
8380
|
+
"gridVersion": "3.0.22",
|
|
8381
|
+
"enterpriseVersion": "3.1.23",
|
|
8359
8382
|
"grid": {
|
|
8360
8383
|
"values": [
|
|
8361
8384
|
"ALL_FILTER_OPERATORS",
|
|
@@ -10704,6 +10727,7 @@ export const apiSurface = {
|
|
|
10704
10727
|
"@svgrid/enterprise/license",
|
|
10705
10728
|
"@svgrid/enterprise/pivot",
|
|
10706
10729
|
"@svgrid/enterprise/print",
|
|
10730
|
+
"@svgrid/enterprise/review",
|
|
10707
10731
|
"@svgrid/enterprise/server",
|
|
10708
10732
|
"@svgrid/enterprise/sheet",
|
|
10709
10733
|
"@svgrid/enterprise/studio",
|
|
@@ -11931,6 +11955,7 @@ export const apiSurface = {
|
|
|
11931
11955
|
"getPageInfo",
|
|
11932
11956
|
"getRowHeight",
|
|
11933
11957
|
"getRowId",
|
|
11958
|
+
"getRowPosition",
|
|
11934
11959
|
"getSavedCharts",
|
|
11935
11960
|
"getSelected",
|
|
11936
11961
|
"getSelectedLast",
|
package/dist/preview.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare const UI_MIME_TYPE = "text/html;profile=mcp-app";
|
|
|
8
8
|
* start failing in a way nobody is watching for. `tools/mcp-tools.test.ts` checks these
|
|
9
9
|
* against the workspace so they cannot quietly rot either.
|
|
10
10
|
*/
|
|
11
|
-
export declare const PREVIEW_GRID_WC_VERSION = "3.0.
|
|
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/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.29",
|
|
9
9
|
"description": "Model Context Protocol server for SvGrid, the Svelte 5 data grid: checks the code your AI writes against the real API surface, plus version-pinned docs, API reference and 373 demo sources.",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"author": "jQWidgets <sales@jqwidgets.com>",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"zod": "^3.23.8"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
|
-
"@svgrid/enterprise": "^3.1.
|
|
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.29",
|
|
7
7
|
"websiteUrl": "https://svgrid.com/docs/help/mcp-server/",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/sv-grid/sv-grid",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"registryType": "npm",
|
|
16
16
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
17
17
|
"identifier": "@svgrid/mcp",
|
|
18
|
-
"version": "3.0.
|
|
18
|
+
"version": "3.0.29",
|
|
19
19
|
"runtimeHint": "npx",
|
|
20
20
|
"transport": {
|
|
21
21
|
"type": "stdio"
|